context
stringlengths
2.52k
185k
gt
stringclasses
1 value
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; // ReSharper disable once CheckNamespace namespace WebTrackr.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } var controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; var actionName = api.ActionDescriptor.ActionName; var parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; var enumerable = parameterNames as IList<string> ?? parameterNames.ToList(); var type = ResolveType(api, controllerName, actionName, enumerable, sampleDirection, out formatters); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, enumerable, sampleDirection); var samples = actionSamples.ToDictionary(actionSample => actionSample.Key.MediaType, actionSample => 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)) { var sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (var mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { var sample = GetActionSample(controllerName, actionName, enumerable, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (var factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } // ReSharper disable once EmptyGeneralCatchClause catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { var controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; var actionName = api.ActionDescriptor.ActionName; var parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type var 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: var requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; // ReSharper disable once RedundantCaseLabel case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } // ReSharper disable once RedundantAssignment 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; var reader = new StreamReader(ms); var serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { var aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object var objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { var 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 { var 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) { var parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); return from sample in ActionSamples let sampleKey = sample.Key where 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 select sample; } private static object WrapSampleIfString(object sample) { var stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using FlatRedBall; using FlatRedBall.Gui; using System.Collections.Generic; using FlatRedBall.Instructions; using FlatRedBall.Input; using FlatRedBall.Instructions.ScriptedAnimations; using FlatRedBall.Utilities; namespace InstructionEditor.Gui { /// <summary> /// Summary description for ListBoxWindow. /// </summary> public class ListBoxWindow : Window { #region Fields CollapseListBox mInstructionSetListBox; Button mAddKeyframeListButton; Button mAddKeyframeButton; ComboBox mTimelineSelection; ListDisplayWindow mAnimationSequenceListBox; #endregion #region Properties public CollapseListBox InstructionSetListBox { get { return mInstructionSetListBox; } } //public Button AddKeyframeListButton //{ // get { return mAddKeyframeListButton; } //} #endregion #region Event Methods private void AddKeyframeListClick(Window callingWindow) { if (EditorData.EditorLogic.CurrentInstructionSet == null) { GuiManager.ShowMessageBox("Currently the InstructionEditor is under \"Current'\" editing mode." + " To add an Animation, you must have a selected object first.", "Error"); return; } TextInputWindow tiw = GuiManager.ShowTextInputWindow("Enter a name for the new Animation:", "Enter name"); if (GuiData.TimeLineWindow.InstructionMode == InstructionMode.Current) { if (EditorData.EditorLogic.CurrentInstructionSet != null) { tiw.Text = "Keyframe List " + EditorData.EditorLogic.CurrentInstructionSet.Count; } else { tiw.Text = "Keyframe List " + 0; } } else { tiw.Text = "Animation " + EditorData.GlobalInstructionSets.Count; } tiw.OkClick += new GuiMessage(AddKeyframeListOk); } private void AddKeyframeListOk(Window callingWindow) { string name = ((TextInputWindow)callingWindow).Text; if (GuiData.TimeLineWindow.InstructionMode == InstructionMode.All) { AnimationSequence newSequence = new AnimationSequence(); newSequence.Name = name; EditorData.GlobalInstructionSets.Add(newSequence); } else { KeyframeList keyframeList = new KeyframeList(); EditorData.EditorLogic.CurrentInstructionSet.Add(keyframeList); keyframeList.Name = name; //GuiData.ListBoxWindow.InstructionSetListBox.HighlightItem(item); } GuiData.ListBoxWindow.UpdateLists(); } private void AddKeyframe(Window callingWindow) { #region See if adding is allowed (Are there objects to record). If not, show a message if (EditorData.CurrentSpriteMembersWatching.Count == 0 && EditorData.CurrentSpriteFrameMembersWatching.Count == 0 && EditorData.CurrentPositionedModelMembersWatching.Count == 0 && EditorData.CurrentTextMembersWatching.Count == 0) { GuiManager.ShowMessageBox("There are no members being recorded. Try opening the " + "\"used members\" window through Window->Used Members menu item.", "No members"); return; } if (GuiData.TimeLineWindow.InstructionMode == InstructionMode.Current) { if (EditorData.EditorLogic.CurrentKeyframeList == null) { GuiManager.ShowMessageBox("There is no Keyframe List currently selected", "Error"); return; } if (EditorData.EditorLogic.CurrentSprites.Count == 0 && EditorData.EditorLogic.CurrentSpriteFrames.Count == 0 && EditorData.EditorLogic.CurrentPositionedModels.Count == 0 && EditorData.EditorLogic.CurrentTexts.Count == 0) { GuiManager.ShowMessageBox("No object is selected. Select an object to record.", "No selected object."); return; } } else if (GuiData.TimeLineWindow.InstructionMode == InstructionMode.All) { if (EditorData.EditorLogic.CurrentAnimationSequence == null) { GuiManager.ShowMessageBox("There is no Animation currently selected", "Error"); return; } } #endregion if (GuiData.TimeLineWindow.InstructionMode == InstructionMode.All) { KeyframeListSelectionWindow klsw = new KeyframeListSelectionWindow(GuiManager.Cursor); GuiManager.AddWindow(klsw); klsw.PopulateComboBoxes(EditorData.BlockingScene, EditorData.ObjectInstructionSets); klsw.OkClick += AddKeyframeToGlobalInstrutionSet; } else { TextInputWindow tiw = GuiManager.ShowTextInputWindow("Enter a name for the new keyframe:", "Enter name"); tiw.Text = "Keyframe " + EditorData.EditorLogic.CurrentKeyframeList.Count; tiw.OkClick += new GuiMessage(AddKeyframeOk); } } public static void AddKeyframeOk(Window callingWindow) { if (EditorData.EditorLogic.CurrentKeyframeList == null) { GuiManager.ShowMessageBox("There is no Keyframe List currently selected", "Error"); return; } if (EditorData.CurrentSpriteMembersWatching.Count == 0 && EditorData.CurrentSpriteFrameMembersWatching.Count == 0 && EditorData.CurrentPositionedModelMembersWatching.Count == 0 && EditorData.CurrentTextMembersWatching.Count == 0) { GuiManager.ShowMessageBox("There are no members being recorded. Try opening the " + "\"used members\" window through Window->Used Members menu item.", "No members"); return; } InstructionList instructionList = new InstructionList(); instructionList.Name = ((TextInputWindow)callingWindow).Text; double timeToExecute = GuiData.TimeLineWindow.timeLine.CurrentValue; EditorData.AddInstructionsToList(instructionList, timeToExecute); GuiData.TimeLineWindow.UpdateToCurrentSet(); EditorData.EditorLogic.CurrentKeyframeList.Add(instructionList); GuiData.ListBoxWindow.UpdateLists(); } public static void AddKeyframeToGlobalInstrutionSet(Window callingWindow) { KeyframeList keyframeList = ((KeyframeListSelectionWindow)callingWindow).SelectedKeyframeList; INameable targetNameable = ((KeyframeListSelectionWindow)callingWindow).SelectedNameable; TimedKeyframeList timedKeyframeList = new TimedKeyframeList(keyframeList, targetNameable.Name); timedKeyframeList.TimeToExecute = GuiData.TimeLineWindow.CurrentValue; // Add the selected KeyframeList to the Global InstructionSet EditorData.EditorLogic.CurrentAnimationSequence.Add(timedKeyframeList); } private void AdjustPositionsAndScales(Window callingWindow) { mInstructionSetListBox.SetPositionTL(ScaleX, ScaleY - 2.3f); mInstructionSetListBox.ScaleX = ScaleX - .5f; mInstructionSetListBox.ScaleY = ScaleY - 3f ; mAnimationSequenceListBox.X = mInstructionSetListBox.X; mAnimationSequenceListBox.Y = mInstructionSetListBox.Y; mAnimationSequenceListBox.ScaleX = mInstructionSetListBox.ScaleX; mAnimationSequenceListBox.ScaleY = mInstructionSetListBox.ScaleY; mAddKeyframeListButton.ScaleX = 6.2f; mAddKeyframeListButton.ScaleY = 2.2f; mAddKeyframeListButton.SetPositionTL(6.8f, 2 * ScaleY - 2.9f); mAddKeyframeButton.ScaleX = 6.2f; mAddKeyframeButton.ScaleY = 2.2f; mAddKeyframeButton.SetPositionTL(19.4f, 2 * ScaleY - 2.9f); } private void AnimationSequenceFocusUpdate(IInputReceiver inputReceiver) { Keyboard keyboard = InputManager.Keyboard; #region Delete if (keyboard.KeyPushed(Microsoft.Xna.Framework.Input.Keys.Delete)) { // Check to see which object is current and delete it // If a CurrentTimedKeyframeList is not null, then the CurrentAnimationSequence is also not null. // Therefore, always check "bottom up" or else the wrong thing will be deleted. if (EditorData.EditorLogic.CurrentTimedKeyframeList != null) { EditorData.EditorLogic.CurrentAnimationSequence.Remove(EditorData.EditorLogic.CurrentTimedKeyframeList); UpdateLists(); } else if (EditorData.EditorLogic.CurrentAnimationSequence != null) { EditorData.GlobalInstructionSets.Remove(EditorData.EditorLogic.CurrentAnimationSequence); EditorData.EditorLogic.CurrentAnimationSequence = null; UpdateLists(); } } #endregion } private void DoubleClickAnimationSequenceListBox(Window callingWindow) { object highlightedObject = mAnimationSequenceListBox.GetFirstHighlightedObject(); if (highlightedObject != null) { if (highlightedObject is AnimationSequence) { // Any logic here? } else if (highlightedObject is TimedKeyframeList) { // Find the object that this references and select it. TimedKeyframeList asTimedKeyframeList = highlightedObject as TimedKeyframeList; INameable target = EditorData.BlockingScene.FindByName(asTimedKeyframeList.TargetName); if (target is Sprite) { EditorData.EditorLogic.SelectObject<Sprite>(target as Sprite, EditorData.EditorLogic.CurrentSprites); } // else other types GuiData.TimeLineWindow.InstructionMode = InstructionMode.Current; EditorData.EditorLogic.CurrentKeyframeList = asTimedKeyframeList.KeyframeList; } } } private string GetTimedKeyframeListStringRepresentation(object timedKeyframeList) { TimedKeyframeList asTimedKeyframeList = timedKeyframeList as TimedKeyframeList; return asTimedKeyframeList.TargetName + " : " + asTimedKeyframeList.Name; } private void HighlightInstructionSetListBox(Window callingWindow) { CollapseItem item = mInstructionSetListBox.GetFirstHighlightedItem(); if (item != null) { // Set the current InstructionSet CollapseItem topParentItem = item.TopParent; EditorData.EditorLogic.CurrentKeyframeList = topParentItem.ReferenceObject as KeyframeList; EditorData.EditorLogic.CurrentKeyframe = mInstructionSetListBox.GetFirstHighlightedItem().ReferenceObject as InstructionList; // if the object is an instruction list, execute em if (EditorData.EditorLogic.CurrentKeyframe != null && EditorData.EditorLogic.CurrentKeyframe.Count != 0) { GuiData.TimeLineWindow.CurrentValue = EditorData.EditorLogic.CurrentKeyframe[0].TimeToExecute; EditorData.EditorLogic.CurrentKeyframe.Execute(); } //GuiData.SpritePropertyGrid.UpdateDisplayedProperties(); } else { EditorData.EditorLogic.CurrentKeyframeList = null; EditorData.EditorLogic.CurrentKeyframe = null; } } private void InstructionListHotkeyUpdate(IInputReceiver receiver) { #region Delete if (InputManager.Keyboard.KeyPushed(Microsoft.Xna.Framework.Input.Keys.Delete)) { object highlightedObject = mInstructionSetListBox.GetFirstHighlightedObject(); if (highlightedObject is KeyframeList) { EditorData.EditorLogic.CurrentInstructionSet.Remove(highlightedObject as KeyframeList); EditorData.EditorLogic.CurrentKeyframe = null; EditorData.EditorLogic.CurrentKeyframeList = null; UpdateLists(); } else if (highlightedObject is InstructionList) { EditorData.EditorLogic.CurrentKeyframeList.Remove(highlightedObject as InstructionList); UpdateLists(); } } #endregion } private void HighlightAnimationSequenceListBox(Window callingWindow) { object highlightedObject = mAnimationSequenceListBox.GetFirstHighlightedObject(); if (highlightedObject == null) { } else { if (highlightedObject is AnimationSequence) { EditorData.EditorLogic.CurrentAnimationSequence = highlightedObject as AnimationSequence; } else if (highlightedObject is TimedKeyframeList) { CollapseItem highlightedItem = mAnimationSequenceListBox.GetFirstHighlightedItem(); CollapseItem parentItem = highlightedItem.TopParent; EditorData.EditorLogic.CurrentAnimationSequence = parentItem.ReferenceObject as AnimationSequence; EditorData.EditorLogic.CurrentTimedKeyframeList = highlightedObject as TimedKeyframeList; } } } private void UpdateAddButtonVisibility(Window callingWindow) { mAddKeyframeButton.Enabled = true; mAddKeyframeListButton.Enabled = true; } #endregion #region Methods #region Constructor public ListBoxWindow() : base(GuiManager.Cursor) { #region Set "this" properties. GuiManager.AddWindow(this); SetPositionTL(97.3f, 25.2f); ScaleX = 13.1f; ScaleY = 19.505f; mName = "Keyframes"; mMoveBar = true; MinimumScaleX = ScaleX; MinimumScaleY = 7; this.Resizable = true; this.Resizing += AdjustPositionsAndScales; #endregion #region List Box mInstructionSetListBox = AddCollapseListBox(); mInstructionSetListBox.Highlight += new GuiMessage(UpdateAddButtonVisibility); mInstructionSetListBox.Highlight += HighlightInstructionSetListBox; mInstructionSetListBox.FocusUpdate += InstructionListHotkeyUpdate; #endregion #region AnimationSequence ListDisplayWindow mAnimationSequenceListBox = new ListDisplayWindow(mCursor); this.AddWindow(mAnimationSequenceListBox); mAnimationSequenceListBox.ListBox.Highlight += HighlightAnimationSequenceListBox; mAnimationSequenceListBox.ListBox.StrongSelect += DoubleClickAnimationSequenceListBox; mAnimationSequenceListBox.ListBox.FocusUpdate += new FocusUpdateDelegate(AnimationSequenceFocusUpdate); ListDisplayWindow.SetStringRepresentationMethod(typeof(TimedKeyframeList), GetTimedKeyframeListStringRepresentation); #endregion #region Add Keyframe List Button mAddKeyframeListButton = AddButton(); mAddKeyframeListButton.Text = "Add Animation"; mAddKeyframeListButton.Click += AddKeyframeListClick; // this will call UpdateVisibleWindows #endregion #region Add Keyframe Button mAddKeyframeButton = AddButton(); mAddKeyframeButton.Text = "Add Keyframe"; mAddKeyframeButton.Click += AddKeyframe; #endregion AdjustPositionsAndScales(null); } #endregion #region Public Methods public void HighlightNoCall(InstructionList keyframe) { UpdateLists(); mInstructionSetListBox.HighlightObjectNoCall(keyframe, false); } public void HighlightNoCall(KeyframeList keyframeList) { UpdateLists(); mInstructionSetListBox.HighlightObjectNoCall(keyframeList, false); } public void UpdateLists() { #region Update List window visibility mInstructionSetListBox.Visible = GuiData.TimeLineWindow.InstructionMode == InstructionMode.Current; mAnimationSequenceListBox.Visible = GuiData.TimeLineWindow.InstructionMode == InstructionMode.All; #endregion #region Update the Global InstructionSets ListDisplayWindow mAnimationSequenceListBox.ListShowing = EditorData.GlobalInstructionSets; #endregion #region If there is not a CurrentInstructionSet if (EditorData.EditorLogic.CurrentInstructionSet == null) { mInstructionSetListBox.Clear(); } #endregion #region Else, there is else { #region See if there are any KeyframeLists that aren't shown in the list for (int i = 0; i < EditorData.EditorLogic.CurrentInstructionSet.Count; i++) { if (mInstructionSetListBox.ContainsObject( EditorData.EditorLogic.CurrentInstructionSet[i]) == false) { CollapseItem item = mInstructionSetListBox.AddItem( EditorData.EditorLogic.CurrentInstructionSet[i].Name, EditorData.EditorLogic.CurrentInstructionSet[i]); } else { mInstructionSetListBox.GetItem(EditorData.EditorLogic.CurrentInstructionSet[i]).Text = EditorData.EditorLogic.CurrentInstructionSet[i].Name; } } #endregion #region See if there are any Keyframes that aren't in the ListBox foreach (KeyframeList keyframeList in EditorData.EditorLogic.CurrentInstructionSet) { CollapseItem itemForKeyframe = mInstructionSetListBox.GetItem(keyframeList); for (int i = 0; i < keyframeList.Count; i++) { InstructionList list = keyframeList[i]; string listName = ""; if (list.Count != 0) { string numberString = list[0].TimeToExecute.ToString("00.000"); listName = numberString + " " + list.Name; } else listName = list.Name; if (itemForKeyframe.Contains(list) == false) { itemForKeyframe.InsertItem(i, listName, list); } else { itemForKeyframe.GetItem(list).Text = listName; } } } #endregion #region See if there are any KeyframeLists or Keyframes in the ListBox that aren't in the List for (int itemNumber = 0; itemNumber < mInstructionSetListBox.Items.Count; itemNumber++) { CollapseItem item = mInstructionSetListBox.Items[itemNumber]; KeyframeList keyframeList = item.ReferenceObject as KeyframeList; if (EditorData.EditorLogic.CurrentInstructionSet.Contains(keyframeList) == false) { mInstructionSetListBox.RemoveCollapseItem(item); } else { for (int i = item.Count - 1; i > -1; i--) { CollapseItem subItem = item[i]; InstructionList keyframe = subItem.ReferenceObject as InstructionList; if (keyframeList.Contains(keyframe) == false) { item.RemoveObject(keyframe); } } } } #endregion } #endregion } #endregion #endregion } }
using MusicXMLSharp.Schema; /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="wavy-line")] public partial class WavyLine { private StartStopContinue typeField; private string numberField; private decimal defaultxField; private bool defaultxFieldSpecified; private decimal defaultyField; private bool defaultyFieldSpecified; private decimal relativexField; private bool relativexFieldSpecified; private decimal relativeyField; private bool relativeyFieldSpecified; private AboveBelow placementField; private bool placementFieldSpecified; private string colorField; private StartNote _startNoteField; private bool startnoteFieldSpecified; private TrillStep _trillStepField; private bool trillstepFieldSpecified; private TwoNoteTurn _twoNoteTurnField; private bool twonoteturnFieldSpecified; private YesNo accelerateField; private bool accelerateFieldSpecified; private decimal beatsField; private bool beatsFieldSpecified; private decimal secondbeatField; private bool secondbeatFieldSpecified; private decimal lastbeatField; private bool lastbeatFieldSpecified; /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public StartStopContinue type { get { return this.typeField; } set { this.typeField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute(DataType="positiveInteger")] public string number { get { return this.numberField; } set { this.numberField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute("default-x")] public decimal defaultx { get { return this.defaultxField; } set { this.defaultxField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool defaultxSpecified { get { return this.defaultxFieldSpecified; } set { this.defaultxFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute("default-y")] public decimal defaulty { get { return this.defaultyField; } set { this.defaultyField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool defaultySpecified { get { return this.defaultyFieldSpecified; } set { this.defaultyFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute("relative-x")] public decimal relativex { get { return this.relativexField; } set { this.relativexField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool relativexSpecified { get { return this.relativexFieldSpecified; } set { this.relativexFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute("relative-y")] public decimal relativey { get { return this.relativeyField; } set { this.relativeyField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool relativeySpecified { get { return this.relativeyFieldSpecified; } set { this.relativeyFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public AboveBelow placement { get { return this.placementField; } set { this.placementField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool placementSpecified { get { return this.placementFieldSpecified; } set { this.placementFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string color { get { return this.colorField; } set { this.colorField = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute("start-note")] public StartNote StartNote { get { return this._startNoteField; } set { this._startNoteField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool startnoteSpecified { get { return this.startnoteFieldSpecified; } set { this.startnoteFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute("trill-step")] public TrillStep TrillStep { get { return this._trillStepField; } set { this._trillStepField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool trillstepSpecified { get { return this.trillstepFieldSpecified; } set { this.trillstepFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute("two-note-turn")] public TwoNoteTurn TwoNoteTurn { get { return this._twoNoteTurnField; } set { this._twoNoteTurnField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool twonoteturnSpecified { get { return this.twonoteturnFieldSpecified; } set { this.twonoteturnFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public YesNo accelerate { get { return this.accelerateField; } set { this.accelerateField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool accelerateSpecified { get { return this.accelerateFieldSpecified; } set { this.accelerateFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute()] public decimal beats { get { return this.beatsField; } set { this.beatsField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool beatsSpecified { get { return this.beatsFieldSpecified; } set { this.beatsFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute("second-beat")] public decimal secondbeat { get { return this.secondbeatField; } set { this.secondbeatField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool secondbeatSpecified { get { return this.secondbeatFieldSpecified; } set { this.secondbeatFieldSpecified = value; } } /// <remarks/> [System.Xml.Serialization.XmlAttributeAttribute("last-beat")] public decimal lastbeat { get { return this.lastbeatField; } set { this.lastbeatField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool lastbeatSpecified { get { return this.lastbeatFieldSpecified; } set { this.lastbeatFieldSpecified = value; } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.ComponentModel; using System.Globalization; using System.Runtime; using System.ServiceModel.Configuration; [TypeConverter(typeof(MessageVersionConverter))] public sealed class MessageVersion { EnvelopeVersion envelope; AddressingVersion addressing; static MessageVersion none; static MessageVersion soap11; static MessageVersion soap12; static MessageVersion soap11Addressing10; static MessageVersion soap12Addressing10; static MessageVersion soap11Addressing200408; static MessageVersion soap12Addressing200408; static MessageVersion() { none = new MessageVersion(EnvelopeVersion.None, AddressingVersion.None); soap11 = new MessageVersion(EnvelopeVersion.Soap11, AddressingVersion.None); soap12 = new MessageVersion(EnvelopeVersion.Soap12, AddressingVersion.None); soap11Addressing10 = new MessageVersion(EnvelopeVersion.Soap11, AddressingVersion.WSAddressing10); soap12Addressing10 = new MessageVersion(EnvelopeVersion.Soap12, AddressingVersion.WSAddressing10); soap11Addressing200408 = new MessageVersion(EnvelopeVersion.Soap11, AddressingVersion.WSAddressingAugust2004); soap12Addressing200408 = new MessageVersion(EnvelopeVersion.Soap12, AddressingVersion.WSAddressingAugust2004); } MessageVersion(EnvelopeVersion envelopeVersion, AddressingVersion addressingVersion) { this.envelope = envelopeVersion; this.addressing = addressingVersion; } public static MessageVersion CreateVersion(EnvelopeVersion envelopeVersion) { return CreateVersion(envelopeVersion, AddressingVersion.WSAddressing10); } public static MessageVersion CreateVersion(EnvelopeVersion envelopeVersion, AddressingVersion addressingVersion) { if (envelopeVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("envelopeVersion"); } if (addressingVersion == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("addressingVersion"); } if (envelopeVersion == EnvelopeVersion.Soap12) { if (addressingVersion == AddressingVersion.WSAddressing10) { return soap12Addressing10; } else if (addressingVersion == AddressingVersion.WSAddressingAugust2004) { return soap12Addressing200408; } else if (addressingVersion == AddressingVersion.None) { return soap12; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("addressingVersion", SR.GetString(SR.AddressingVersionNotSupported, addressingVersion)); } } else if (envelopeVersion == EnvelopeVersion.Soap11) { if (addressingVersion == AddressingVersion.WSAddressing10) { return soap11Addressing10; } else if (addressingVersion == AddressingVersion.WSAddressingAugust2004) { return soap11Addressing200408; } else if (addressingVersion == AddressingVersion.None) { return soap11; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("addressingVersion", SR.GetString(SR.AddressingVersionNotSupported, addressingVersion)); } } else if (envelopeVersion == EnvelopeVersion.None) { if (addressingVersion == AddressingVersion.None) { return none; } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("addressingVersion", SR.GetString(SR.AddressingVersionNotSupported, addressingVersion)); } } else { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument("envelopeVersion", SR.GetString(SR.EnvelopeVersionNotSupported, envelopeVersion)); } } public AddressingVersion Addressing { get { return addressing; } } public static MessageVersion Default { get { return soap12Addressing10; } } public EnvelopeVersion Envelope { get { return envelope; } } public override bool Equals(object obj) { return this == obj; } public override int GetHashCode() { int code = 0; if (this.Envelope == EnvelopeVersion.Soap11) code += 1; if (this.Addressing == AddressingVersion.WSAddressingAugust2004) code += 2; return code; } public static MessageVersion None { get { return none; } } public static MessageVersion Soap12WSAddressing10 { get { return soap12Addressing10; } } public static MessageVersion Soap11WSAddressing10 { get { return soap11Addressing10; } } public static MessageVersion Soap12WSAddressingAugust2004 { get { return soap12Addressing200408; } } public static MessageVersion Soap11WSAddressingAugust2004 { get { return soap11Addressing200408; } } public static MessageVersion Soap11 { get { return soap11; } } public static MessageVersion Soap12 { get { return soap12; } } public override string ToString() { return SR.GetString(SR.MessageVersionToStringFormat, envelope.ToString(), addressing.ToString()); } internal bool IsMatch(MessageVersion messageVersion) { if (messageVersion == null) { Fx.Assert("Invalid (null) messageVersion value"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion"); } if (addressing == null) { Fx.Assert("Invalid (null) addressing value"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "MessageVersion.Addressing cannot be null"))); } if (envelope != messageVersion.Envelope) return false; if (addressing.Namespace != messageVersion.Addressing.Namespace) return false; return true; } } }
//#define COSMOSDEBUG using System; using System.Collections.Generic; using System.Drawing; using Cosmos.HAL.Drivers; namespace Cosmos.System.Graphics { /// <summary> /// VBECanvas class. Used to control screen, by VBE (VESA BIOS Extensions) standard. See also: <seealso cref="Canvas"/>. /// </summary> public class VBECanvas : Canvas { /// <summary> /// Default video mode. 1024x768x32. /// </summary> private static readonly Mode _DefaultMode = new Mode(1024, 768, ColorDepth.ColorDepth32); /// <summary> /// Driver for Setting vbe modes and ploting/getting pixels /// </summary> private readonly VBEDriver _VBEDriver; /// <summary> /// Video mode. /// </summary> private Mode _Mode; /// <summary> /// Create new instance of the <see cref="VBEScreen"/> class. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Thrown if default mode (1024x768x32) is not suppoted.</exception> public VBECanvas() : this(_DefaultMode) { } /// <summary> /// Create new instance of the <see cref="VBEScreen"/> class. /// </summary> /// <param name="mode">VBE mode.</param> /// <exception cref="ArgumentOutOfRangeException">Thrown if mode is not suppoted.</exception> public VBECanvas(Mode aMode) { Global.mDebugger.SendInternal($"Creating new VBEScreen() with mode {aMode.Columns}x{aMode.Rows}x{(uint)aMode.ColorDepth}"); if (Core.VBE.IsAvailable()) { Core.VBE.ModeInfo ModeInfo = Core.VBE.getModeInfo(); aMode = new Mode(ModeInfo.width, ModeInfo.height, (ColorDepth)ModeInfo.bpp); Global.mDebugger.SendInternal($"Detected VBE VESA with {aMode.Columns}x{aMode.Rows}x{(uint)aMode.ColorDepth}"); } ThrowIfModeIsNotValid(aMode); _VBEDriver = new VBEDriver((ushort)aMode.Columns, (ushort)aMode.Rows, (ushort)aMode.ColorDepth); Mode = aMode; } /// <summary> /// Disables VBE Graphics mode, parent method returns to VGA text mode (80x25) /// </summary> public override void Disable() { _VBEDriver.DisableDisplay(); } /// <summary> /// Name of the backend /// </summary> public override string Name() => "VBECanvas"; /// <summary> /// Get and set video mode. /// </summary> /// <exception cref="ArgumentOutOfRangeException">(set) Thrown if mode is not suppoted.</exception> public override Mode Mode { get => _Mode; set { _Mode = value; SetMode(_Mode); } } #region Display /// <summary> /// All the available screen modes VBE supports, I would like to query the hardware and obtain from it the list but I have /// not yet find how to do it! For now I hardcode the most used VESA modes, VBE seems to support until HDTV resolution /// without problems that is well... excellent :-) /// </summary> //public override IReadOnlyList<Mode> AvailableModes { get; } = new List<Mode> /// <summary> /// Available VBE supported video modes. /// <para> /// Low res: /// <list type="bullet"> /// <item>320x240x32.</item> /// <item>640x480x32.</item> /// <item>800x600x32.</item> /// <item>1024x768x32.</item> /// </list> /// </para> /// <para> /// HD: /// <list type="bullet"> /// <item>1280x720x32.</item> /// <item>1280x1024x32.</item> /// </list> /// </para> /// <para> /// HDR: /// <list type="bullet"> /// <item>1366x768x32.</item> /// <item>1680x1050x32.</item> /// </list> /// </para> /// <para> /// HDTV: /// <list type="bullet"> /// <item>1920x1080x32.</item> /// <item>1920x1200x32.</item> /// </list> /// </para> /// </summary> public override List<Mode> AvailableModes { get; } = new List<Mode> { new Mode(320, 240, ColorDepth.ColorDepth32), new Mode(640, 480, ColorDepth.ColorDepth32), new Mode(800, 600, ColorDepth.ColorDepth32), new Mode(1024, 768, ColorDepth.ColorDepth32), /* The so called HD-Ready resolution */ new Mode(1280, 720, ColorDepth.ColorDepth32), new Mode(1280, 768, ColorDepth.ColorDepth32), new Mode(1280, 1024, ColorDepth.ColorDepth32), /* A lot of HD-Ready screen uses this instead of 1280x720 */ new Mode(1366, 768, ColorDepth.ColorDepth32), new Mode(1680, 1050, ColorDepth.ColorDepth32), /* HDTV resolution */ new Mode(1920, 1080, ColorDepth.ColorDepth32), /* HDTV resolution (16:10 AR) */ new Mode(1920, 1200, ColorDepth.ColorDepth32), }; /// <summary> /// Override Canvas default graphics mode. /// </summary> public override Mode DefaultGraphicMode => _DefaultMode; /// <summary> /// Use this to setup the screen, this will disable the console. /// </summary> /// <param name="Mode">The desired Mode resolution</param> /// <exception cref="ArgumentOutOfRangeException">Thrown if mode is not suppoted.</exception> private void SetMode(Mode aMode) { ThrowIfModeIsNotValid(aMode); ushort xres = (ushort)Mode.Columns; ushort yres = (ushort)Mode.Rows; ushort bpp = (ushort)Mode.ColorDepth; //set the screen _VBEDriver.VBESet(xres, yres, bpp); } #endregion #region Drawing /// <summary> /// Clear screen to specified color. /// </summary> /// <param name="color">Color.</param> public override void Clear(int aColor) { Global.mDebugger.SendInternal($"Clearing the Screen with Color {aColor}"); //if (color == null) // throw new ArgumentNullException(nameof(color)); /* * TODO this version of Clear() works only when mode.ColorDepth == ColorDepth.ColorDepth32 * in the other cases you should before convert color and then call the opportune ClearVRAM() overload * (the one that takes ushort for ColorDepth.ColorDepth16 and the one that takes byte for ColorDepth.ColorDepth8) * For ColorDepth.ColorDepth24 you should mask the Alpha byte. */ switch (_Mode.ColorDepth) { case ColorDepth.ColorDepth4: throw new NotImplementedException(); case ColorDepth.ColorDepth8: throw new NotImplementedException(); case ColorDepth.ColorDepth16: throw new NotImplementedException(); case ColorDepth.ColorDepth24: throw new NotImplementedException(); case ColorDepth.ColorDepth32: _VBEDriver.ClearVRAM((uint)aColor); break; default: throw new NotImplementedException(); } } /// <summary> /// Clear screen to specified color. /// </summary> /// <param name="color">Color.</param> public override void Clear(Color aColor) { Global.mDebugger.SendInternal($"Clearing the Screen with Color {aColor}"); //if (color == null) // throw new ArgumentNullException(nameof(color)); /* * TODO this version of Clear() works only when mode.ColorDepth == ColorDepth.ColorDepth32 * in the other cases you should before convert color and then call the opportune ClearVRAM() overload * (the one that takes ushort for ColorDepth.ColorDepth16 and the one that takes byte for ColorDepth.ColorDepth8) * For ColorDepth.ColorDepth24 you should mask the Alpha byte. */ switch (_Mode.ColorDepth) { case ColorDepth.ColorDepth4: throw new NotImplementedException(); case ColorDepth.ColorDepth8: throw new NotImplementedException(); case ColorDepth.ColorDepth16: throw new NotImplementedException(); case ColorDepth.ColorDepth24: throw new NotImplementedException(); case ColorDepth.ColorDepth32: _VBEDriver.ClearVRAM((uint)aColor.ToArgb()); break; default: throw new NotImplementedException(); } } /* * As DrawPoint() is the basic block of DrawLine() and DrawRect() and in theory of all the future other methods that will * be implemented is better to not check the validity of the arguments here or it will repeat the check for any point * to be drawn slowing down all. */ /// <summary> /// Draw point to the screen. /// </summary> /// <param name="aPen">Pen to draw the point with.</param> /// <param name="aX">X coordinate.</param> /// <param name="aY">Y coordinate.</param> /// <exception cref="NotImplementedException">Thrown if color depth is not supported (currently only 32 is supported).</exception> public override void DrawPoint(Pen aPen, int aX, int aY) { uint offset; /* * For now we can Draw only if the ColorDepth is 32 bit, we will throw otherwise. * * How to support other ColorDepth? The offset calculation should be the same (and so could be done out of the switch) * ColorDepth.ColorDepth16 and ColorDepth.ColorDepth8 need a conversion from color (an ARGB32 color) to the RGB16 and RGB8 * how to do this conversion faster maybe using pre-computed tables? What happens if the color cannot be converted? We will throw? */ switch (Mode.ColorDepth) { case ColorDepth.ColorDepth32: offset = (uint)GetPointOffset(aX, aY); if (aPen.Color.A < 255) { if (aPen.Color.A == 0) { return; } aPen.Color = AlphaBlend(aPen.Color, GetPointColor(aX, aY), aPen.Color.A); } _VBEDriver.SetVRAM(offset, aPen.Color.B); _VBEDriver.SetVRAM(offset + 1, aPen.Color.G); _VBEDriver.SetVRAM(offset + 2, aPen.Color.R); _VBEDriver.SetVRAM(offset + 3, aPen.Color.A); break; case ColorDepth.ColorDepth24: offset = (uint)GetPointOffset(aX, aY); _VBEDriver.SetVRAM(offset, aPen.Color.B); _VBEDriver.SetVRAM(offset + 1, aPen.Color.G); _VBEDriver.SetVRAM(offset + 2, aPen.Color.R); break; default: string errorMsg = "DrawPoint() with ColorDepth " + (int)Mode.ColorDepth + " not yet supported"; throw new NotImplementedException(errorMsg); } } /// <summary> /// Draw point to the screen. /// Not implemented. /// </summary> /// <param name="aPen">Pen to draw the point with.</param> /// <param name="aX">X coordinate.</param> /// <param name="aY">Y coordinate.</param> /// <exception cref="NotImplementedException">Thrown always (only int coordinats supported).</exception> public override void DrawPoint(Pen aPen, float aX, float aY) { throw new NotImplementedException(); } /* This is just temp */ /// <summary> /// Draw array of colors. /// </summary> /// <param name="aColors">Colors array.</param> /// <param name="aX">X coordinate.</param> /// <param name="aY">Y coordinate.</param> /// <param name="aWidth">Width.</param> /// <param name="aHeight">unused.</param> /// <exception cref="ArgumentOutOfRangeException">Thrown if coordinates are invalid, or width is less than 0.</exception> /// <exception cref="NotImplementedException">Thrown if color depth is not supported.</exception> public override void DrawArray(Color[] aColors, int aX, int aY, int aWidth, int aHeight) { ThrowIfCoordNotValid(aX, aY); ThrowIfCoordNotValid(aX + aWidth, aY + aHeight); for (int i = 0; i < aX; i++) { for (int ii = 0; ii < aY; ii++) { DrawPoint(new Pen(aColors[i + (ii * aWidth)]), i, ii); } } } /// <summary> /// Draw filled rectangle. /// </summary> /// <param name="aPen">Pen to draw with.</param> /// <param name="aX">X coordinate.</param> /// <param name="aY">Y coordinate.</param> /// <param name="aWidth">Width.</param> /// <param name="aHeight">Height.</param> public override void DrawFilledRectangle(Pen aPen, int aX, int aY, int aWidth, int aHeight) { //ClearVRAM clears one uint at a time. So we clear pixelwise not byte wise. That's why we divide by 32 and not 8. aWidth = Math.Min(aWidth, Mode.Columns - aX) * (int)Mode.ColorDepth / 32; var color = aPen.Color.ToArgb(); for (int i = aY; i < aY + aHeight; i++) { _VBEDriver.ClearVRAM(GetPointOffset(aX, i), aWidth, color); } } /// <summary> /// Draw image. /// </summary> /// <param name="aImage">Image.</param> /// <param name="aX">X coordinate.</param> /// <param name="aY">Y coordinate.</param> public override void DrawImage(Image aImage, int aX, int aY) { var xBitmap = aImage.rawData; var xWidth = (int)aImage.Width; var xHeight = (int)aImage.Height; int xOffset = GetPointOffset(aX, aY); int xScreenWidthInPixel = Mode.Columns; for (int i = 0; i < xHeight; i++) { _VBEDriver.CopyVRAM((i * xScreenWidthInPixel) + xOffset, xBitmap, (i * xWidth), xWidth); } } #endregion /// <summary> /// Display screen /// </summary> public override void Display() { _VBEDriver.Swap(); } #region Reading /// <summary> /// Get point color. /// </summary> /// <param name="aX">X coordinate.</param> /// <param name="aY">Y coordinate.</param> /// <returns>Color value.</returns> public override Color GetPointColor(int aX, int aY) { uint offset = (uint)GetPointOffset(aX, aY); return Color.FromArgb((int)_VBEDriver.GetVRAM(offset)); } #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.Collections.Generic; using System.Linq.Expressions; using Xunit; namespace System.Linq.Tests { public class GroupByTests : EnumerableBasedTests { private static void AssertGroupingCorrect<TKey, TElement>(IQueryable<TKey> keys, IQueryable<TElement> elements, IQueryable<IGrouping<TKey, TElement>> grouping) { AssertGroupingCorrect<TKey, TElement>(keys, elements, grouping, EqualityComparer<TKey>.Default); } private static void AssertGroupingCorrect<TKey, TElement>(IQueryable<TKey> keys, IQueryable<TElement> elements, IQueryable<IGrouping<TKey, TElement>> grouping, IEqualityComparer<TKey> keyComparer) { if (grouping == null) { Assert.Null(elements); Assert.Null(keys); return; } Assert.NotNull(elements); Assert.NotNull(keys); Dictionary<TKey, List<TElement>> dict = new Dictionary<TKey, List<TElement>>(keyComparer); List<TElement> groupingForNullKeys = new List<TElement>(); using (IEnumerator<TElement> elEn = elements.GetEnumerator()) using (IEnumerator<TKey> keyEn = keys.GetEnumerator()) { while (keyEn.MoveNext()) { Assert.True(elEn.MoveNext()); TKey key = keyEn.Current; if (key == null) { groupingForNullKeys.Add(elEn.Current); } else { List<TElement> list; if (!dict.TryGetValue(key, out list)) dict.Add(key, list = new List<TElement>()); list.Add(elEn.Current); } } Assert.False(elEn.MoveNext()); } foreach (IGrouping<TKey, TElement> group in grouping) { Assert.NotEmpty(group); TKey key = group.Key; List<TElement> list; if (key == null) { Assert.Equal(groupingForNullKeys, group); groupingForNullKeys.Clear(); } else { Assert.True(dict.TryGetValue(key, out list)); Assert.Equal(list, group); dict.Remove(key); } } Assert.Empty(dict); Assert.Empty(groupingForNullKeys); } public struct Record { public string Name; public int Score; } [Fact] public void SingleNullKeySingleNullElement() { string[] key = { null }; string[] element = { null }; AssertGroupingCorrect(key.AsQueryable(), element.AsQueryable(), new string[] { null }.AsQueryable().GroupBy(e => e, e => e, EqualityComparer<string>.Default), EqualityComparer<string>.Default); } [Fact] public void EmptySource() { Assert.Empty(new Record[] { }.AsQueryable().GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer())); } [Fact] public void SourceIsNull() { IQueryable<Record> source = null; AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, new AnagramEqualityComparer())); AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, new AnagramEqualityComparer())); AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score)); AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name)); AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, (k, es) => es.Sum(), new AnagramEqualityComparer())); AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, e => e.Score, (k, es) => es.Sum())); AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, (k, es) => es.Sum(e => e.Score))); AssertExtensions.Throws<ArgumentNullException>("source", () => source.GroupBy(e => e.Name, (k, es) => es.Sum(e => e.Score), new AnagramEqualityComparer())); } [Fact] public void KeySelectorNull() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Expression<Func<Record, string>> keySelector = null; AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(null, e => e.Score, new AnagramEqualityComparer())); AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(null, e => e.Score, (k, es) => es.Sum(), new AnagramEqualityComparer())); AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(keySelector, e => e.Score, (k, es) => es.Sum())); AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(keySelector, e => e.Score)); AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(keySelector, e => e.Score, (k, es) => es.Sum())); AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(null, (k, es) => es.Sum(e => e.Score), new AnagramEqualityComparer())); AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(keySelector, (k, es) => es.Sum(e => e.Score))); AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(null, new AnagramEqualityComparer())); AssertExtensions.Throws<ArgumentNullException>("keySelector", () => source.AsQueryable().GroupBy(keySelector)); } [Fact] public void ElementSelectorNull() { Record[] source = new[] { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Expression<Func<Record, int>> elementSelector = null; AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => source.AsQueryable().GroupBy(e => e.Name, elementSelector)); AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => source.AsQueryable().GroupBy(e => e.Name, elementSelector, new AnagramEqualityComparer())); AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => source.AsQueryable().GroupBy(e => e.Name, elementSelector, (k, es) => es.Sum())); AssertExtensions.Throws<ArgumentNullException>("elementSelector", () => source.AsQueryable().GroupBy(e => e.Name, elementSelector, (k, es) => es.Sum(), new AnagramEqualityComparer())); } [Fact] public void ResultSelectorNull() { Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Expression<Func<string, IEnumerable<int>, long>> resultSelector = null; AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => source.AsQueryable().GroupBy(e => e.Name, e => e.Score, resultSelector, new AnagramEqualityComparer())); } [Fact] public void ResultSelectorNullNoComparer() { Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Expression<Func<string, IEnumerable<int>, long>> resultSelector = null; AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => source.AsQueryable().GroupBy(e => e.Name, e => e.Score, resultSelector)); } [Fact] public void ResultSelectorNullNoElementSelector() { Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "Tim", Score = 25 } }; Expression<Func<string, IEnumerable<Record>, long>> resultSelector = null; AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => source.AsQueryable().GroupBy(e => e.Name, resultSelector)); } [Fact] public void ResultSelectorNullNoElementSelectorCustomComparer() { string[] key = { "Tim", "Tim", "Tim", "Tim" }; int[] element = { 60, -10, 40, 100 }; var source = key.Zip(element, (k, e) => new Record { Name = k, Score = e }); Expression<Func<string, IEnumerable<Record>, long>> resultSelector = null; AssertExtensions.Throws<ArgumentNullException>("resultSelector", () => source.AsQueryable().GroupBy(e => e.Name, resultSelector, new AnagramEqualityComparer())); } [Fact] public void EmptySourceWithResultSelector() { Assert.Empty(new Record[] { }.AsQueryable().GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer())); } [Fact] public void DuplicateKeysCustomComparer() { string[] key = { "Tim", "Tim", "Chris", "Chris", "Robert", "Prakash" }; int[] element = { 55, 25, 49, 24, -100, 9 }; Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = "Chris", Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = "Prakash", Score = 9 }, new Record { Name = "miT", Score = 25 } }; long[] expected = { 240, 365, -600, 63 }; Assert.Equal(expected, source.AsQueryable().GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), new AnagramEqualityComparer())); } [Fact] public void NullComparer() { string[] key = { "Tim", null, null, "Robert", "Chris", "miT" }; int[] element = { 55, 49, 9, -100, 24, 25 }; Record[] source = { new Record { Name = "Tim", Score = 55 }, new Record { Name = null, Score = 49 }, new Record { Name = "Robert", Score = -100 }, new Record { Name = "Chris", Score = 24 }, new Record { Name = null, Score = 9 }, new Record { Name = "miT", Score = 25 } }; long[] expected = { 165, 58, -600, 120, 75 }; Assert.Equal(expected, source.AsQueryable().GroupBy(e => e.Name, e => e.Score, (k, es) => (long)(k ?? " ").Length * es.Sum(), null)); } [Fact] public void SingleNonNullElement() { string[] key = { "Tim" }; Record[] source = { new Record { Name = key[0], Score = 60 } }; AssertGroupingCorrect(key.AsQueryable(), source.AsQueryable(), source.AsQueryable().GroupBy(e => e.Name)); } [Fact] public void AllElementsSameKey() { string[] key = { "Tim", "Tim", "Tim", "Tim" }; int[] scores = { 60, -10, 40, 100 }; var source = key.Zip(scores, (k, e) => new Record { Name = k, Score = e }); AssertGroupingCorrect(key.AsQueryable(), source.AsQueryable(), source.AsQueryable().GroupBy(e => e.Name, new AnagramEqualityComparer()), new AnagramEqualityComparer()); } [Fact] public void AllElementsSameKeyResultSelectorUsed() { int[] element = { 60, -10, 40, 100 }; long[] expected = { 570 }; Record[] source = { new Record { Name = "Tim", Score = element[0] }, new Record { Name = "Tim", Score = element[1] }, new Record { Name = "miT", Score = element[2] }, new Record { Name = "miT", Score = element[3] } }; Assert.Equal(expected, source.AsQueryable().GroupBy(e => e.Name, (k, es) => k.Length * es.Sum(e => (long)e.Score), new AnagramEqualityComparer())); } [Fact] public void NullComparerResultSelectorUsed() { int[] element = { 60, -10, 40, 100 }; Record[] source = { new Record { Name = "Tim", Score = element[0] }, new Record { Name = "Tim", Score = element[1] }, new Record { Name = "miT", Score = element[2] }, new Record { Name = "miT", Score = element[3] }, }; long[] expected = { 150, 420 }; Assert.Equal(expected, source.AsQueryable().GroupBy(e => e.Name, (k, es) => k.Length * es.Sum(e => (long)e.Score), null)); } [Fact] public void GroupBy1() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n).Count(); Assert.Equal(3, count); } [Fact] public void GroupBy2() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, EqualityComparer<int>.Default).Count(); Assert.Equal(3, count); } [Fact] public void GroupBy3() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, n => n).Count(); Assert.Equal(3, count); } [Fact] public void GroupBy4() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, n => n, EqualityComparer<int>.Default).Count(); Assert.Equal(3, count); } [Fact] public void GroupBy5() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, n => n, (k, g) => k).Count(); Assert.Equal(3, count); } [Fact] public void GroupBy6() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, (k, g) => k).Count(); Assert.Equal(3, count); } [Fact] public void GroupBy7() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, n => n, (k, g) => k, EqualityComparer<int>.Default).Count(); Assert.Equal(3, count); } [Fact] public void GroupBy8() { var count = (new int[] { 0, 1, 2, 2, 0 }).AsQueryable().GroupBy(n => n, (k, g) => k, EqualityComparer<int>.Default).Count(); Assert.Equal(3, count); } } }
// 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] Value of GL_DRAW_PIXELS_APPLE symbol. /// </summary> [RequiredByFeature("GL_APPLE_fence")] public const int DRAW_PIXELS_APPLE = 0x8A0A; /// <summary> /// [GL] Value of GL_FENCE_APPLE symbol. /// </summary> [RequiredByFeature("GL_APPLE_fence")] public const int FENCE_APPLE = 0x8A0B; /// <summary> /// [GL] glGenFencesAPPLE: Binding for glGenFencesAPPLE. /// </summary> /// <param name="fences"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GL_APPLE_fence")] public static void GenFencesAPPLE(uint[] fences) { unsafe { fixed (uint* p_fences = fences) { Debug.Assert(Delegates.pglGenFencesAPPLE != null, "pglGenFencesAPPLE not implemented"); Delegates.pglGenFencesAPPLE(fences.Length, p_fences); LogCommand("glGenFencesAPPLE", null, fences.Length, fences ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glGenFencesAPPLE: Binding for glGenFencesAPPLE. /// </summary> [RequiredByFeature("GL_APPLE_fence")] public static uint GenFenceAPPLE() { uint retValue; unsafe { Delegates.pglGenFencesAPPLE(1, &retValue); LogCommand("glGenFencesAPPLE", null, 1, "{ " + retValue + " }" ); } DebugCheckErrors(null); return (retValue); } /// <summary> /// [GL] glDeleteFencesAPPLE: Binding for glDeleteFencesAPPLE. /// </summary> /// <param name="fences"> /// A <see cref="T:uint[]"/>. /// </param> [RequiredByFeature("GL_APPLE_fence")] public static void DeleteFencesAPPLE(params uint[] fences) { unsafe { fixed (uint* p_fences = fences) { Debug.Assert(Delegates.pglDeleteFencesAPPLE != null, "pglDeleteFencesAPPLE not implemented"); Delegates.pglDeleteFencesAPPLE(fences.Length, p_fences); LogCommand("glDeleteFencesAPPLE", null, fences.Length, fences ); } } DebugCheckErrors(null); } /// <summary> /// [GL] glSetFenceAPPLE: Binding for glSetFenceAPPLE. /// </summary> /// <param name="fence"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_APPLE_fence")] public static void SetFenceAPPLE(uint fence) { Debug.Assert(Delegates.pglSetFenceAPPLE != null, "pglSetFenceAPPLE not implemented"); Delegates.pglSetFenceAPPLE(fence); LogCommand("glSetFenceAPPLE", null, fence ); DebugCheckErrors(null); } /// <summary> /// [GL] glIsFenceAPPLE: Binding for glIsFenceAPPLE. /// </summary> /// <param name="fence"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_APPLE_fence")] public static bool IsFenceAPPLE(uint fence) { bool retValue; Debug.Assert(Delegates.pglIsFenceAPPLE != null, "pglIsFenceAPPLE not implemented"); retValue = Delegates.pglIsFenceAPPLE(fence); LogCommand("glIsFenceAPPLE", retValue, fence ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GL] glTestFenceAPPLE: Binding for glTestFenceAPPLE. /// </summary> /// <param name="fence"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_APPLE_fence")] public static bool TestFenceAPPLE(uint fence) { bool retValue; Debug.Assert(Delegates.pglTestFenceAPPLE != null, "pglTestFenceAPPLE not implemented"); retValue = Delegates.pglTestFenceAPPLE(fence); LogCommand("glTestFenceAPPLE", retValue, fence ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GL] glFinishFenceAPPLE: Binding for glFinishFenceAPPLE. /// </summary> /// <param name="fence"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_APPLE_fence")] public static void FinishFenceAPPLE(uint fence) { Debug.Assert(Delegates.pglFinishFenceAPPLE != null, "pglFinishFenceAPPLE not implemented"); Delegates.pglFinishFenceAPPLE(fence); LogCommand("glFinishFenceAPPLE", null, fence ); DebugCheckErrors(null); } /// <summary> /// [GL] glTestObjectAPPLE: Binding for glTestObjectAPPLE. /// </summary> /// <param name="object"> /// A <see cref="T:int"/>. /// </param> /// <param name="name"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_APPLE_fence")] public static bool TestObjectAPPLE(int @object, uint name) { bool retValue; Debug.Assert(Delegates.pglTestObjectAPPLE != null, "pglTestObjectAPPLE not implemented"); retValue = Delegates.pglTestObjectAPPLE(@object, name); LogCommand("glTestObjectAPPLE", retValue, @object, name ); DebugCheckErrors(retValue); return (retValue); } /// <summary> /// [GL] glFinishObjectAPPLE: Binding for glFinishObjectAPPLE. /// </summary> /// <param name="object"> /// A <see cref="T:int"/>. /// </param> /// <param name="name"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GL_APPLE_fence")] public static void FinishObjectAPPLE(int @object, int name) { Debug.Assert(Delegates.pglFinishObjectAPPLE != null, "pglFinishObjectAPPLE not implemented"); Delegates.pglFinishObjectAPPLE(@object, name); LogCommand("glFinishObjectAPPLE", null, @object, name ); DebugCheckErrors(null); } internal static unsafe partial class Delegates { [RequiredByFeature("GL_APPLE_fence")] [SuppressUnmanagedCodeSecurity] internal delegate void glGenFencesAPPLE(int n, uint* fences); [RequiredByFeature("GL_APPLE_fence")] [ThreadStatic] internal static glGenFencesAPPLE pglGenFencesAPPLE; [RequiredByFeature("GL_APPLE_fence")] [SuppressUnmanagedCodeSecurity] internal delegate void glDeleteFencesAPPLE(int n, uint* fences); [RequiredByFeature("GL_APPLE_fence")] [ThreadStatic] internal static glDeleteFencesAPPLE pglDeleteFencesAPPLE; [RequiredByFeature("GL_APPLE_fence")] [SuppressUnmanagedCodeSecurity] internal delegate void glSetFenceAPPLE(uint fence); [RequiredByFeature("GL_APPLE_fence")] [ThreadStatic] internal static glSetFenceAPPLE pglSetFenceAPPLE; [RequiredByFeature("GL_APPLE_fence")] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] internal delegate bool glIsFenceAPPLE(uint fence); [RequiredByFeature("GL_APPLE_fence")] [ThreadStatic] internal static glIsFenceAPPLE pglIsFenceAPPLE; [RequiredByFeature("GL_APPLE_fence")] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] internal delegate bool glTestFenceAPPLE(uint fence); [RequiredByFeature("GL_APPLE_fence")] [ThreadStatic] internal static glTestFenceAPPLE pglTestFenceAPPLE; [RequiredByFeature("GL_APPLE_fence")] [SuppressUnmanagedCodeSecurity] internal delegate void glFinishFenceAPPLE(uint fence); [RequiredByFeature("GL_APPLE_fence")] [ThreadStatic] internal static glFinishFenceAPPLE pglFinishFenceAPPLE; [RequiredByFeature("GL_APPLE_fence")] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.I1)] internal delegate bool glTestObjectAPPLE(int @object, uint name); [RequiredByFeature("GL_APPLE_fence")] [ThreadStatic] internal static glTestObjectAPPLE pglTestObjectAPPLE; [RequiredByFeature("GL_APPLE_fence")] [SuppressUnmanagedCodeSecurity] internal delegate void glFinishObjectAPPLE(int @object, int name); [RequiredByFeature("GL_APPLE_fence")] [ThreadStatic] internal static glFinishObjectAPPLE pglFinishObjectAPPLE; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Batch.Protocol.Models { using System.Linq; /// <summary> /// Resource usage statistics for a job schedule. /// </summary> public partial class JobScheduleStatistics { /// <summary> /// Initializes a new instance of the JobScheduleStatistics class. /// </summary> public JobScheduleStatistics() { } /// <summary> /// Initializes a new instance of the JobScheduleStatistics class. /// </summary> /// <param name="url">The URL of the statistics.</param> /// <param name="startTime">The start time of the time range covered by /// the statistics.</param> /// <param name="lastUpdateTime">The time at which the statistics were /// last updated. All statistics are limited to the range between /// startTime and lastUpdateTime.</param> /// <param name="userCPUTime">The total user mode CPU time (summed /// across all cores and all compute nodes) consumed by all tasks in /// all jobs created under the schedule.</param> /// <param name="kernelCPUTime">The total kernel mode CPU time (summed /// across all cores and all compute nodes) consumed by all tasks in /// all jobs created under the schedule.</param> /// <param name="wallClockTime">The total wall clock time of all the /// tasks in all the jobs created under the schedule.</param> /// <param name="readIOps">The total number of disk read operations /// made by all tasks in all jobs created under the schedule.</param> /// <param name="writeIOps">The total number of disk write operations /// made by all tasks in all jobs created under the schedule.</param> /// <param name="readIOGiB">The total gibibytes read from disk by all /// tasks in all jobs created under the schedule.</param> /// <param name="writeIOGiB">The total gibibytes written to disk by all /// tasks in all jobs created under the schedule.</param> /// <param name="numSucceededTasks">The total number of tasks /// successfully completed during the given time range in jobs created /// under the schedule. A task completes successfully if it returns /// exit code 0.</param> /// <param name="numFailedTasks">The total number of tasks that failed /// during the given time range in jobs created under the schedule. A /// task fails if it exhausts its maximum retry count without returning /// exit code 0.</param> /// <param name="numTaskRetries">The total number of retries during the /// given time range on all tasks in all jobs created under the /// schedule.</param> /// <param name="waitTime">The total wait time of all tasks in all jobs /// created under the schedule. The wait time for a task is defined as /// the elapsed time between the creation of the task and the start of /// task execution. (If the task is retried due to failures, the wait /// time is the time to the most recent task execution.)</param> public JobScheduleStatistics(string url, System.DateTime startTime, System.DateTime lastUpdateTime, System.TimeSpan userCPUTime, System.TimeSpan kernelCPUTime, System.TimeSpan wallClockTime, long readIOps, long writeIOps, double readIOGiB, double writeIOGiB, long numSucceededTasks, long numFailedTasks, long numTaskRetries, System.TimeSpan waitTime) { this.Url = url; this.StartTime = startTime; this.LastUpdateTime = lastUpdateTime; this.UserCPUTime = userCPUTime; this.KernelCPUTime = kernelCPUTime; this.WallClockTime = wallClockTime; this.ReadIOps = readIOps; this.WriteIOps = writeIOps; this.ReadIOGiB = readIOGiB; this.WriteIOGiB = writeIOGiB; this.NumSucceededTasks = numSucceededTasks; this.NumFailedTasks = numFailedTasks; this.NumTaskRetries = numTaskRetries; this.WaitTime = waitTime; } /// <summary> /// Gets or sets the URL of the statistics. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "url")] public string Url { get; set; } /// <summary> /// Gets or sets the start time of the time range covered by the /// statistics. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "startTime")] public System.DateTime StartTime { get; set; } /// <summary> /// Gets or sets the time at which the statistics were last updated. /// All statistics are limited to the range between startTime and /// lastUpdateTime. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "lastUpdateTime")] public System.DateTime LastUpdateTime { get; set; } /// <summary> /// Gets or sets the total user mode CPU time (summed across all cores /// and all compute nodes) consumed by all tasks in all jobs created /// under the schedule. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "userCPUTime")] public System.TimeSpan UserCPUTime { get; set; } /// <summary> /// Gets or sets the total kernel mode CPU time (summed across all /// cores and all compute nodes) consumed by all tasks in all jobs /// created under the schedule. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "kernelCPUTime")] public System.TimeSpan KernelCPUTime { get; set; } /// <summary> /// Gets or sets the total wall clock time of all the tasks in all the /// jobs created under the schedule. /// </summary> /// <remarks> /// The wall clock time is the elapsed time from when the task started /// running on a compute node to when it finished (or to the last time /// the statistics were updated, if the task had not finished by then). /// If a task was retried, this includes the wall clock time of all the /// task retries. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "wallClockTime")] public System.TimeSpan WallClockTime { get; set; } /// <summary> /// Gets or sets the total number of disk read operations made by all /// tasks in all jobs created under the schedule. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "readIOps")] public long ReadIOps { get; set; } /// <summary> /// Gets or sets the total number of disk write operations made by all /// tasks in all jobs created under the schedule. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "writeIOps")] public long WriteIOps { get; set; } /// <summary> /// Gets or sets the total gibibytes read from disk by all tasks in all /// jobs created under the schedule. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "readIOGiB")] public double ReadIOGiB { get; set; } /// <summary> /// Gets or sets the total gibibytes written to disk by all tasks in /// all jobs created under the schedule. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "writeIOGiB")] public double WriteIOGiB { get; set; } /// <summary> /// Gets or sets the total number of tasks successfully completed /// during the given time range in jobs created under the schedule. A /// task completes successfully if it returns exit code 0. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "numSucceededTasks")] public long NumSucceededTasks { get; set; } /// <summary> /// Gets or sets the total number of tasks that failed during the given /// time range in jobs created under the schedule. A task fails if it /// exhausts its maximum retry count without returning exit code 0. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "numFailedTasks")] public long NumFailedTasks { get; set; } /// <summary> /// Gets or sets the total number of retries during the given time /// range on all tasks in all jobs created under the schedule. /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "numTaskRetries")] public long NumTaskRetries { get; set; } /// <summary> /// Gets or sets the total wait time of all tasks in all jobs created /// under the schedule. The wait time for a task is defined as the /// elapsed time between the creation of the task and the start of task /// execution. (If the task is retried due to failures, the wait time /// is the time to the most recent task execution.) /// </summary> /// <remarks> /// This value is only reported in the account lifetime statistics; it /// is not included in the job statistics. /// </remarks> [Newtonsoft.Json.JsonProperty(PropertyName = "waitTime")] public System.TimeSpan WaitTime { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (this.Url == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "Url"); } } } }
/* nwitsml Copyright 2010 Setiri LLC Derived from the jwitsml project, Copyright 2010 Statoil ASA Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ namespace witsmllib { //import java.text.DateFormat; //import java.text.SimpleDateFormat; //import java.util.Date; /** * Meta-information about a WITSML request. * * @see WitsmlAccessListener * @author <a href="mailto:info@nwitsml.org">NWitsml</a> */ using System; using System.Text; public class WitsmlAccessEvent { /** The server being accessed. Non-null. */ private WitsmlServer witsmlServer; /** The WSDL function called. Non-null. */ private String wsdlFunction; /** The WITSML type accessed. May be null if N/A. */ private String witsmlType; /** Time of request. Milliseconds since the epoch. */ private long requestTime; /** The request string. Null if N/A. */ private String request; /** The response string. Null if N/A or the operation failed. */ private String response; /** The WSDL function status code. Null if N/A. */ private Int32? statusCode; /** Server message. Null if N/A or not supplied. */ private String serverMessage; /** Server response time in milliseconds. */ private long responseTime; /** The exception thrown. Null if operation was OK. */ private Exception /*Throwable*/ throwable; /** * Create a WITSML response information instance. * * @param requestTime Time of request in milliseconds since the epoch. * @param requestXml The request XML. Non-null. * @param responseXml The response XML. May be null. * @param throwable Throwable if one was thrown, or null if not. */ internal WitsmlAccessEvent(WitsmlServer witsmlServer, String wsdlFunction, String witsmlType, long requestTime, String request, String response, Int32? statusCode, String serverMessage, Exception throwable) //Throwable throwable) { //Debug.Assert(witsmlServer != null : "witsmlServer cannot be null"; //Debug.Assert(wsdlFunction != null : "wsdlFunction cannot be null"; //Debug.Assert(requestTime <= System.currentTimeMillis() : "Request time in the future: " + requestTime; this.witsmlServer = witsmlServer; this.wsdlFunction = wsdlFunction; this.witsmlType = witsmlType; this.requestTime = requestTime; this.request = request; this.response = response; this.statusCode = statusCode; this.serverMessage = serverMessage; this.responseTime = DateTime.Now.Ticks - requestTime ; // System.currentTimeMillis() - requestTime; this.throwable = throwable; } /** * Return the WITSML server instance of this event. * * @return WITSML server instance of this event. Never null. */ public WitsmlServer getWitsmlServer() { return witsmlServer; } /** * Return name of the WSDL function being called. * * @return Name of the WSDL function being called. Never null. */ public String getWsdlFunction() { return wsdlFunction; } /** * Return the WITSML type being queried. * * @return The WITSML type being queried. Null if not applicable * for the given WSDL function. */ public String getWitsmlType() { return witsmlType; } /** * Get time of request. * * @return Time request was made. Never null. */ public DateTime? getRequestTime() { return new DateTime(requestTime); } /** * Get the client request string. Typcailly an XML query, but this * may be depend on the WSDL function being called. * * @return The request string. Null if not applicable for the WSDL * function being called. */ public String getRequest() { return request; } /** * Get the server response string. Typically an XML response, but this * may depend on the WSDL function being called. * * @return The WITSML response. Null if not applicable for the WSDL * function being called, or the operation failed for some reason. */ public String getResponse() { return response; } /** * Return the status code defined by the WSDL function. * * @return The status code defined by most WSDL functions. Null * if not applicable for the WSDL function being called. */ public Int32? getStatusCode() { return statusCode; } /** * Return the WITSML server message supplied with the response. * * @return The WITSML server message. Null if none supplied or if * not applicable for the WSDL function being called. */ public String getServerMessage() { return serverMessage; } /** * Return the response time, i.e. the time from the request was * sent to the WITSML server until the response was available * at the client. * * @return The response time in milliseconds. >= 0. */ public long getResponseTime() { return responseTime; } /** * Return the throwable if one was thrown during the request. * * @return The throwable thrown during the request, or null if * the respoinse was returned successfully. */ public Exception /*Throwable*/ getThrowable() { return throwable; } /** * Return a string representation of this instance. * * @return A string representation of this instance. Never null. */ public override String ToString() { StringBuilder s = new StringBuilder(); //DateFormat timeFormat = new SimpleDateFormat("dd.MM.yy HH:mm:ss"); String requestText = ""; if (request != null) { int length = Math.Min(50, request.Length ); //.Length()); requestText = request.Substring(0, length); } String responseText = ""; if (response != null) { int length = Math.Min(50, response.Length); //.Length()); responseText = response.Substring(0, length); } s.Append("Server...........: " + witsmlServer + "\n"); s.Append("WSDL function....: " + wsdlFunction + "\n"); s.Append("Time.............: " + requestTime.ToString("dd.MM.yy HH:mm:ss"));// timeFormat.format(new Date(requestTime)) + "\n"); s.Append("WITSML type......: " + witsmlType + "\n"); s.Append("Request..........: " + requestText + "\n"); s.Append("Response.........: " + responseText + "\n"); s.Append("Response size....: " + (response != null ? response.Length.ToString() : "0") + "\n"); s.Append("Response time....: " + responseTime + "ms\n"); s.Append("Status code......: " + statusCode + "\n"); s.Append("Server message...: " + serverMessage + "\n"); s.Append("Exception........: " + (throwable != null ? throwable.Message : "") + "\n"); return s.ToString(); } } }
/* * Copyright (c) Contributors, http://aurora-sim.org/, 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 Aurora-Sim 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.Net; using System.Reflection; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenMetaverse.StructuredData; using Aurora.Framework; using OpenSim.Services.Interfaces; namespace OpenSim.Services { public class LLLoginHandlers { private readonly ILoginService m_LocalService; private readonly bool m_Proxy; public LLLoginHandlers(ILoginService service, IConfigSource config, bool hasProxy) { m_LocalService = service; m_Proxy = hasProxy; } public XmlRpcResponse HandleXMLRPCLogin(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable) request.Params[0]; if (m_Proxy && request.Params[3] != null) { IPEndPoint ep = NetworkUtils.GetClientIPFromXFF((string) request.Params[3]); if (ep != null) // Bang! remoteClient = ep; } if (requestData != null) { if (((requestData.ContainsKey("first") && requestData["first"] != null && requestData.ContainsKey("last") && requestData["last"] != null) || requestData.ContainsKey("username") && requestData["username"] != null) && ((requestData.ContainsKey("passwd") && requestData["passwd"] != null) || (requestData.ContainsKey("web_login_key") && requestData["web_login_key"] != null))) { string first = requestData.ContainsKey("first") ? requestData["first"].ToString() : ""; string last = requestData.ContainsKey("last") ? requestData["last"].ToString() : ""; string name = requestData.ContainsKey("username") ? requestData["username"].ToString() : ""; string passwd = ""; string authType = "UserAccount"; if (!requestData.ContainsKey("web_login_key")) passwd = requestData["passwd"].ToString(); else { passwd = requestData["web_login_key"].ToString(); authType = "WebLoginKey"; } string startLocation = string.Empty; UUID scopeID = UUID.Zero; if (requestData["scope_id"] != null) scopeID = new UUID(requestData["scope_id"].ToString()); if (requestData.ContainsKey("start")) startLocation = requestData["start"].ToString(); string clientVersion = "Unknown"; if (requestData.Contains("version") && requestData["version"] != null) clientVersion = requestData["version"].ToString(); //MAC BANNING START string mac = (string) requestData["mac"]; if (mac == "") return FailedXMLRPCResponse("Bad Viewer Connection."); string channel = "Unknown"; if (requestData.Contains("channel") && requestData["channel"] != null) channel = requestData["channel"].ToString(); if (channel == "") return FailedXMLRPCResponse("Bad Viewer Connection."); string id0 = "Unknown"; if (requestData.Contains("id0") && requestData["id0"] != null) id0 = requestData["id0"].ToString(); LoginResponse reply = null; string loginName = (name == "" || name == null) ? first + " " + last : name; reply = m_LocalService.Login(UUID.Zero, loginName, "UserAccount", passwd, startLocation, scopeID, clientVersion, channel, mac, id0, remoteClient, requestData); XmlRpcResponse response = new XmlRpcResponse {Value = reply.ToHashtable()}; return response; } } return FailedXMLRPCResponse(); } public XmlRpcResponse HandleXMLRPCSetLoginLevel(XmlRpcRequest request, IPEndPoint remoteClient) { Hashtable requestData = (Hashtable) request.Params[0]; if (requestData != null) { if (requestData.ContainsKey("first") && requestData["first"] != null && requestData.ContainsKey("last") && requestData["last"] != null && requestData.ContainsKey("level") && requestData["level"] != null && requestData.ContainsKey("passwd") && requestData["passwd"] != null) { string first = requestData["first"].ToString(); string last = requestData["last"].ToString(); string passwd = requestData["passwd"].ToString(); int level = Int32.Parse(requestData["level"].ToString()); MainConsole.Instance.InfoFormat("[LOGIN]: XMLRPC Set Level to {2} Requested by {0} {1}", first, last, level); Hashtable reply = m_LocalService.SetLevel(first, last, passwd, level, remoteClient); XmlRpcResponse response = new XmlRpcResponse {Value = reply}; return response; } } XmlRpcResponse failResponse = new XmlRpcResponse(); Hashtable failHash = new Hashtable(); failHash["success"] = "false"; failResponse.Value = failHash; return failResponse; } public OSD HandleLLSDLogin(string path, OSD request, IPEndPoint remoteClient) { if (request.Type == OSDType.Map) { OSDMap map = (OSDMap) request; if (map.ContainsKey("first") && map.ContainsKey("last") && map.ContainsKey("passwd")) { string startLocation = string.Empty; if (map.ContainsKey("start")) startLocation = map["start"].AsString(); UUID scopeID = UUID.Zero; if (map.ContainsKey("scope_id")) scopeID = new UUID(map["scope_id"].AsString()); MainConsole.Instance.Info("[LOGIN]: LLSD Login Requested for: '" + map["first"].AsString() + "' '" + map["last"].AsString() + "' / " + startLocation); LoginResponse reply = null; string loginName = map["name"].AsString() == "" ? map["first"].AsString() + " " + map["last"].AsString() : map["name"].AsString(); reply = m_LocalService.Login(UUID.Zero, loginName, "UserAccount", map["passwd"].AsString(), startLocation, scopeID, "", "", "", "", remoteClient, new Hashtable()); return reply.ToOSDMap(); } } return FailedOSDResponse(); } private XmlRpcResponse FailedXMLRPCResponse() { Hashtable hash = new Hashtable(); hash["reason"] = "key"; hash["message"] = "Incomplete login credentials. Check your username and password."; hash["login"] = "false"; XmlRpcResponse response = new XmlRpcResponse {Value = hash}; return response; } private XmlRpcResponse FailedXMLRPCResponse(string message) { Hashtable hash = new Hashtable(); hash["reason"] = "key"; hash["message"] = message; hash["login"] = "false"; XmlRpcResponse response = new XmlRpcResponse {Value = hash}; return response; } private OSD FailedOSDResponse() { OSDMap map = new OSDMap(); map["reason"] = OSD.FromString("key"); map["message"] = OSD.FromString("Invalid login credentials. Check your username and passwd."); map["login"] = OSD.FromString("false"); return map; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Xml; using OpenSim.Framework; using OpenSim.Services.Base; using OpenSim.Services.Interfaces; using log4net; using Nini.Config; using OpenMetaverse; namespace OpenSim.Services.InventoryService { /// <summary> /// Basically a hack to give us a Inventory library while we don't have a inventory server /// once the server is fully implemented then should read the data from that /// </summary> public class LibraryService : ServiceBase, ILibraryService { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private InventoryFolderImpl m_LibraryRootFolder; public InventoryFolderImpl LibraryRootFolder { get { return m_LibraryRootFolder; } } private UUID libOwner = new UUID("11111111-1111-0000-0000-000100bba000"); /// <summary> /// Holds the root library folder and all its descendents. This is really only used during inventory /// setup so that we don't have to repeatedly search the tree of library folders. /// </summary> protected Dictionary<UUID, InventoryFolderImpl> libraryFolders = new Dictionary<UUID, InventoryFolderImpl>(); public LibraryService(IConfigSource config) : base(config) { string pLibrariesLocation = Path.Combine("inventory", "Libraries.xml"); string pLibName = "OpenSim Library"; IConfig libConfig = config.Configs["LibraryService"]; if (libConfig != null) { pLibrariesLocation = libConfig.GetString("DefaultLibrary", pLibrariesLocation); pLibName = libConfig.GetString("LibraryName", pLibName); } m_log.Debug("[LIBRARY]: Starting library service..."); m_LibraryRootFolder = new InventoryFolderImpl(); m_LibraryRootFolder.Owner = libOwner; m_LibraryRootFolder.ID = new UUID("00000112-000f-0000-0000-000100bba000"); m_LibraryRootFolder.Name = pLibName; m_LibraryRootFolder.ParentID = UUID.Zero; m_LibraryRootFolder.Type = (short)8; m_LibraryRootFolder.Version = (ushort)1; libraryFolders.Add(m_LibraryRootFolder.ID, m_LibraryRootFolder); LoadLibraries(pLibrariesLocation); } public InventoryItemBase CreateItem(UUID inventoryID, UUID assetID, string name, string description, int assetType, int invType, UUID parentFolderID) { InventoryItemBase item = new InventoryItemBase(); item.Owner = libOwner; item.CreatorId = libOwner.ToString(); item.ID = inventoryID; item.AssetID = assetID; item.Description = description; item.Name = name; item.AssetType = assetType; item.InvType = invType; item.Folder = parentFolderID; item.BasePermissions = 0x7FFFFFFF; item.EveryOnePermissions = 0x7FFFFFFF; item.CurrentPermissions = 0x7FFFFFFF; item.NextPermissions = 0x7FFFFFFF; return item; } /// <summary> /// Use the asset set information at path to load assets /// </summary> /// <param name="path"></param> /// <param name="assets"></param> protected void LoadLibraries(string librariesControlPath) { m_log.InfoFormat("[LIBRARY INVENTORY]: Loading library control file {0}", librariesControlPath); LoadFromFile(librariesControlPath, "Libraries control", ReadLibraryFromConfig); } /// <summary> /// Read a library set from config /// </summary> /// <param name="config"></param> protected void ReadLibraryFromConfig(IConfig config, string path) { string basePath = Path.GetDirectoryName(path); string foldersPath = Path.Combine( basePath, config.GetString("foldersFile", String.Empty)); LoadFromFile(foldersPath, "Library folders", ReadFolderFromConfig); string itemsPath = Path.Combine( basePath, config.GetString("itemsFile", String.Empty)); LoadFromFile(itemsPath, "Library items", ReadItemFromConfig); } /// <summary> /// Read a library inventory folder from a loaded configuration /// </summary> /// <param name="source"></param> private void ReadFolderFromConfig(IConfig config, string path) { InventoryFolderImpl folderInfo = new InventoryFolderImpl(); folderInfo.ID = new UUID(config.GetString("folderID", m_LibraryRootFolder.ID.ToString())); folderInfo.Name = config.GetString("name", "unknown"); folderInfo.ParentID = new UUID(config.GetString("parentFolderID", m_LibraryRootFolder.ID.ToString())); folderInfo.Type = (short)config.GetInt("type", 8); folderInfo.Owner = libOwner; folderInfo.Version = 1; if (libraryFolders.ContainsKey(folderInfo.ParentID)) { InventoryFolderImpl parentFolder = libraryFolders[folderInfo.ParentID]; libraryFolders.Add(folderInfo.ID, folderInfo); parentFolder.AddChildFolder(folderInfo); // m_log.InfoFormat("[LIBRARY INVENTORY]: Adding folder {0} ({1})", folderInfo.name, folderInfo.folderID); } else { m_log.WarnFormat( "[LIBRARY INVENTORY]: Couldn't add folder {0} ({1}) since parent folder with ID {2} does not exist!", folderInfo.Name, folderInfo.ID, folderInfo.ParentID); } } /// <summary> /// Read a library inventory item metadata from a loaded configuration /// </summary> /// <param name="source"></param> private void ReadItemFromConfig(IConfig config, string path) { InventoryItemBase item = new InventoryItemBase(); item.Owner = libOwner; item.CreatorId = libOwner.ToString(); item.ID = new UUID(config.GetString("inventoryID", m_LibraryRootFolder.ID.ToString())); item.AssetID = new UUID(config.GetString("assetID", item.ID.ToString())); item.Folder = new UUID(config.GetString("folderID", m_LibraryRootFolder.ID.ToString())); item.Name = config.GetString("name", String.Empty); item.Description = config.GetString("description", item.Name); item.InvType = config.GetInt("inventoryType", 0); item.AssetType = config.GetInt("assetType", item.InvType); item.CurrentPermissions = (uint)config.GetLong("currentPermissions", 0x7FFFFFFF); item.NextPermissions = (uint)config.GetLong("nextPermissions", 0x7FFFFFFF); item.EveryOnePermissions = (uint)config.GetLong("everyonePermissions", 0x7FFFFFFF); item.BasePermissions = (uint)config.GetLong("basePermissions", 0x7FFFFFFF); item.Flags = (uint)config.GetInt("flags", 0); if (libraryFolders.ContainsKey(item.Folder)) { InventoryFolderImpl parentFolder = libraryFolders[item.Folder]; try { parentFolder.Items.Add(item.ID, item); } catch (Exception) { m_log.WarnFormat("[LIBRARY INVENTORY] Item {1} [{0}] not added, duplicate item", item.ID, item.Name); } } else { m_log.WarnFormat( "[LIBRARY INVENTORY]: Couldn't add item {0} ({1}) since parent folder with ID {2} does not exist!", item.Name, item.ID, item.Folder); } } private delegate void ConfigAction(IConfig config, string path); /// <summary> /// Load the given configuration at a path and perform an action on each Config contained within it /// </summary> /// <param name="path"></param> /// <param name="fileDescription"></param> /// <param name="action"></param> private static void LoadFromFile(string path, string fileDescription, ConfigAction action) { if (File.Exists(path)) { try { XmlConfigSource source = new XmlConfigSource(path); for (int i = 0; i < source.Configs.Count; i++) { action(source.Configs[i], path); } } catch (XmlException e) { m_log.ErrorFormat("[LIBRARY INVENTORY]: Error loading {0} : {1}", path, e); } } else { m_log.ErrorFormat("[LIBRARY INVENTORY]: {0} file {1} does not exist!", fileDescription, path); } } /// <summary> /// Looks like a simple getter, but is written like this for some consistency with the other Request /// methods in the superclass /// </summary> /// <returns></returns> public Dictionary<UUID, InventoryFolderImpl> GetAllFolders() { Dictionary<UUID, InventoryFolderImpl> fs = new Dictionary<UUID, InventoryFolderImpl>(); fs.Add(m_LibraryRootFolder.ID, m_LibraryRootFolder); List<InventoryFolderImpl> fis = TraverseFolder(m_LibraryRootFolder); foreach (InventoryFolderImpl f in fis) { fs.Add(f.ID, f); } //return libraryFolders; return fs; } private List<InventoryFolderImpl> TraverseFolder(InventoryFolderImpl node) { List<InventoryFolderImpl> folders = node.RequestListOfFolderImpls(); List<InventoryFolderImpl> subs = new List<InventoryFolderImpl>(); foreach (InventoryFolderImpl f in folders) subs.AddRange(TraverseFolder(f)); folders.AddRange(subs); return folders; } } }
// MetadataBuilder.cs // Script#/Core/Compiler // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Xml; using ScriptSharp; using ScriptSharp.CodeModel; using ScriptSharp.ResourceModel; using ScriptSharp.ScriptModel; namespace ScriptSharp.Compiler { internal sealed class MetadataBuilder { private IErrorHandler _errorHandler; private CompilerOptions _options; private SymbolSet _symbols; private ISymbolTable _symbolTable; public MetadataBuilder(IErrorHandler errorHandler) { Debug.Assert(errorHandler != null); _errorHandler = errorHandler; } private void BuildAssembly(ParseNodeList compilationUnits) { string scriptName = GetAssemblyScriptName(compilationUnits); if (String.IsNullOrEmpty(scriptName)) { _errorHandler.ReportError("You must declare a ScriptAssembly attribute.", String.Empty); } else if (Utility.IsValidScriptName(scriptName) == false) { string errorMessage = "The ScriptAssembly attribute referenced an invalid name '{0}'. Script names must only contain letters, numbers, dots or underscores."; _errorHandler.ReportError(String.Format(errorMessage, scriptName), String.Empty); } _symbols.ScriptName = scriptName; List<AttributeNode> referenceAttributes = GetAttributes(compilationUnits, "ScriptReference"); foreach (AttributeNode attribNode in referenceAttributes) { string name = null; string identifier = null; string path = null; bool delayLoad = false; Debug.Assert((attribNode.Arguments.Count != 0) && (attribNode.Arguments[0].NodeType == ParseNodeType.Literal)); Debug.Assert(((LiteralNode)attribNode.Arguments[0]).Value is string); name = (string)((LiteralNode)attribNode.Arguments[0]).Value; if (attribNode.Arguments.Count > 1) { for (int i = 1; i < attribNode.Arguments.Count; i++) { Debug.Assert(attribNode.Arguments[1] is BinaryExpressionNode); BinaryExpressionNode propExpression = (BinaryExpressionNode)attribNode.Arguments[1]; Debug.Assert((propExpression.LeftChild.NodeType == ParseNodeType.Name)); string propName = ((NameNode)propExpression.LeftChild).Name; if (String.CompareOrdinal(propName, "Identifier") == 0) { Debug.Assert(propExpression.RightChild.NodeType == ParseNodeType.Literal); Debug.Assert(((LiteralNode)propExpression.RightChild).Value is string); identifier = (string)((LiteralNode)propExpression.RightChild).Value; } if (String.CompareOrdinal(propName, "Path") == 0) { Debug.Assert(propExpression.RightChild.NodeType == ParseNodeType.Literal); Debug.Assert(((LiteralNode)propExpression.RightChild).Value is string); path = (string)((LiteralNode)propExpression.RightChild).Value; } else if (String.CompareOrdinal(propName, "DelayLoad") == 0) { Debug.Assert(propExpression.RightChild.NodeType == ParseNodeType.Literal); Debug.Assert(((LiteralNode)propExpression.RightChild).Value is bool); delayLoad = (bool)((LiteralNode)propExpression.RightChild).Value; } } } bool newReference; ScriptReference reference = _symbols.GetDependency(name, out newReference); reference.Path = path; reference.DelayLoaded = delayLoad; if (newReference) { reference.Identifier = identifier; } } string template; if (GetScriptTemplate(compilationUnits, out template)) { _options.ScriptInfo.Template = template; } string description; string copyright; string version; GetAssemblyMetadata(compilationUnits, out description, out copyright, out version); if (description != null) { _options.ScriptInfo.Description = description; } if (copyright != null) { _options.ScriptInfo.Copyright = copyright; } if (version != null) { _options.ScriptInfo.Version = version; } } private EnumerationFieldSymbol BuildEnumField(EnumerationFieldNode fieldNode, TypeSymbol typeSymbol) { Debug.Assert(typeSymbol is EnumerationSymbol); EnumerationSymbol enumSymbol = (EnumerationSymbol)typeSymbol; TypeSymbol fieldTypeSymbol; if (enumSymbol.UseNamedValues) { fieldTypeSymbol = _symbols.ResolveIntrinsicType(IntrinsicType.String); } else { fieldTypeSymbol = _symbols.ResolveIntrinsicType(IntrinsicType.Integer); } EnumerationFieldSymbol fieldSymbol = new EnumerationFieldSymbol(fieldNode.Name, typeSymbol, fieldNode.Value, fieldTypeSymbol); BuildMemberDetails(fieldSymbol, typeSymbol, fieldNode, fieldNode.Attributes); return fieldSymbol; } private EventSymbol BuildEvent(EventDeclarationNode eventNode, TypeSymbol typeSymbol) { TypeSymbol handlerType = typeSymbol.SymbolSet.ResolveType(eventNode.Type, _symbolTable, typeSymbol); Debug.Assert(handlerType != null); if (handlerType != null) { EventSymbol eventSymbol = new EventSymbol(eventNode.Name, typeSymbol, handlerType); BuildMemberDetails(eventSymbol, typeSymbol, eventNode, eventNode.Attributes); if (eventNode.IsField) { eventSymbol.SetImplementationState(SymbolImplementationFlags.Generated); } else { if ((eventNode.Modifiers & Modifiers.Abstract) != 0) { eventSymbol.SetImplementationState(SymbolImplementationFlags.Abstract); } else if ((eventNode.Modifiers & Modifiers.Override) != 0) { eventSymbol.SetImplementationState(SymbolImplementationFlags.Override); } } if (typeSymbol.IsApplicationType == false) { AttributeNode eventAttribute = AttributeNode.FindAttribute(eventNode.Attributes, "ScriptEvent"); if ((eventAttribute != null) && (eventAttribute.Arguments != null) && (eventAttribute.Arguments.Count == 2)) { string addAccessor = (string)((LiteralNode)eventAttribute.Arguments[0]).Value; string removeAccessor = (string)((LiteralNode)eventAttribute.Arguments[1]).Value; eventSymbol.SetAccessors(addAccessor, removeAccessor); } } return eventSymbol; } return null; } private FieldSymbol BuildField(FieldDeclarationNode fieldNode, TypeSymbol typeSymbol) { TypeSymbol fieldType = typeSymbol.SymbolSet.ResolveType(fieldNode.Type, _symbolTable, typeSymbol); Debug.Assert(fieldType != null); if (fieldType != null) { FieldSymbol symbol = new FieldSymbol(fieldNode.Name, typeSymbol, fieldType); BuildMemberDetails(symbol, typeSymbol, fieldNode, fieldNode.Attributes); if (fieldNode.Initializers.Count != 0) { VariableInitializerNode initializer = (VariableInitializerNode)fieldNode.Initializers[0]; if (initializer.Value != null) { symbol.SetImplementationState(/* hasInitializer */ true); } } if (fieldNode.NodeType == ParseNodeType.ConstFieldDeclaration) { Debug.Assert(fieldNode.Initializers.Count == 1); VariableInitializerNode initializer = (VariableInitializerNode)fieldNode.Initializers[0]; if ((initializer.Value != null) && (initializer.Value.NodeType == ParseNodeType.Literal)) { symbol.SetConstant(); symbol.Value = ((LiteralToken)initializer.Value.Token).LiteralValue; } // TODO: Handle other constant cases that can be evaluated at compile // time (eg. combining enum flags) } return symbol; } return null; } private IndexerSymbol BuildIndexer(IndexerDeclarationNode indexerNode, TypeSymbol typeSymbol) { TypeSymbol indexerType = typeSymbol.SymbolSet.ResolveType(indexerNode.Type, _symbolTable, typeSymbol); Debug.Assert(indexerType != null); if (indexerType != null) { IndexerSymbol indexer = new IndexerSymbol(typeSymbol, indexerType); BuildMemberDetails(indexer, typeSymbol, indexerNode, indexerNode.Attributes); if (AttributeNode.FindAttribute(indexerNode.Attributes, "ScriptField") != null) { indexer.SetScriptIndexer(); } SymbolImplementationFlags implFlags = SymbolImplementationFlags.Regular; if (indexerNode.SetAccessor == null) { implFlags |= SymbolImplementationFlags.ReadOnly; } if ((indexerNode.Modifiers & Modifiers.Abstract) != 0) { implFlags |= SymbolImplementationFlags.Abstract; } else if ((indexerNode.Modifiers & Modifiers.Override) != 0) { implFlags |= SymbolImplementationFlags.Override; } indexer.SetImplementationState(implFlags); Debug.Assert(indexerNode.Parameters.Count != 0); foreach (ParameterNode parameterNode in indexerNode.Parameters) { ParameterSymbol paramSymbol = BuildParameter(parameterNode, indexer); if (paramSymbol != null) { paramSymbol.SetParseContext(parameterNode); indexer.AddParameter(paramSymbol); } } indexer.AddParameter(new ParameterSymbol("value", indexer, indexerType, ParameterMode.In)); return indexer; } return null; } private void BuildInterfaceAssociations(ClassSymbol classSymbol) { if (classSymbol.PrimaryPartialClass != classSymbol) { // Don't build interface associations for non-primary partial classes. return; } ICollection<InterfaceSymbol> interfaces = classSymbol.Interfaces; if ((interfaces != null) && (interfaces.Count != 0)) { foreach (InterfaceSymbol interfaceSymbol in interfaces) { foreach (MemberSymbol memberSymbol in interfaceSymbol.Members) { MemberSymbol associatedSymbol = classSymbol.GetMember(memberSymbol.Name); if (associatedSymbol != null) { associatedSymbol.SetInterfaceMember(memberSymbol); } } } } } private void BuildMemberDetails(MemberSymbol memberSymbol, TypeSymbol typeSymbol, MemberNode memberNode, ParseNodeList attributes) { if (memberSymbol.Type != SymbolType.EnumerationField) { memberSymbol.SetVisibility(GetVisibility(memberNode, typeSymbol)); } AttributeNode nameAttribute = AttributeNode.FindAttribute(attributes, "ScriptName"); if ((nameAttribute != null) && (nameAttribute.Arguments != null) && (nameAttribute.Arguments.Count != 0)) { string name = null; bool preserveCase = false; bool preserveName = false; foreach (ParseNode argNode in nameAttribute.Arguments) { Debug.Assert((argNode.NodeType == ParseNodeType.Literal) || (argNode.NodeType == ParseNodeType.BinaryExpression)); if (argNode.NodeType == ParseNodeType.Literal) { Debug.Assert(((LiteralNode)argNode).Value is string); name = (string)((LiteralNode)argNode).Value; preserveName = preserveCase = true; break; } else { BinaryExpressionNode propSetNode = (BinaryExpressionNode)argNode; if (String.CompareOrdinal(((NameNode)propSetNode.LeftChild).Name, "PreserveName") == 0) { preserveName = (bool)((LiteralNode)propSetNode.RightChild).Value; } else { preserveCase = (bool)((LiteralNode)propSetNode.RightChild).Value; if (preserveCase) { preserveName = true; break; } } } } if (String.IsNullOrEmpty(name) == false) { memberSymbol.SetTransformedName(name); } else { memberSymbol.SetNameCasing(preserveCase); if (preserveName) { memberSymbol.DisableNameTransformation(); } } } } private void BuildMembers(TypeSymbol typeSymbol) { if (typeSymbol.Type == SymbolType.Delegate) { DelegateTypeNode delegateNode = (DelegateTypeNode)typeSymbol.ParseContext; TypeSymbol returnType = typeSymbol.SymbolSet.ResolveType(delegateNode.ReturnType, _symbolTable, typeSymbol); Debug.Assert(returnType != null); if (returnType != null) { MethodSymbol invokeMethod = new MethodSymbol("Invoke", typeSymbol, returnType, MemberVisibility.Public); invokeMethod.SetTransformedName(String.Empty); // Mark the method as abstract, as there is no actual implementation of the method // to be generated invokeMethod.SetImplementationState(SymbolImplementationFlags.Abstract); typeSymbol.AddMember(invokeMethod); } return; } CustomTypeNode typeNode = (CustomTypeNode)typeSymbol.ParseContext; foreach (MemberNode member in typeNode.Members) { MemberSymbol memberSymbol = null; switch (member.NodeType) { case ParseNodeType.FieldDeclaration: case ParseNodeType.ConstFieldDeclaration: memberSymbol = BuildField((FieldDeclarationNode)member, typeSymbol); break; case ParseNodeType.PropertyDeclaration: memberSymbol = BuildPropertyAsField((PropertyDeclarationNode)member, typeSymbol); if (memberSymbol == null) { memberSymbol = BuildProperty((PropertyDeclarationNode)member, typeSymbol); } break; case ParseNodeType.IndexerDeclaration: memberSymbol = BuildIndexer((IndexerDeclarationNode)member, typeSymbol); break; case ParseNodeType.ConstructorDeclaration: case ParseNodeType.MethodDeclaration: if ((member.Modifiers & Modifiers.Extern) != 0) { // Extern methods are there for defining overload signatures, so // we just skip them as far as metadata goes. The validator has // taken care of the requirements/constraints around use of extern methods. continue; } memberSymbol = BuildMethod((MethodDeclarationNode)member, typeSymbol); break; case ParseNodeType.EventDeclaration: memberSymbol = BuildEvent((EventDeclarationNode)member, typeSymbol); break; case ParseNodeType.EnumerationFieldDeclaration: memberSymbol = BuildEnumField((EnumerationFieldNode)member, typeSymbol); break; } if (memberSymbol != null) { memberSymbol.SetParseContext(member); if ((typeSymbol.IsApplicationType == false) && ((memberSymbol.Type == SymbolType.Constructor) || (typeSymbol.GetMember(memberSymbol.Name) != null))) { // If the type is an imported type, then it is allowed to contain // overloads, and we're simply going to ignore its existence, as long // as one overload has been added to the member table. continue; } typeSymbol.AddMember(memberSymbol); if ((typeSymbol.Type == SymbolType.Class) && (memberSymbol.Type == SymbolType.Event)) { EventSymbol eventSymbol = (EventSymbol)memberSymbol; if (eventSymbol.DefaultImplementation) { // Add a private field that will serve as the backing member // later on in the conversion (eg. in non-event expressions) MemberVisibility visibility = MemberVisibility.PrivateInstance; if ((eventSymbol.Visibility & MemberVisibility.Static) != 0) { visibility |= MemberVisibility.Static; } FieldSymbol fieldSymbol = new FieldSymbol("__" + Utility.CreateCamelCaseName(eventSymbol.Name), typeSymbol, eventSymbol.AssociatedType); fieldSymbol.SetVisibility(visibility); fieldSymbol.SetParseContext(((EventDeclarationNode)eventSymbol.ParseContext).Field); typeSymbol.AddMember(fieldSymbol); } } } } } public ICollection<TypeSymbol> BuildMetadata(ParseNodeList compilationUnits, SymbolSet symbols, CompilerOptions options) { Debug.Assert(compilationUnits != null); Debug.Assert(symbols != null); _symbols = symbols; _symbolTable = symbols; _options = options; BuildAssembly(compilationUnits); List<TypeSymbol> types = new List<TypeSymbol>(); // Build all the types first. // Types need to be loaded upfront so that they can be used in resolving types associated // with members. foreach (CompilationUnitNode compilationUnit in compilationUnits) { foreach (NamespaceNode namespaceNode in compilationUnit.Members) { string namespaceName = namespaceNode.Name; NamespaceSymbol namespaceSymbol = symbols.GetNamespace(namespaceName); List<string> imports = null; Dictionary<string, string> aliases = null; ParseNodeList usingClauses = namespaceNode.UsingClauses; if ((usingClauses != null) && (usingClauses.Count != 0)) { foreach (ParseNode usingNode in namespaceNode.UsingClauses) { if (usingNode is UsingNamespaceNode) { if (imports == null) { imports = new List<string>(usingClauses.Count); } string referencedNamespace = ((UsingNamespaceNode)usingNode).ReferencedNamespace; if (imports.Contains(referencedNamespace) == false) { imports.Add(referencedNamespace); } } else { Debug.Assert(usingNode is UsingAliasNode); if (aliases == null) { aliases = new Dictionary<string, string>(); } UsingAliasNode aliasNode = (UsingAliasNode)usingNode; aliases[aliasNode.Alias] = aliasNode.TypeName; } } } // Add parent namespaces as imports in reverse order since they // are searched in that fashion. string[] namespaceParts = namespaceName.Split('.'); for (int i = namespaceParts.Length - 2; i >= 0; i--) { string partialNamespace; if (i == 0) { partialNamespace = namespaceParts[0]; } else { partialNamespace = String.Join(".", namespaceParts, 0, i + 1); } if (imports == null) { imports = new List<string>(); } if (imports.Contains(partialNamespace) == false) { imports.Add(partialNamespace); } } // Build type symbols for all user-defined types foreach (TypeNode typeNode in namespaceNode.Members) { UserTypeNode userTypeNode = typeNode as UserTypeNode; if (userTypeNode == null) { continue; } ClassSymbol partialTypeSymbol = null; bool isPartial = false; if ((userTypeNode.Modifiers & Modifiers.Partial) != 0) { partialTypeSymbol = (ClassSymbol)((ISymbolTable)namespaceSymbol).FindSymbol(userTypeNode.Name, /* context */ null, SymbolFilter.Types); if ((partialTypeSymbol != null) && partialTypeSymbol.IsApplicationType) { // This class will be considered as a partial class isPartial = true; // Merge code model information for the partial class onto the code model node // for the primary partial class. Interesting bits of information include things // such as base class etc. that is yet to be processed. CustomTypeNode partialTypeNode = (CustomTypeNode)partialTypeSymbol.ParseContext; partialTypeNode.MergePartialType((CustomTypeNode)userTypeNode); // Merge interesting bits of information onto the primary type symbol as well // representing this partial class BuildType(partialTypeSymbol, userTypeNode); } } TypeSymbol typeSymbol = BuildType(userTypeNode, namespaceSymbol); if (typeSymbol != null) { typeSymbol.SetParseContext(userTypeNode); typeSymbol.SetParentSymbolTable(symbols); if (imports != null) { typeSymbol.SetImports(imports); } if (aliases != null) { typeSymbol.SetAliases(aliases); } if (isPartial == false) { namespaceSymbol.AddType(typeSymbol); } else { // Partial types don't get added to the namespace, so we don't have // duplicated named items. However, they still do get instantiated // and processed as usual. // // The members within partial classes refer to the partial type as their parent, // and hence derive context such as the list of imports scoped to the // particular type. // However, the members will get added to the primary partial type's list of // members so they can be found. // Effectively the partial class here gets created just to hold // context of type-symbol level bits of information such as the list of // imports, that are consumed when generating code for the members defined // within a specific partial class. ((ClassSymbol)typeSymbol).SetPrimaryPartialClass(partialTypeSymbol); } types.Add(typeSymbol); } } } } // Build inheritance chains foreach (TypeSymbol typeSymbol in types) { if (typeSymbol.Type == SymbolType.Class) { BuildTypeInheritance((ClassSymbol)typeSymbol); } } // Import members foreach (TypeSymbol typeSymbol in types) { BuildMembers(typeSymbol); } // Associate interface members with interface member symbols foreach (TypeSymbol typeSymbol in types) { if (typeSymbol.Type == SymbolType.Class) { BuildInterfaceAssociations((ClassSymbol)typeSymbol); } } // Load resource values if (_symbols.HasResources) { foreach (TypeSymbol typeSymbol in types) { if (typeSymbol.Type == SymbolType.Resources) { BuildResources((ResourcesSymbol)typeSymbol); } } } // Load documentation if (_options.EnableDocComments) { Stream docCommentsStream = options.DocCommentFile.GetStream(); if (docCommentsStream != null) { try { XmlDocument docComments = new XmlDocument(); docComments.Load(docCommentsStream); symbols.SetComments(docComments); } finally { options.DocCommentFile.CloseStream(docCommentsStream); } } } return types; } private MethodSymbol BuildMethod(MethodDeclarationNode methodNode, TypeSymbol typeSymbol) { MethodSymbol method = null; if (methodNode.NodeType == ParseNodeType.ConstructorDeclaration) { method = new ConstructorSymbol(typeSymbol, (methodNode.Modifiers & Modifiers.Static) != 0); } else { TypeSymbol returnType = typeSymbol.SymbolSet.ResolveType(methodNode.Type, _symbolTable, typeSymbol); Debug.Assert(returnType != null); if (returnType != null) { method = new MethodSymbol(methodNode.Name, typeSymbol, returnType); BuildMemberDetails(method, typeSymbol, methodNode, methodNode.Attributes); ICollection<string> conditions = null; foreach (AttributeNode attrNode in methodNode.Attributes) { if (attrNode.TypeName.Equals("Conditional", StringComparison.Ordinal)) { if (conditions == null) { conditions = new List<string>(); } Debug.Assert(attrNode.Arguments[0] is LiteralNode); Debug.Assert(((LiteralNode)attrNode.Arguments[0]).Value is string); conditions.Add((string)((LiteralNode)attrNode.Arguments[0]).Value); } } if (conditions != null) { method.SetConditions(conditions); } if (typeSymbol.IsApplicationType == false) { foreach (AttributeNode attrNode in methodNode.Attributes) { if (attrNode.TypeName.Equals("ScriptMethod", StringComparison.Ordinal)) { Debug.Assert(attrNode.Arguments[0] is LiteralNode); Debug.Assert(((LiteralNode)attrNode.Arguments[0]).Value is string); method.SetSelector((string)((LiteralNode)attrNode.Arguments[0]).Value); break; } } } } } if (method != null) { if ((methodNode.Modifiers & Modifiers.Abstract) != 0) { method.SetImplementationState(SymbolImplementationFlags.Abstract); } else if ((methodNode.Modifiers & Modifiers.Override) != 0) { method.SetImplementationState(SymbolImplementationFlags.Override); } if ((methodNode.Parameters != null) && (methodNode.Parameters.Count != 0)) { foreach (ParameterNode parameterNode in methodNode.Parameters) { ParameterSymbol paramSymbol = BuildParameter(parameterNode, method); if (paramSymbol != null) { paramSymbol.SetParseContext(parameterNode); method.AddParameter(paramSymbol); } } } string scriptAlias = GetAttributeValue(methodNode.Attributes, "ScriptAlias"); if (scriptAlias != null) { method.SetAlias(scriptAlias); } } return method; } private ParameterSymbol BuildParameter(ParameterNode parameterNode, MethodSymbol methodSymbol) { ParameterMode parameterMode = ParameterMode.In; if ((parameterNode.Flags == ParameterFlags.Out) || (parameterNode.Flags == ParameterFlags.Ref)) { parameterMode = ParameterMode.InOut; } else if (parameterNode.Flags == ParameterFlags.Params) { parameterMode = ParameterMode.List; } TypeSymbol parameterType = methodSymbol.SymbolSet.ResolveType(parameterNode.Type, _symbolTable, methodSymbol); Debug.Assert(parameterType != null); if (parameterType != null) { return new ParameterSymbol(parameterNode.Name, methodSymbol, parameterType, parameterMode); } return null; } private ParameterSymbol BuildParameter(ParameterNode parameterNode, IndexerSymbol indexerSymbol) { TypeSymbol parameterType = indexerSymbol.SymbolSet.ResolveType(parameterNode.Type, _symbolTable, indexerSymbol); Debug.Assert(parameterType != null); if (parameterType != null) { return new ParameterSymbol(parameterNode.Name, indexerSymbol, parameterType, ParameterMode.In); } return null; } private PropertySymbol BuildProperty(PropertyDeclarationNode propertyNode, TypeSymbol typeSymbol) { TypeSymbol propertyType = typeSymbol.SymbolSet.ResolveType(propertyNode.Type, _symbolTable, typeSymbol); Debug.Assert(propertyType != null); if (propertyType != null) { PropertySymbol property = new PropertySymbol(propertyNode.Name, typeSymbol, propertyType); BuildMemberDetails(property, typeSymbol, propertyNode, propertyNode.Attributes); SymbolImplementationFlags implFlags = SymbolImplementationFlags.Regular; if (propertyNode.SetAccessor == null) { implFlags |= SymbolImplementationFlags.ReadOnly; } if ((propertyNode.Modifiers & Modifiers.Abstract) != 0) { implFlags |= SymbolImplementationFlags.Abstract; } else if ((propertyNode.Modifiers & Modifiers.Override) != 0) { implFlags |= SymbolImplementationFlags.Override; } property.SetImplementationState(implFlags); property.AddParameter(new ParameterSymbol("value", property, propertyType, ParameterMode.In)); return property; } return null; } private FieldSymbol BuildPropertyAsField(PropertyDeclarationNode propertyNode, TypeSymbol typeSymbol) { AttributeNode scriptFieldAttribute = AttributeNode.FindAttribute(propertyNode.Attributes, "ScriptField"); if (scriptFieldAttribute == null) { return null; } TypeSymbol fieldType = typeSymbol.SymbolSet.ResolveType(propertyNode.Type, _symbolTable, typeSymbol); Debug.Assert(fieldType != null); if (fieldType != null) { FieldSymbol symbol = new FieldSymbol(propertyNode.Name, typeSymbol, fieldType); BuildMemberDetails(symbol, typeSymbol, propertyNode, propertyNode.Attributes); string scriptAlias = GetAttributeValue(propertyNode.Attributes, "ScriptAlias"); if (scriptAlias != null) { symbol.SetAlias(scriptAlias); } return symbol; } return null; } private void BuildResources(ResourcesSymbol resourcesSymbol) { ICollection<ResXItem> items = _symbols.GetResources(resourcesSymbol.Name).Values; if (items.Count != 0) { foreach (ResXItem item in items) { FieldSymbol fieldSymbol = resourcesSymbol.GetMember(item.Name) as FieldSymbol; Debug.Assert(fieldSymbol != null); if (fieldSymbol != null) { fieldSymbol.Value = item.Value; } } } } private TypeSymbol BuildType(UserTypeNode typeNode, NamespaceSymbol namespaceSymbol) { Debug.Assert(typeNode != null); Debug.Assert(namespaceSymbol != null); TypeSymbol typeSymbol = null; ParseNodeList attributes = typeNode.Attributes; if (typeNode.Type == TokenType.Class) { CustomTypeNode customTypeNode = (CustomTypeNode)typeNode; Debug.Assert(customTypeNode != null); if (AttributeNode.FindAttribute(attributes, "ScriptObject") != null) { typeSymbol = new RecordSymbol(typeNode.Name, namespaceSymbol); } else if (AttributeNode.FindAttribute(attributes, "ScriptResources") != null) { typeSymbol = new ResourcesSymbol(typeNode.Name, namespaceSymbol); } else { typeSymbol = new ClassSymbol(typeNode.Name, namespaceSymbol); NameNode baseTypeNameNode = null; if (customTypeNode.BaseTypes.Count != 0) { baseTypeNameNode = customTypeNode.BaseTypes[0] as NameNode; } if ((baseTypeNameNode != null) && (String.CompareOrdinal(baseTypeNameNode.Name, "TestClass") == 0)) { ((ClassSymbol)typeSymbol).SetTestClass(); } } } else if (typeNode.Type == TokenType.Interface) { typeSymbol = new InterfaceSymbol(typeNode.Name, namespaceSymbol); } else if (typeNode.Type == TokenType.Enum) { bool flags = false; AttributeNode flagsAttribute = AttributeNode.FindAttribute(typeNode.Attributes, "Flags"); if (flagsAttribute != null) { flags = true; } typeSymbol = new EnumerationSymbol(typeNode.Name, namespaceSymbol, flags); } else if (typeNode.Type == TokenType.Delegate) { typeSymbol = new DelegateSymbol(typeNode.Name, namespaceSymbol); typeSymbol.SetTransformedName("Function"); typeSymbol.SetIgnoreNamespace(); } Debug.Assert(typeSymbol != null, "Unexpected type node " + typeNode.Type); if (typeSymbol != null) { if ((typeNode.Modifiers & Modifiers.Public) != 0) { typeSymbol.SetPublic(); } BuildType(typeSymbol, typeNode); if (namespaceSymbol.Name.EndsWith(".Tests", StringComparison.Ordinal) || (namespaceSymbol.Name.IndexOf(".Tests.", StringComparison.Ordinal) > 0)) { typeSymbol.SetTestType(); } } return typeSymbol; } private void BuildType(TypeSymbol typeSymbol, UserTypeNode typeNode) { Debug.Assert(typeSymbol != null); Debug.Assert(typeNode != null); ParseNodeList attributes = typeNode.Attributes; if (AttributeNode.FindAttribute(attributes, "ScriptImport") != null) { ScriptReference dependency = null; AttributeNode dependencyAttribute = AttributeNode.FindAttribute(attributes, "ScriptDependency"); if (dependencyAttribute != null) { string dependencyIdentifier = null; Debug.Assert((dependencyAttribute.Arguments.Count != 0) && (dependencyAttribute.Arguments[0].NodeType == ParseNodeType.Literal)); Debug.Assert(((LiteralNode)dependencyAttribute.Arguments[0]).Value is string); string dependencyName = (string)((LiteralNode)dependencyAttribute.Arguments[0]).Value; if (dependencyAttribute.Arguments.Count > 1) { Debug.Assert(dependencyAttribute.Arguments[1] is BinaryExpressionNode); BinaryExpressionNode propExpression = (BinaryExpressionNode)dependencyAttribute.Arguments[1]; Debug.Assert((propExpression.LeftChild.NodeType == ParseNodeType.Name) && (String.CompareOrdinal(((NameNode)propExpression.LeftChild).Name, "Identifier") == 0)); Debug.Assert(propExpression.RightChild.NodeType == ParseNodeType.Literal); Debug.Assert(((LiteralNode)propExpression.RightChild).Value is string); dependencyIdentifier = (string)((LiteralNode)propExpression.RightChild).Value; } dependency = new ScriptReference(dependencyName, dependencyIdentifier); } typeSymbol.SetImported(dependency); if ((AttributeNode.FindAttribute(attributes, "ScriptIgnoreNamespace") != null) || (dependency == null)) { typeSymbol.SetIgnoreNamespace(); } else { typeSymbol.ScriptNamespace = dependency.Identifier; } } if (AttributeNode.FindAttribute(attributes, "PreserveName") != null) { typeSymbol.DisableNameTransformation(); } string scriptName = GetAttributeValue(attributes, "ScriptName"); if (scriptName != null) { typeSymbol.SetTransformedName(scriptName); } if (typeNode.Type == TokenType.Class) { AttributeNode extensionAttribute = AttributeNode.FindAttribute(attributes, "ScriptExtension"); if (extensionAttribute != null) { Debug.Assert(extensionAttribute.Arguments[0] is LiteralNode); Debug.Assert(((LiteralNode)extensionAttribute.Arguments[0]).Value is string); string extendee = (string)((LiteralNode)extensionAttribute.Arguments[0]).Value; Debug.Assert(String.IsNullOrEmpty(extendee) == false); ((ClassSymbol)typeSymbol).SetExtenderClass(extendee); } AttributeNode moduleAttribute = AttributeNode.FindAttribute(attributes, "ScriptModule"); if (moduleAttribute != null) { ((ClassSymbol)typeSymbol).SetModuleClass(); } if ((typeNode.Modifiers & Modifiers.Static) != 0) { ((ClassSymbol)typeSymbol).SetStaticClass(); } } if (typeNode.Type == TokenType.Enum) { AttributeNode constantsAttribute = AttributeNode.FindAttribute(attributes, "ScriptConstants"); if (constantsAttribute != null) { bool useNames = false; if ((constantsAttribute.Arguments != null) && (constantsAttribute.Arguments.Count != 0)) { Debug.Assert(constantsAttribute.Arguments[0] is BinaryExpressionNode); BinaryExpressionNode propExpression = (BinaryExpressionNode)constantsAttribute.Arguments[0]; Debug.Assert((propExpression.LeftChild.NodeType == ParseNodeType.Name) && (String.CompareOrdinal(((NameNode)propExpression.LeftChild).Name, "UseNames") == 0)); Debug.Assert(propExpression.RightChild.NodeType == ParseNodeType.Literal); Debug.Assert(((LiteralNode)propExpression.RightChild).Value is bool); useNames = (bool)((LiteralNode)propExpression.RightChild).Value; } if (useNames) { ((EnumerationSymbol)typeSymbol).SetNamedValues(); } else { ((EnumerationSymbol)typeSymbol).SetNumericValues(); } } } } private void BuildTypeInheritance(ClassSymbol classSymbol) { if (classSymbol.PrimaryPartialClass != classSymbol) { // Don't build type inheritance for non-primary partial classes. return; } CustomTypeNode customTypeNode = (CustomTypeNode)classSymbol.ParseContext; if ((customTypeNode.BaseTypes != null) && (customTypeNode.BaseTypes.Count != 0)) { ClassSymbol baseClass = null; List<InterfaceSymbol> interfaces = null; foreach (NameNode node in customTypeNode.BaseTypes) { TypeSymbol baseTypeSymbol = (TypeSymbol)_symbolTable.FindSymbol(node.Name, classSymbol, SymbolFilter.Types); Debug.Assert(baseTypeSymbol != null); if (baseTypeSymbol.Type == SymbolType.Class) { Debug.Assert(baseClass == null); baseClass = (ClassSymbol)baseTypeSymbol; } else { Debug.Assert(baseTypeSymbol.Type == SymbolType.Interface); if (interfaces == null) { interfaces = new List<InterfaceSymbol>(); } interfaces.Add((InterfaceSymbol)baseTypeSymbol); } } if ((baseClass != null) || (interfaces != null)) { classSymbol.SetInheritance(baseClass, interfaces); } } } private void GetAssemblyMetadata(ParseNodeList compilationUnits, out string description, out string copyright, out string version) { description = null; copyright = null; version = null; foreach (CompilationUnitNode compilationUnit in compilationUnits) { foreach (AttributeBlockNode attribBlock in compilationUnit.Attributes) { if (description == null) { description = GetAttributeValue(attribBlock.Attributes, "AssemblyDescription"); } if (copyright == null) { copyright = GetAttributeValue(attribBlock.Attributes, "AssemblyCopyright"); } if (version == null) { version = GetAttributeValue(attribBlock.Attributes, "AssemblyFileVersion"); } } } } private string GetAssemblyScriptName(ParseNodeList compilationUnits) { foreach (CompilationUnitNode compilationUnit in compilationUnits) { foreach (AttributeBlockNode attribBlock in compilationUnit.Attributes) { string scriptName = GetAttributeValue(attribBlock.Attributes, "ScriptAssembly"); if (scriptName != null) { return scriptName; } } } return null; } private List<AttributeNode> GetAttributes(ParseNodeList compilationUnits, string attributeName) { List<AttributeNode> attributes = new List<AttributeNode>(); foreach (CompilationUnitNode compilationUnit in compilationUnits) { foreach (AttributeBlockNode attribBlock in compilationUnit.Attributes) { foreach (AttributeNode attribNode in attribBlock.Attributes) { if (attribNode.TypeName.Equals(attributeName, StringComparison.Ordinal)) { attributes.Add(attribNode); } } } } return attributes; } private string GetAttributeValue(ParseNodeList attributes, string attributeName) { AttributeNode node = AttributeNode.FindAttribute(attributes, attributeName); if ((node != null) && (node.Arguments.Count != 0) && (node.Arguments[0].NodeType == ParseNodeType.Literal)) { Debug.Assert(((LiteralNode)node.Arguments[0]).Value is string); return (string)((LiteralNode)node.Arguments[0]).Value; } return null; } private bool GetScriptTemplate(ParseNodeList compilationUnits, out string template) { template = null; foreach (CompilationUnitNode compilationUnit in compilationUnits) { foreach (AttributeBlockNode attribBlock in compilationUnit.Attributes) { template = GetAttributeValue(attribBlock.Attributes, "ScriptTemplate"); if (template != null) { return true; } } } return false; } private MemberVisibility GetVisibility(MemberNode node, TypeSymbol typeSymbol) { if (typeSymbol.Type == SymbolType.Interface) { return MemberVisibility.Public; } MemberVisibility visibility = MemberVisibility.PrivateInstance; if (((node.Modifiers & Modifiers.Static) != 0) || (node.NodeType == ParseNodeType.ConstFieldDeclaration)) { visibility |= MemberVisibility.Static; } if ((node.Modifiers & Modifiers.Public) != 0) { visibility |= MemberVisibility.Public; } else { if ((node.Modifiers & Modifiers.Protected) != 0) { visibility |= MemberVisibility.Protected; } if ((node.Modifiers & Modifiers.Internal) != 0) { visibility |= MemberVisibility.Internal; } } return visibility; } } }
// // This file was generated by the BinaryNotes compiler. // See http://bnotes.sourceforge.net // Any modifications to this file will be lost upon recompilation of the source ASN.1. // using GSF.ASN1; using GSF.ASN1.Attributes; using GSF.ASN1.Coders; using GSF.ASN1.Types; namespace GSF.MMS.Model { [ASN1PreparedElement] [ASN1Sequence(Name = "Named_Variable_instance", IsSet = false)] public class Named_Variable_instance : IASN1PreparedElement { private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(Named_Variable_instance)); private DefinitionChoiceType definition_; private ObjectName name_; [ASN1Element(Name = "name", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)] public ObjectName Name { get { return name_; } set { name_ = value; } } [ASN1Element(Name = "definition", IsOptional = false, HasTag = false, HasDefaultValue = false)] public DefinitionChoiceType Definition { get { return definition_; } set { definition_ = value; } } public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } [ASN1PreparedElement] [ASN1Choice(Name = "definition")] public class DefinitionChoiceType : IASN1PreparedElement { private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DefinitionChoiceType)); private DetailsSequenceType details_; private bool details_selected; private ObjectIdentifier reference_; private bool reference_selected; [ASN1ObjectIdentifier(Name = "")] [ASN1Element(Name = "reference", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)] public ObjectIdentifier Reference { get { return reference_; } set { selectReference(value); } } [ASN1Element(Name = "details", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)] public DetailsSequenceType Details { get { return details_; } set { selectDetails(value); } } public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } public bool isReferenceSelected() { return reference_selected; } public void selectReference(ObjectIdentifier val) { reference_ = val; reference_selected = true; details_selected = false; } public bool isDetailsSelected() { return details_selected; } public void selectDetails(DetailsSequenceType val) { details_ = val; details_selected = true; reference_selected = false; } [ASN1PreparedElement] [ASN1Sequence(Name = "details", IsSet = false)] public class DetailsSequenceType : IASN1PreparedElement { private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(DetailsSequenceType)); private Access_Control_List_instance accessControl_; private Address address_; private bool address_present; private string meaning_; private bool meaning_present; private TypeDescription typeDescription_; [ASN1Element(Name = "accessControl", IsOptional = false, HasTag = true, Tag = 3, HasDefaultValue = false)] public Access_Control_List_instance AccessControl { get { return accessControl_; } set { accessControl_ = value; } } [ASN1Element(Name = "typeDescription", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = false)] public TypeDescription TypeDescription { get { return typeDescription_; } set { typeDescription_ = value; } } [ASN1Element(Name = "address", IsOptional = true, HasTag = true, Tag = 5, HasDefaultValue = false)] public Address Address { get { return address_; } set { address_ = value; address_present = true; } } [ASN1String(Name = "", StringType = UniversalTags.VisibleString, IsUCS = false)] [ASN1Element(Name = "meaning", IsOptional = true, HasTag = true, Tag = 6, HasDefaultValue = false)] public string Meaning { get { return meaning_; } set { meaning_ = value; meaning_present = true; } } public void initWithDefaults() { } public IASN1PreparedElementData PreparedData { get { return preparedData; } } public bool isAddressPresent() { return address_present; } public bool isMeaningPresent() { return meaning_present; } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable enable using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Primitives; using Microsoft.Net.Http.Headers; // Keep the type public for Security repo as it would be a breaking change to change the accessor now. // Make this type internal for other repos as it could be used by multiple projects and having it public causes type conflicts. #if SECURITY namespace Microsoft.AspNetCore.Authentication.Cookies { /// <summary> /// This handles cookies that are limited by per cookie length. It breaks down long cookies for responses, and reassembles them /// from requests. /// </summary> public class ChunkingCookieManager : ICookieManager { #else namespace Microsoft.AspNetCore.Internal { /// <summary> /// This handles cookies that are limited by per cookie length. It breaks down long cookies for responses, and reassembles them /// from requests. /// </summary> internal class ChunkingCookieManager { #endif /// <summary> /// The default maximum size of characters in a cookie to send back to the client. /// </summary> public const int DefaultChunkSize = 4050; private const string ChunkKeySuffix = "C"; private const string ChunkCountPrefix = "chunks-"; /// <summary> /// Initializes a new instance of <see cref="ChunkingCookieManager"/>. /// </summary> public ChunkingCookieManager() { // Lowest common denominator. Safari has the lowest known limit (4093), and we leave little extra just in case. // See http://browsercookielimits.x64.me/. // Leave at least 40 in case CookiePolicy tries to add 'secure', 'samesite=strict' and/or 'httponly'. ChunkSize = DefaultChunkSize; } /// <summary> /// The maximum size of cookie to send back to the client. If a cookie exceeds this size it will be broken down into multiple /// cookies. Set this value to null to disable this behavior. The default is 4090 characters, which is supported by all /// common browsers. /// /// Note that browsers may also have limits on the total size of all cookies per domain, and on the number of cookies per domain. /// </summary> public int? ChunkSize { get; set; } /// <summary> /// Throw if not all chunks of a cookie are available on a request for re-assembly. /// </summary> public bool ThrowForPartialCookies { get; set; } // Parse the "chunks-XX" to determine how many chunks there should be. private static int ParseChunksCount(string? value) { if (value != null && value.StartsWith(ChunkCountPrefix, StringComparison.Ordinal)) { if (int.TryParse(value.AsSpan(ChunkCountPrefix.Length), NumberStyles.None, CultureInfo.InvariantCulture, out var chunksCount)) { return chunksCount; } } return 0; } /// <summary> /// Get the reassembled cookie. Non chunked cookies are returned normally. /// Cookies with missing chunks just have their "chunks-XX" header returned. /// </summary> /// <param name="context"></param> /// <param name="key"></param> /// <returns>The reassembled cookie, if any, or null.</returns> public string? GetRequestCookie(HttpContext context, string key) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } var requestCookies = context.Request.Cookies; var value = requestCookies[key]; var chunksCount = ParseChunksCount(value); if (chunksCount > 0) { var chunks = new string[chunksCount]; for (var chunkId = 1; chunkId <= chunksCount; chunkId++) { var chunk = requestCookies[key + ChunkKeySuffix + chunkId.ToString(CultureInfo.InvariantCulture)]; if (string.IsNullOrEmpty(chunk)) { if (ThrowForPartialCookies) { var totalSize = 0; for (int i = 0; i < chunkId - 1; i++) { totalSize += chunks[i].Length; } throw new FormatException( string.Format( CultureInfo.CurrentCulture, "The chunked cookie is incomplete. Only {0} of the expected {1} chunks were found, totaling {2} characters. A client size limit may have been exceeded.", chunkId - 1, chunksCount, totalSize)); } // Missing chunk, abort by returning the original cookie value. It may have been a false positive? return value; } chunks[chunkId - 1] = chunk; } return string.Join(string.Empty, chunks); } return value; } /// <summary> /// Appends a new response cookie to the Set-Cookie header. If the cookie is larger than the given size limit /// then it will be broken down into multiple cookies as follows: /// Set-Cookie: CookieName=chunks-3; path=/ /// Set-Cookie: CookieNameC1=Segment1; path=/ /// Set-Cookie: CookieNameC2=Segment2; path=/ /// Set-Cookie: CookieNameC3=Segment3; path=/ /// </summary> /// <param name="context"></param> /// <param name="key"></param> /// <param name="value"></param> /// <param name="options"></param> public void AppendResponseCookie(HttpContext context, string key, string? value, CookieOptions options) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var responseCookies = context.Response.Cookies; if (string.IsNullOrEmpty(value)) { responseCookies.Append(key, string.Empty, options); return; } var template = new SetCookieHeaderValue(key) { Domain = options.Domain, Expires = options.Expires, SameSite = (Net.Http.Headers.SameSiteMode)options.SameSite, HttpOnly = options.HttpOnly, Path = options.Path, Secure = options.Secure, MaxAge = options.MaxAge, }; var templateLength = template.ToString().Length; // Normal cookie if (!ChunkSize.HasValue || ChunkSize.Value > templateLength + value.Length) { responseCookies.Append(key, value, options); } else if (ChunkSize.Value < templateLength + 10) { // 10 is the minimum data we want to put in an individual cookie, including the cookie chunk identifier "CXX". // No room for data, we can't chunk the options and name throw new InvalidOperationException("The cookie key and options are larger than ChunksSize, leaving no room for data."); } else { // Break the cookie down into multiple cookies. // Key = CookieName, value = "Segment1Segment2Segment2" // Set-Cookie: CookieName=chunks-3; path=/ // Set-Cookie: CookieNameC1="Segment1"; path=/ // Set-Cookie: CookieNameC2="Segment2"; path=/ // Set-Cookie: CookieNameC3="Segment3"; path=/ var dataSizePerCookie = ChunkSize.Value - templateLength - 3; // Budget 3 chars for the chunkid. var cookieChunkCount = (int)Math.Ceiling(value.Length * 1.0 / dataSizePerCookie); var keyValuePairs = new KeyValuePair<string, string>[cookieChunkCount + 1]; keyValuePairs[0] = KeyValuePair.Create(key, ChunkCountPrefix + cookieChunkCount.ToString(CultureInfo.InvariantCulture)); var offset = 0; for (var chunkId = 1; chunkId <= cookieChunkCount; chunkId++) { var remainingLength = value.Length - offset; var length = Math.Min(dataSizePerCookie, remainingLength); var segment = value.Substring(offset, length); offset += length; keyValuePairs[chunkId] = KeyValuePair.Create(string.Concat(key, ChunkKeySuffix, chunkId.ToString(CultureInfo.InvariantCulture)), segment); } responseCookies.Append(keyValuePairs, options); } } /// <summary> /// Deletes the cookie with the given key by setting an expired state. If a matching chunked cookie exists on /// the request, delete each chunk. /// </summary> /// <param name="context"></param> /// <param name="key"></param> /// <param name="options"></param> public void DeleteCookie(HttpContext context, string key, CookieOptions options) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (key == null) { throw new ArgumentNullException(nameof(key)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } var keys = new List<string> { key + "=" }; var requestCookie = context.Request.Cookies[key]; var chunks = ParseChunksCount(requestCookie); if (chunks > 0) { for (var i = 1; i <= chunks + 1; i++) { var subkey = key + ChunkKeySuffix + i.ToString(CultureInfo.InvariantCulture); keys.Add(subkey + "="); } } var domainHasValue = !string.IsNullOrEmpty(options.Domain); var pathHasValue = !string.IsNullOrEmpty(options.Path); Func<string, bool> rejectPredicate; Func<string, bool> predicate = value => keys.Any(k => value.StartsWith(k, StringComparison.OrdinalIgnoreCase)); if (domainHasValue) { rejectPredicate = value => predicate(value) && value.IndexOf("domain=" + options.Domain, StringComparison.OrdinalIgnoreCase) != -1; } else if (pathHasValue) { rejectPredicate = value => predicate(value) && value.IndexOf("path=" + options.Path, StringComparison.OrdinalIgnoreCase) != -1; } else { rejectPredicate = value => predicate(value); } var responseHeaders = context.Response.Headers; var existingValues = responseHeaders.SetCookie; if (!StringValues.IsNullOrEmpty(existingValues)) { var values = existingValues.ToArray(); var newValues = new List<string>(); for (var i = 0; i < values.Length; i++) { var value = values[i]!; if (!rejectPredicate(value)) { newValues.Add(value); } } responseHeaders.SetCookie = new StringValues(newValues.ToArray()); } var responseCookies = context.Response.Cookies; var keyValuePairs = new KeyValuePair<string, string>[chunks + 1]; keyValuePairs[0] = KeyValuePair.Create(key, string.Empty); for (var i = 1; i <= chunks; i++) { keyValuePairs[i] = KeyValuePair.Create(string.Concat(key, "C", i.ToString(CultureInfo.InvariantCulture)), string.Empty); } responseCookies.Append(keyValuePairs, new CookieOptions() { Path = options.Path, Domain = options.Domain, SameSite = options.SameSite, Secure = options.Secure, IsEssential = options.IsEssential, Expires = DateTimeOffset.UnixEpoch, HttpOnly = options.HttpOnly, }); } } }
using System; using System.Collections; using System.IO; using System.Linq; using System.Text.RegularExpressions; using System.Xml; using Umbraco.Core.Cache; using Umbraco.Core.IO; using umbraco.cms.businesslogic.cache; using umbraco.DataLayer; using Umbraco.Core; namespace umbraco.cms.businesslogic.web { /// <summary> /// Summary description for StyleSheet. /// </summary> public class StyleSheet : CMSNode { private string _filename = ""; private string _content = ""; private StylesheetProperty[] _properties; public static Guid ModuleObjectType = new Guid(Constants.ObjectTypes.Stylesheet); public string Filename { get { return _filename; } set { //move old file _filename = value; SqlHelper.ExecuteNonQuery(string.Format("update cmsStylesheet set filename = '{0}' where nodeId = {1}", _filename, Id)); InvalidateCache(); } } public string Content { get { return _content; } set { _content = value; SqlHelper.ExecuteNonQuery("update cmsStylesheet set content = @content where nodeId = @id", SqlHelper.CreateParameter("@content", this.Content), SqlHelper.CreateParameter("@id", this.Id)); InvalidateCache(); } } public StylesheetProperty[] Properties { get { if (_properties == null) { var tmp = this.ChildrenOfAllObjectTypes; var retVal = new StylesheetProperty[tmp.Length]; for (var i = 0; i < tmp.Length; i++) { //So this will go get cached properties but yet the above call to ChildrenOfAllObjectTypes is not cached :/ retVal[i] = StylesheetProperty.GetStyleSheetProperty(tmp[i].Id); } _properties = retVal; } return _properties; } } //static bool isInitialized = false; public StyleSheet(Guid id) : base(id) { SetupStyleSheet(true, true); } public StyleSheet(int id) : base(id) { SetupStyleSheet(true, true); } public StyleSheet(int id, bool setupStyleProperties, bool loadContentFromFile) : base(id) { SetupStyleSheet(loadContentFromFile, setupStyleProperties); } /// <summary> /// Used to persist object changes to the database. In Version3.0 it's just a stub for future compatibility /// </summary> public override void Save() { var e = new SaveEventArgs(); FireBeforeSave(e); if (!e.Cancel) { base.Save(); FireAfterSave(e); } } private void SetupStyleSheet(bool loadFileData, bool updateStyleProperties) { // Get stylesheet data using (var dr = SqlHelper.ExecuteReader("select filename, content from cmsStylesheet where nodeid = " + Id)) { if (dr.Read()) { if (!dr.IsNull("filename")) _filename = dr.GetString("filename"); // Get Content from db or file if (!loadFileData) { if (!dr.IsNull("content")) _content = dr.GetString("content"); } else if (File.Exists(IOHelper.MapPath(String.Format("{0}/{1}.css", SystemDirectories.Css, this.Text)))) { var propertiesContent = String.Empty; using (var re = File.OpenText(IOHelper.MapPath(String.Format("{0}/{1}.css", SystemDirectories.Css, this.Text)))) { string input = null; _content = string.Empty; // NH: Updates the reader to support properties var readingProperties = false; while ((input = re.ReadLine()) != null && true) { if (input.Contains("EDITOR PROPERTIES")) { readingProperties = true; } else if (readingProperties) { propertiesContent += input.Replace("\n", "") + "\n"; } else { _content += input.Replace("\n", "") + "\n"; } } } // update properties if (updateStyleProperties) { if (propertiesContent != String.Empty) { ParseProperties(propertiesContent); } } } } } } private void ParseProperties(string propertiesContent) { var m = Regex.Matches(propertiesContent, "([^{]*){([^}]*)}", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); foreach (Match match in m) { var groups = match.Groups; var cssClass = groups[1].Value.Replace("\n", "").Replace("\r", "").Trim().Trim(Environment.NewLine.ToCharArray()); var cssCode = groups[2].Value.Trim(Environment.NewLine.ToCharArray()); foreach (StylesheetProperty sp in this.Properties) if (sp.Alias == cssClass && sp.value != cssCode) // check before setting to avoid invalidating cache unecessarily sp.value = cssCode; } } public static StyleSheet MakeNew(BusinessLogic.User user, string Text, string FileName, string Content) { // validate if node ends with css, if it does we'll remove it as we append it later if (Text.ToLowerInvariant().EndsWith(".css")) { Text = Text.Substring(0, Text.Length - 4); } // Create the umbraco node var newNode = CMSNode.MakeNew(-1, ModuleObjectType, user.Id, 1, Text, Guid.NewGuid()); // Create the stylesheet data SqlHelper.ExecuteNonQuery(string.Format("insert into cmsStylesheet (nodeId, filename, content) values ('{0}','{1}',@content)", newNode.Id, FileName), SqlHelper.CreateParameter("@content", Content)); // save to file to avoid file coherency issues var newCss = new StyleSheet(newNode.Id, false, false); var e = new NewEventArgs(); newCss.OnNew(e); return newCss; } public static StyleSheet[] GetAll() { var dbStylesheets = new ArrayList(); var topNodeIds = CMSNode.TopMostNodeIds(ModuleObjectType); //StyleSheet[] retval = new StyleSheet[topNodeIds.Length]; for (int i = 0; i < topNodeIds.Length; i++) { //retval[i] = new StyleSheet(topNodeIds[i]); dbStylesheets.Add(new StyleSheet(topNodeIds[i]).Text.ToLower()); } var fileStylesheets = new ArrayList(); var fileListing = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.Css + "/")); foreach (var file in fileListing.GetFiles("*.css")) { if (!dbStylesheets.Contains(file.Name.Replace(file.Extension, "").ToLower())) { fileStylesheets.Add(file.Name.Replace(file.Extension, "")); } } var retval = new StyleSheet[dbStylesheets.Count + fileStylesheets.Count]; for (int i = 0; i < topNodeIds.Length; i++) { retval[i] = new StyleSheet(topNodeIds[i]); } for (int i = 0; i < fileStylesheets.Count; i++) { string content = string.Empty; using (StreamReader re = File.OpenText(IOHelper.MapPath(string.Format("{0}/{1}.css", SystemDirectories.Css, fileStylesheets[i])))) { content = re.ReadToEnd(); } retval[dbStylesheets.Count + i] = StyleSheet.MakeNew(new umbraco.BusinessLogic.User(0), fileStylesheets[i].ToString(), fileStylesheets[i].ToString(), content); } Array.Sort(retval, 0, retval.Length, new StyleSheetComparer()); return retval; } public StylesheetProperty AddProperty(string Alias, BusinessLogic.User u) { return StylesheetProperty.MakeNew(Alias, this, u); } public override void delete() { var e = new DeleteEventArgs(); FireBeforeDelete(e); if (!e.Cancel) { File.Delete(IOHelper.MapPath(String.Format("{0}/{1}.css", SystemDirectories.Css, this.Text))); foreach (var p in Properties.Where(p => p != null)) { p.delete(); } SqlHelper.ExecuteNonQuery("delete from cmsStylesheet where nodeId = @nodeId", SqlHelper.CreateParameter("@nodeId", this.Id)); base.delete(); FireAfterDelete(e); } } public void saveCssToFile() { using (StreamWriter SW = File.CreateText(IOHelper.MapPath(string.Format("{0}/{1}.css", SystemDirectories.Css, this.Text)))) { string tmpCss = this.Content ; tmpCss += "/* EDITOR PROPERTIES - PLEASE DON'T DELETE THIS LINE TO AVOID DUPLICATE PROPERTIES */\n"; foreach (StylesheetProperty p in this.Properties) { tmpCss += p + "\n"; } SW.Write(tmpCss); } } public XmlNode ToXml(XmlDocument xd) { XmlNode doc = xd.CreateElement("Stylesheet"); doc.AppendChild(xmlHelper.addTextNode(xd, "Name", this.Text)); doc.AppendChild(xmlHelper.addTextNode(xd, "FileName", this.Filename)); doc.AppendChild(xmlHelper.addCDataNode(xd, "Content", this.Content)); if (this.Properties.Length > 0) { XmlNode properties = xd.CreateElement("Properties"); foreach (StylesheetProperty sp in this.Properties) { XmlElement prop = xd.CreateElement("Property"); prop.AppendChild(xmlHelper.addTextNode(xd, "Name", sp.Text)); prop.AppendChild(xmlHelper.addTextNode(xd, "Alias", sp.Alias)); prop.AppendChild(xmlHelper.addTextNode(xd, "Value", sp.value)); properties.AppendChild(prop); } doc.AppendChild(properties); } return doc; } public static StyleSheet GetStyleSheet(int id, bool setupStyleProperties, bool loadContentFromFile) { return ApplicationContext.Current.ApplicationCache.GetCacheItem( GetCacheKey(id), TimeSpan.FromMinutes(30), () => { try { return new StyleSheet(id, setupStyleProperties, loadContentFromFile); } catch { return null; } }); } [Obsolete("Stylesheet cache is automatically invalidated by Umbraco when a stylesheet is saved or deleted")] public void InvalidateCache() { ApplicationContext.Current.ApplicationCache.ClearCacheItem(GetCacheKey(Id)); } private static string GetCacheKey(int id) { return CacheKeys.StylesheetCacheKey + id; } //EVENTS /// <summary> /// The save event handler /// </summary> public delegate void SaveEventHandler(StyleSheet sender, SaveEventArgs e); /// <summary> /// The new event handler /// </summary> public delegate void NewEventHandler(StyleSheet sender, NewEventArgs e); /// <summary> /// The delete event handler /// </summary> public delegate void DeleteEventHandler(StyleSheet sender, DeleteEventArgs e); /// <summary> /// Occurs when [before save]. /// </summary> public static event SaveEventHandler BeforeSave; /// <summary> /// Raises the <see cref="E:BeforeSave"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected virtual void FireBeforeSave(SaveEventArgs e) { if (BeforeSave != null) BeforeSave(this, e); } /// <summary> /// Occurs when [after save]. /// </summary> public static event SaveEventHandler AfterSave; /// <summary> /// Raises the <see cref="E:AfterSave"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected virtual void FireAfterSave(SaveEventArgs e) { if (AfterSave != null) AfterSave(this, e); } /// <summary> /// Occurs when [new]. /// </summary> public static event NewEventHandler New; /// <summary> /// Raises the <see cref="E:New"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected virtual void OnNew(NewEventArgs e) { if (New != null) New(this, e); } /// <summary> /// Occurs when [before delete]. /// </summary> public static event DeleteEventHandler BeforeDelete; /// <summary> /// Raises the <see cref="E:BeforeDelete"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected virtual void FireBeforeDelete(DeleteEventArgs e) { if (BeforeDelete != null) BeforeDelete(this, e); } /// <summary> /// Occurs when [after delete]. /// </summary> public static event DeleteEventHandler AfterDelete; /// <summary> /// Raises the <see cref="E:AfterDelete"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected virtual void FireAfterDelete(DeleteEventArgs e) { if (AfterDelete != null) AfterDelete(this, e); } public static StyleSheet GetByName(string name) { try { int id = SqlHelper.ExecuteScalar<int>("SELECT id FROM umbracoNode WHERE text = @text AND nodeObjectType = @objType ", SqlHelper.CreateParameter("@text", name), SqlHelper.CreateParameter("@objType", StyleSheet.ModuleObjectType)); return new StyleSheet(id); } catch { return null; } } public static StyleSheet Import(XmlNode n, umbraco.BusinessLogic.User u) { string stylesheetName = xmlHelper.GetNodeValue(n.SelectSingleNode("Name")); StyleSheet s = GetByName(stylesheetName); if (s == null) { s = StyleSheet.MakeNew( u, stylesheetName, xmlHelper.GetNodeValue(n.SelectSingleNode("FileName")), xmlHelper.GetNodeValue(n.SelectSingleNode("Content"))); } foreach (XmlNode prop in n.SelectNodes("Properties/Property")) { string alias = xmlHelper.GetNodeValue(prop.SelectSingleNode("Alias")); var sp = s.Properties.SingleOrDefault(p => p != null && p.Alias == alias); string name = xmlHelper.GetNodeValue(prop.SelectSingleNode("Name")); if (sp == default(StylesheetProperty)) { sp = StylesheetProperty.MakeNew( name, s, u); } else { sp.Text = name; } sp.Alias = alias; sp.value = xmlHelper.GetNodeValue(prop.SelectSingleNode("Value")); } s.saveCssToFile(); return s; } } public class StyleSheetComparer : IComparer { public StyleSheetComparer() { //default constructor } public Int32 Compare(Object pFirstObject, Object pObjectToCompare) { if (pFirstObject is StyleSheet) { return String.Compare(((StyleSheet)pFirstObject).Text, ((StyleSheet)pObjectToCompare).Text); } else { return 0; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.Extensions.Logging; using Maw.Domain.Email; using Maw.Domain.Identity; using MawAuth.ViewModels.Account; using SignInRes = Microsoft.AspNetCore.Identity.SignInResult; using Microsoft.AspNetCore.Authentication; using Duende.IdentityServer.Services; using MawAuth.ViewModels.Email; using Mvc.RenderViewToString; namespace MawAuth.Controllers { [Route("account")] public class AccountController : Controller { const byte LOGIN_AREA_FORM = 1; const string EmailFrom = "webmaster@mikeandwan.us"; readonly ILogger _log; readonly IIdentityServerInteractionService _interaction; readonly IUserRepository _repo; readonly SignInManager<MawUser> _signInManager; readonly UserManager<MawUser> _userMgr; readonly ILoginService _loginService; readonly RazorViewToStringRenderer _razorRenderer; readonly IEmailService _emailService; public AccountController(ILogger<AccountController> log, IIdentityServerInteractionService interaction, IUserRepository userRepository, SignInManager<MawUser> signInManager, UserManager<MawUser> userManager, ILoginService loginService, IEmailService emailService, RazorViewToStringRenderer razorRenderer) { _log = log ?? throw new ArgumentNullException(nameof(log)); _interaction = interaction ?? throw new ArgumentNullException(nameof(interaction)); _repo = userRepository ?? throw new ArgumentNullException(nameof(userRepository)); _signInManager = signInManager ?? throw new ArgumentNullException(nameof(signInManager)); _userMgr = userManager ?? throw new ArgumentNullException(nameof(userManager)); _loginService = loginService ?? throw new ArgumentNullException(nameof(loginService)); _emailService = emailService ?? throw new ArgumentNullException(nameof(emailService)); _razorRenderer = razorRenderer ?? throw new ArgumentNullException(nameof(razorRenderer)); } [HttpGet("login")] public async Task<IActionResult> Login(string returnUrl) { var vm = new LoginModel() { ReturnUrl = returnUrl, ExternalSchemes = await GetExternalLoginSchemes().ConfigureAwait(false) }; return View(vm); } [HttpPost("login")] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } model.WasAttempted = true; model.ExternalSchemes = await GetExternalLoginSchemes().ConfigureAwait(false); if (!ModelState.IsValid) { LogValidationErrors(); return View(model); } var result = await _loginService.AuthenticateAsync(model.Username, model.Password, LOGIN_AREA_FORM).ConfigureAwait(false); _log.LogInformation("Login complete"); if (result == SignInRes.Success) { return RedirectToLocal(model.ReturnUrl); } else { ModelState.AddModelError("Error", "Sorry, a user was not found with this username/password combination"); } return View(model); } [HttpGet("external-login")] public IActionResult ExternalLogin(string provider, string returnUrl) { var props = new AuthenticationProperties() { RedirectUri = Url.Action(nameof(ExternalLoginCallback)), Items = { { "returnUrl", returnUrl }, { "scheme", provider }, } }; return Challenge(props, provider); } [HttpGet("external-login-callback")] public async Task<IActionResult> ExternalLoginCallback() { var result = await HttpContext.AuthenticateAsync(Duende.IdentityServer.IdentityServerConstants.ExternalCookieAuthenticationScheme).ConfigureAwait(false); var items = result?.Properties?.Items; if (result?.Succeeded != true || items == null || !items.ContainsKey("scheme")) { _log.LogError("Unable to obtain external login info"); return View(); } var provider = items["scheme"]; var email = result.Principal?.Claims?.FirstOrDefault(x => x.Type == ClaimTypes.Email); if (email == null) { _log.LogError("Unable to obtain email from External Authentication Provider {Provider}", provider); return View(); } var user = await _userMgr.FindByEmailAsync(email.Value).ConfigureAwait(false); if (user != null) { if (user.IsExternalAuthEnabled(provider)) { // now sign in the local user await _signInManager.SignInAsync(user, false).ConfigureAwait(false); await _loginService.LogExternalLoginAttemptAsync(email.Value, provider, true).ConfigureAwait(false); // delete temporary cookie used during external authentication await HttpContext.SignOutAsync(Duende.IdentityServer.IdentityServerConstants.ExternalCookieAuthenticationScheme).ConfigureAwait(false); _log.LogInformation("User {Username} logged in with {Provider} provider.", user.Username, provider); // validate return URL and redirect back to authorization endpoint or a local page var returnUrl = result.Properties.Items["returnUrl"]; if (_interaction.IsValidReturnUrl(returnUrl) || Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { // we should have a valid redirect url, but if they login and we don't, // let them review there profile... return RedirectToAction(nameof(EditProfile)); } } else { _log.LogError("User {Username} unable to login with {Provider} as they have not yet opted-in for this provider.", user.Username, provider); } } await _loginService.LogExternalLoginAttemptAsync(email.Value, provider, false).ConfigureAwait(false); return View(); } [HttpGet("logout")] public async Task<IActionResult> Logout(string logoutId) { var logout = await _interaction.GetLogoutContextAsync(logoutId).ConfigureAwait(false); await _signInManager.SignOutAsync().ConfigureAwait(false); #pragma warning disable SCS0027 return Redirect(logout.PostLogoutRedirectUri); #pragma warning restore SCS0027 } [HttpGet("forgot-password")] public IActionResult ForgotPassword() { return View(new ForgotPasswordModel()); } [HttpPost("forgot-password")] [ValidateAntiForgeryToken] public async Task<IActionResult> ForgotPassword(ForgotPasswordModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } model.WasEmailAttempted = true; if (ModelState.IsValid) { var user = await _userMgr.FindByEmailAsync(model.Email).ConfigureAwait(false); if (user == null) { _log.LogInformation("Unable to find user with email [{Email}].", model.Email); return View(model); } // legacy users might not have the security stamp set. if so, set it here, as a non-null security stamp is required for this to work if (string.IsNullOrEmpty(user.SecurityStamp)) { await _userMgr.UpdateSecurityStampAsync(user).ConfigureAwait(false); } var code = await _userMgr.GeneratePasswordResetTokenAsync(user).ConfigureAwait(false); var callbackUrl = Url.Action("ResetPassword", "Account", new { user.Email, code }, Request.Scheme); _log.LogInformation("Sending password reset email to user: {User}", user.Name); var emailModel = new ResetPasswordEmailModel { Title = "Reset Password", CallbackUrl = callbackUrl }; var body = await _razorRenderer.RenderViewToStringAsync("~/Views/Email/ResetPassword.cshtml", emailModel).ConfigureAwait(false); await _emailService.SendHtmlAsync(user.Email, EmailFrom, "Reset Password for mikeandwan.us", body).ConfigureAwait(false); model.WasSuccessful = true; return View(model); } else { LogValidationErrors(); } return View(model); } [HttpGet("reset-password")] public async Task<IActionResult> ResetPassword(string code) { var model = new ResetPasswordModel(); await TryUpdateModelAsync<ResetPasswordModel>(model, string.Empty, x => x.Email, x => x.Code).ConfigureAwait(false); ModelState.Clear(); return View(model); } [HttpPost("reset-password")] [ValidateAntiForgeryToken] public async Task<IActionResult> ResetPassword(ResetPasswordModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } model.ResetAttempted = true; if (ModelState.IsValid) { var user = await _repo.GetUserByEmailAsync(model.Email).ConfigureAwait(false); var result = await _userMgr.ResetPasswordAsync(user, model.Code, model.NewPassword).ConfigureAwait(false); if (result.Succeeded) { model.WasReset = true; } else { _log.LogWarning("reset password result: {Result}", result.ToString()); AddErrors(result); } } else { LogValidationErrors(); } return View(model); } [Authorize] [HttpGet("change-password")] public IActionResult ChangePassword() { var m = new ChangePasswordModel(); return View(m); } [HttpPost("change-password")] [Authorize] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } model.ChangeAttempted = true; if (ModelState.IsValid) { var user = await _repo.GetUserAsync(User.Identity.Name).ConfigureAwait(false); var result = await _userMgr.ChangePasswordAsync(user, model.CurrentPassword, model.NewPassword).ConfigureAwait(false); if (result.Succeeded) { model.ChangeSucceeded = true; } else { _log.LogWarning("change password result: {Result}", result.ToString()); AddErrors(result); } } else { LogValidationErrors(); } return View(model); } [HttpGet("access-denied")] public IActionResult AccessDenied() { return View(); } [Authorize] [HttpGet("edit-profile")] public async Task<IActionResult> EditProfile() { ViewBag.States = await GetStateSelectListItemsAsync().ConfigureAwait(false); ViewBag.Countries = await GetCountrySelectListItemsAsync().ConfigureAwait(false); var user = await _userMgr.FindByNameAsync(User.Identity.Name).ConfigureAwait(false); var model = new ProfileModel { Username = user.Username, FirstName = user.FirstName, LastName = user.LastName, Email = user.Email, EnableGithubAuth = user.IsGithubAuthEnabled, EnableGoogleAuth = user.IsGoogleAuthEnabled, EnableMicrosoftAuth = user.IsMicrosoftAuthEnabled, EnableTwitterAuth = user.IsTwitterAuthEnabled }; return View(model); } [HttpPost("edit-profile")] [Authorize] [ValidateAntiForgeryToken] public async Task<IActionResult> EditProfile(ProfileModel model) { if (model == null) { throw new ArgumentNullException(nameof(model)); } ViewBag.States = await GetStateSelectListItemsAsync().ConfigureAwait(false); ViewBag.Countries = await GetCountrySelectListItemsAsync().ConfigureAwait(false); model.WasAttempted = true; model.Username = User.Identity.Name; if (ModelState.IsValid) { var user = await _userMgr.FindByNameAsync(User.Identity.Name).ConfigureAwait(false); user.FirstName = model.FirstName; user.LastName = model.LastName; user.Email = model.Email; user.IsGithubAuthEnabled = model.EnableGithubAuth; user.IsGoogleAuthEnabled = model.EnableGoogleAuth; user.IsMicrosoftAuthEnabled = model.EnableMicrosoftAuth; user.IsTwitterAuthEnabled = model.EnableTwitterAuth; await _repo.UpdateUserAsync(user).ConfigureAwait(false); model.WasUpdated = true; } else { LogValidationErrors(); } return View(model); } async Task<IEnumerable<SelectListItem>> GetStateSelectListItemsAsync() { var states = await _repo.GetStatesAsync().ConfigureAwait(false); return states.Select(x => new SelectListItem { Value = x.Code, Text = x.Name }); } async Task<IEnumerable<SelectListItem>> GetCountrySelectListItemsAsync() { var countries = await _repo.GetCountriesAsync().ConfigureAwait(false); return countries.Select(x => new SelectListItem { Value = x.Code, Text = x.Name }); } async Task<IEnumerable<ExternalLoginScheme>> GetExternalLoginSchemes() { var schemes = await _signInManager.GetExternalAuthenticationSchemesAsync().ConfigureAwait(false); return schemes .Select(x => new ExternalLoginScheme(x)) .OrderBy(x => x.ExternalAuth.DisplayName); } void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return Redirect("/"); //return RedirectToAction(nameof(HomeController.Index), "Home"); } } void LogValidationErrors() { var errs = ModelState.Values.SelectMany(v => v.Errors); foreach (var err in errs) { _log.LogWarning("validation error: {ValidationError}", err.ErrorMessage); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Resources; using System.Runtime.ExceptionServices; using Xunit; using Xunit.NetCore.Extensions; namespace System.Tests { public class AppDomainTests : RemoteExecutorTestBase { public AppDomainTests() { string sourceTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, "AssemblyResolveTests.dll"); string destTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, "AssemblyResolveTests", "AssemblyResolveTests.dll"); if (File.Exists(sourceTestAssemblyPath)) { Directory.CreateDirectory(Path.GetDirectoryName(destTestAssemblyPath)); File.Copy(sourceTestAssemblyPath, destTestAssemblyPath, true); File.Delete(sourceTestAssemblyPath); } sourceTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, "TestAppOutsideOfTPA.exe"); destTestAssemblyPath = Path.Combine(Environment.CurrentDirectory, "TestAppOutsideOfTPA", "TestAppOutsideOfTPA.exe"); if (File.Exists(sourceTestAssemblyPath)) { Directory.CreateDirectory(Path.GetDirectoryName(destTestAssemblyPath)); File.Copy(sourceTestAssemblyPath, destTestAssemblyPath, true); File.Delete(sourceTestAssemblyPath); } } [Fact] public void CurrentDomain_Not_Null() { Assert.NotNull(AppDomain.CurrentDomain); } [Fact] public void CurrentDomain_Idempotent() { Assert.Equal(AppDomain.CurrentDomain, AppDomain.CurrentDomain); } [Fact] public void BaseDirectory_Same_As_AppContext() { Assert.Equal(AppDomain.CurrentDomain.BaseDirectory, AppContext.BaseDirectory); } [Fact] public void RelativeSearchPath_Is_Null() { Assert.Null(AppDomain.CurrentDomain.RelativeSearchPath); } [Fact] public void UnhandledException_Add_Remove() { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler); AppDomain.CurrentDomain.UnhandledException -= new UnhandledExceptionEventHandler(MyHandler); } [Fact] public void UnhandledException_NotCalled_When_Handled() { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(NotExpectedToBeCalledHandler); try { throw new Exception(); } catch { } AppDomain.CurrentDomain.UnhandledException -= new UnhandledExceptionEventHandler(NotExpectedToBeCalledHandler); } [ActiveIssue(12716)] [PlatformSpecific(~TestPlatforms.OSX)] // Unhandled exception on a separate process causes xunit to crash on osx [Fact] public void UnhandledException_Called() { System.IO.File.Delete("success.txt"); RemoteInvokeOptions options = new RemoteInvokeOptions(); options.CheckExitCode = false; RemoteInvoke(() => { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler); throw new Exception("****This Unhandled Exception is Expected****"); #pragma warning disable 0162 return SuccessExitCode; #pragma warning restore 0162 }, options).Dispose(); Assert.True(System.IO.File.Exists("success.txt")); } static void NotExpectedToBeCalledHandler(object sender, UnhandledExceptionEventArgs args) { Assert.True(false, "UnhandledException handler not expected to be called"); } static void MyHandler(object sender, UnhandledExceptionEventArgs args) { System.IO.File.Create("success.txt"); } [Fact] public void DynamicDirectory_Null() { Assert.Null(AppDomain.CurrentDomain.DynamicDirectory); } [Fact] public void FriendlyName() { string s = AppDomain.CurrentDomain.FriendlyName; Assert.NotNull(s); string expected = Assembly.GetEntryAssembly().GetName().Name; Assert.Equal(expected, s); } [Fact] public void Id() { Assert.Equal(1, AppDomain.CurrentDomain.Id); } [Fact] public void IsFullyTrusted() { Assert.True(AppDomain.CurrentDomain.IsFullyTrusted); } [Fact] public void IsHomogenous() { Assert.True(AppDomain.CurrentDomain.IsHomogenous); } [Fact] public void FirstChanceException_Add_Remove() { EventHandler<FirstChanceExceptionEventArgs> handler = (sender, e) => { }; AppDomain.CurrentDomain.FirstChanceException += handler; AppDomain.CurrentDomain.FirstChanceException -= handler; } [Fact] public void FirstChanceException_Called() { bool flag = false; EventHandler<FirstChanceExceptionEventArgs> handler = (sender, e) => { Exception ex = (Exception) e.Exception; if (ex is FirstChanceTestException) { flag = !flag; } }; AppDomain.CurrentDomain.FirstChanceException += handler; try { throw new FirstChanceTestException("testing"); } catch { } AppDomain.CurrentDomain.FirstChanceException -= handler; Assert.True(flag, "FirstChanceHandler not called"); } class FirstChanceTestException : Exception { public FirstChanceTestException(string message) : base(message) { } } [Fact] public void ProcessExit_Add_Remove() { EventHandler handler = (sender, e) => { }; AppDomain.CurrentDomain.ProcessExit += handler; AppDomain.CurrentDomain.ProcessExit -= handler; } [Fact] public void ProcessExit_Called() { System.IO.File.Delete("success.txt"); RemoteInvoke(() => { EventHandler handler = (sender, e) => { System.IO.File.Create("success.txt"); }; AppDomain.CurrentDomain.ProcessExit += handler; return SuccessExitCode; }).Dispose(); Assert.True(System.IO.File.Exists("success.txt")); } [Fact] public void ApplyPolicy() { AssertExtensions.Throws<ArgumentNullException>("assemblyName", () => { AppDomain.CurrentDomain.ApplyPolicy(null); }); Assert.Throws<ArgumentException>(() => { AppDomain.CurrentDomain.ApplyPolicy(""); }); Assert.Equal(AppDomain.CurrentDomain.ApplyPolicy(Assembly.GetEntryAssembly().FullName), Assembly.GetEntryAssembly().FullName); } [Fact] public void CreateDomain() { AssertExtensions.Throws<ArgumentNullException>("friendlyName", () => { AppDomain.CreateDomain(null); }); Assert.Throws<PlatformNotSupportedException>(() => { AppDomain.CreateDomain("test"); }); } [Fact] public void ExecuteAssemblyByName() { string name = "TestApp"; var assembly = Assembly.Load(name); Assert.Equal(5, AppDomain.CurrentDomain.ExecuteAssemblyByName(assembly.FullName)); Assert.Equal(10, AppDomain.CurrentDomain.ExecuteAssemblyByName(assembly.FullName, new string[2] {"2", "3"})); Assert.Throws<FormatException>(() => AppDomain.CurrentDomain.ExecuteAssemblyByName(assembly.FullName, new string[1] {"a"})); AssemblyName assemblyName = assembly.GetName(); assemblyName.CodeBase = null; Assert.Equal(105, AppDomain.CurrentDomain.ExecuteAssemblyByName(assemblyName, new string[3] {"50", "25", "25"})); } [Fact] public void ExecuteAssembly() { string name = Path.Combine(Environment.CurrentDirectory, "TestAppOutsideOfTPA", "TestAppOutsideOfTPA.exe"); AssertExtensions.Throws<ArgumentNullException>("assemblyFile", () => AppDomain.CurrentDomain.ExecuteAssembly(null)); Assert.Throws<FileNotFoundException>(() => AppDomain.CurrentDomain.ExecuteAssembly("NonExistentFile.exe")); Assert.Throws<PlatformNotSupportedException>(() => AppDomain.CurrentDomain.ExecuteAssembly(name, new string[2] {"2", "3"}, null, Configuration.Assemblies.AssemblyHashAlgorithm.SHA1)); Assert.Equal(5, AppDomain.CurrentDomain.ExecuteAssembly(name)); Assert.Equal(10, AppDomain.CurrentDomain.ExecuteAssembly(name, new string[2] { "2", "3" })); } [Fact] public void GetData_SetData() { AssertExtensions.Throws<ArgumentNullException>("name", () => { AppDomain.CurrentDomain.SetData(null, null); }); AppDomain.CurrentDomain.SetData("", null); Assert.Null(AppDomain.CurrentDomain.GetData("")); AppDomain.CurrentDomain.SetData("randomkey", 4); Assert.Equal(4, AppDomain.CurrentDomain.GetData("randomkey")); } [Fact] public void IsCompatibilitySwitchSet() { Assert.Throws<ArgumentNullException>(() => { AppDomain.CurrentDomain.IsCompatibilitySwitchSet(null); }); Assert.Throws<ArgumentException>(() => { AppDomain.CurrentDomain.IsCompatibilitySwitchSet("");}); Assert.Null(AppDomain.CurrentDomain.IsCompatibilitySwitchSet("randomSwitch")); } [Fact] public void IsDefaultAppDomain() { Assert.True(AppDomain.CurrentDomain.IsDefaultAppDomain()); } [Fact] public void IsFinalizingForUnload() { Assert.False(AppDomain.CurrentDomain.IsFinalizingForUnload()); } [Fact] public void toString() { string actual = AppDomain.CurrentDomain.ToString(); string expected = "Name:" + AppDomain.CurrentDomain.FriendlyName + Environment.NewLine + "There are no context policies."; Assert.Equal(expected, actual); } [Fact] public void Unload() { AssertExtensions.Throws<ArgumentNullException>("domain", () => { AppDomain.Unload(null);}); Assert.Throws<CannotUnloadAppDomainException>(() => { AppDomain.Unload(AppDomain.CurrentDomain); }); } [Fact] public void Load() { AssemblyName assemblyName = typeof(AppDomainTests).Assembly.GetName(); assemblyName.CodeBase = null; Assert.NotNull(AppDomain.CurrentDomain.Load(assemblyName)); Assert.NotNull(AppDomain.CurrentDomain.Load(typeof(AppDomainTests).Assembly.FullName)); Assembly assembly = typeof(AppDomainTests).Assembly; byte[] aBytes = System.IO.File.ReadAllBytes(assembly.Location); Assert.NotNull(AppDomain.CurrentDomain.Load(aBytes)); } [Fact] public void ReflectionOnlyGetAssemblies() { Assert.Equal(Array.Empty<Assembly>(), AppDomain.CurrentDomain.ReflectionOnlyGetAssemblies()); } [Fact] public void MonitoringIsEnabled() { Assert.False(AppDomain.MonitoringIsEnabled); Assert.Throws<ArgumentException>(() => {AppDomain.MonitoringIsEnabled = false;}); Assert.Throws<PlatformNotSupportedException>(() => {AppDomain.MonitoringIsEnabled = true;}); } [Fact] public void MonitoringSurvivedMemorySize() { Assert.Throws<InvalidOperationException>(() => { var t = AppDomain.CurrentDomain.MonitoringSurvivedMemorySize; }); } [Fact] public void MonitoringSurvivedProcessMemorySize() { Assert.Throws<InvalidOperationException>(() => { var t = AppDomain.MonitoringSurvivedProcessMemorySize; }); } [Fact] public void MonitoringTotalAllocatedMemorySize() { Assert.Throws<InvalidOperationException>(() => { var t = AppDomain.CurrentDomain.MonitoringTotalAllocatedMemorySize; } ); } [Fact] public void MonitoringTotalProcessorTime() { Assert.Throws<InvalidOperationException>(() => { var t = AppDomain.CurrentDomain.MonitoringTotalProcessorTime; } ); } #pragma warning disable 618 [Fact] public void GetCurrentThreadId() { Assert.True(AppDomain.GetCurrentThreadId() == Environment.CurrentManagedThreadId); } [Fact] public void ShadowCopyFiles() { Assert.False(AppDomain.CurrentDomain.ShadowCopyFiles); } [Fact] public void AppendPrivatePath() { AppDomain.CurrentDomain.AppendPrivatePath("test"); } [Fact] public void ClearPrivatePath() { AppDomain.CurrentDomain.ClearPrivatePath(); } [Fact] public void ClearShadowCopyPath() { AppDomain.CurrentDomain.ClearShadowCopyPath(); } [Fact] public void SetCachePath() { AppDomain.CurrentDomain.SetCachePath("test"); } [Fact] public void SetShadowCopyFiles() { AppDomain.CurrentDomain.SetShadowCopyFiles(); } [Fact] public void SetShadowCopyPath() { AppDomain.CurrentDomain.SetShadowCopyPath("test"); } #pragma warning restore 618 [Fact] public void GetAssemblies() { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); Assert.NotNull(assemblies); Assert.True(assemblies.Length > 0, "There must be assemblies already loaded in the process"); AppDomain.CurrentDomain.Load(typeof(AppDomainTests).Assembly.GetName().FullName); Assembly[] assemblies1 = AppDomain.CurrentDomain.GetAssemblies(); // Another thread could have loaded an assembly hence not checking for equality Assert.True(assemblies1.Length >= assemblies.Length, "Assembly.Load of an already loaded assembly should not cause another load"); Assembly.LoadFile(typeof(AppDomain).Assembly.Location); Assembly[] assemblies2 = AppDomain.CurrentDomain.GetAssemblies(); Assert.True(assemblies2.Length > assemblies.Length, "Assembly.LoadFile should cause an increase in GetAssemblies list"); int ctr = 0; foreach (var a in assemblies2) { if (a.Location == typeof(AppDomain).Assembly.Location) ctr++; } foreach (var a in assemblies) { if (a.Location == typeof(AppDomain).Assembly.Location) ctr--; } Assert.True(ctr > 0, "Assembly.LoadFile should cause file to be loaded again"); } [Fact] public void AssemblyLoad() { bool AssemblyLoadFlag = false; AssemblyLoadEventHandler handler = (sender, args) => { if (args.LoadedAssembly.FullName.Equals(typeof(AppDomainTests).Assembly.FullName)) { AssemblyLoadFlag = !AssemblyLoadFlag; } }; AppDomain.CurrentDomain.AssemblyLoad += handler; try { Assembly.LoadFile(typeof(AppDomainTests).Assembly.Location); } finally { AppDomain.CurrentDomain.AssemblyLoad -= handler; } Assert.True(AssemblyLoadFlag); } [Fact] public void AssemblyResolve() { RemoteInvoke(() => { ResolveEventHandler handler = (sender, e) => { return Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "AssemblyResolveTests", "AssemblyResolveTests.dll")); }; AppDomain.CurrentDomain.AssemblyResolve += handler; Type t = Type.GetType("AssemblyResolveTests.Class1, AssemblyResolveTests", true); Assert.NotNull(t); return SuccessExitCode; }).Dispose(); } [Fact] public void AssemblyResolve_RequestingAssembly() { RemoteInvoke(() => { Assembly a = Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "TestAppOutsideOfTPA", "TestAppOutsideOfTPA.exe")); ResolveEventHandler handler = (sender, e) => { Assert.Equal(e.RequestingAssembly, a); return Assembly.LoadFile(Path.Combine(Environment.CurrentDirectory, "AssemblyResolveTests", "AssemblyResolveTests.dll")); }; AppDomain.CurrentDomain.AssemblyResolve += handler; Type ptype = a.GetType("Program"); MethodInfo myMethodInfo = ptype.GetMethod("foo"); object ret = myMethodInfo.Invoke(null, null); Assert.NotNull(ret); return SuccessExitCode; }).Dispose(); } [Fact] public void TypeResolve() { Assert.Throws<TypeLoadException>(() => Type.GetType("Program", true)); ResolveEventHandler handler = (sender, args) => { return Assembly.Load("TestApp"); }; AppDomain.CurrentDomain.TypeResolve += handler; Type t; try { t = Type.GetType("Program", true); } finally { AppDomain.CurrentDomain.TypeResolve -= handler; } Assert.NotNull(t); } [Fact] public void ResourceResolve() { ResourceManager res = new ResourceManager(typeof(FxResources.TestApp.SR)); Assert.Throws<MissingManifestResourceException>(() => res.GetString("Message")); ResolveEventHandler handler = (sender, args) => { return Assembly.Load("TestApp"); }; AppDomain.CurrentDomain.ResourceResolve += handler; String s; try { s = res.GetString("Message"); } finally { AppDomain.CurrentDomain.ResourceResolve -= handler; } Assert.Equal(s, "Happy Halloween"); } [Fact] public void SetThreadPrincipal() { Assert.Throws<ArgumentNullException>(() => {AppDomain.CurrentDomain.SetThreadPrincipal(null);}); var identity = new System.Security.Principal.GenericIdentity("NewUser"); var principal = new System.Security.Principal.GenericPrincipal(identity, null); AppDomain.CurrentDomain.SetThreadPrincipal(principal); } } } namespace FxResources.TestApp { class SR { } }
// *********************************************************************** // Copyright (c) 2011 Charlie Poole, Rob Prouse // // 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.Reflection; using System.Globalization; using NUnit.Common; using NUnit.Options; using NUnit.Framework; namespace NUnitLite.Tests { using System.Collections.Generic; using System.IO; using System.Linq; using NUnit.TestUtilities; [TestFixture] public class CommandLineTests { #region Argument PreProcessor Tests [TestCase("--arg", "--arg")] [TestCase("--ArG", "--ArG")] [TestCase("--arg1 --arg2", "--arg1", "--arg2")] [TestCase("--arg1 data --arg2", "--arg1", "data", "--arg2")] [TestCase("")] [TestCase(" ")] [TestCase("\"--arg 1\" --arg2", "--arg 1", "--arg2")] [TestCase("--arg1 \"--arg 2\"", "--arg1", "--arg 2")] [TestCase("\"--arg 1\" \"--arg 2\"", "--arg 1", "--arg 2")] [TestCase("\"--arg 1\" \"--arg 2\" arg3 \"arg 4\"", "--arg 1", "--arg 2", "arg3", "arg 4")] [TestCase("--arg1 \"--arg 2\" arg3 \"arg 4\"", "--arg1", "--arg 2", "arg3", "arg 4")] [TestCase("\"--arg 1\" \"--arg 2\" arg3 \"arg 4\" \"--arg 1\" \"--arg 2\" arg3 \"arg 4\"", "--arg 1", "--arg 2", "arg3", "arg 4", "--arg 1", "--arg 2", "arg3", "arg 4")] [TestCase("\"--arg\"", "--arg")] [TestCase("\"--arg 1\"", "--arg 1")] [TestCase("\"--arg abc\"", "--arg abc")] [TestCase("\"--arg abc\"", "--arg abc")] [TestCase("\" --arg abc \"", " --arg abc ")] [TestCase("\"--arg=abc\"", "--arg=abc")] [TestCase("\"--arg=aBc\"", "--arg=aBc")] [TestCase("\"--arg = abc\"", "--arg = abc")] [TestCase("\"--arg=abc,xyz\"", "--arg=abc,xyz")] [TestCase("\"--arg=abc, xyz\"", "--arg=abc, xyz")] [TestCase("\"@arg = ~ ` ! @ # $ % ^ & * ( ) _ - : ; + ' ' { } [ ] | \\ ? / . , , xYz\"", "@arg = ~ ` ! @ # $ % ^ & * ( ) _ - : ; + ' ' { } [ ] | \\ ? / . , , xYz")] public void GetArgsFromCommandLine(string cmdline, params string[] expectedArgs) { var actualArgs = CommandLineOptions.GetArgs(cmdline); Assert.AreEqual(expectedArgs, actualArgs); } [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 --filearg2", "--arg1", "--filearg1", "--filearg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1\r\n--filearg2", "--arg1", "--filearg1", "--filearg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 data", "--arg1", "--filearg1", "data", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 \"data in quotes\"", "--arg1", "--filearg1", "data in quotes", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 \"data in quotes with 'single' quotes\"", "--arg1", "--filearg1", "data in quotes with 'single' quotes", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 \"data in quotes with /slashes/\"", "--arg1", "--filearg1", "data in quotes with /slashes/", "--arg2")] [TestCase("--arg1 @file1.txt --arg2 @file2.txt", "file1.txt:--filearg1 --filearg2,file2.txt:--filearg3", "--arg1", "--filearg1", "--filearg2", "--arg2", "--filearg3")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:", "--arg1", "--arg2")] // Blank lines [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\n\n\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\n \n\t\t\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\r\n\r\n\r\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\r\n \r\n\t\t\r\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--filearg1 --filearg2\r\n\n--filearg3 --filearg4", "--arg1", "--filearg1", "--filearg2", "--filearg3", "--filearg4", "--arg2")] // Comments [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\nThis is NOT treated as a COMMENT\n--fileArg2", "--arg1", "--fileArg1", "This", "is", "NOT", "treated", "as", "a", "COMMENT", "--fileArg2", "--arg2")] [TestCase("--arg1 @file1.txt --arg2", "file1.txt:--fileArg1\n#This is treated as a COMMENT\n--fileArg2", "--arg1", "--fileArg1", "--fileArg2", "--arg2")] // Nested files [TestCase("--arg1 @file1.txt --arg2 @file2.txt", "file1.txt:--filearg1 --filearg2,file2.txt:--filearg3 @file3.txt,file3.txt:--filearg4", "--arg1", "--filearg1", "--filearg2", "--arg2", "--filearg3", "--filearg4")] // Where clauses [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where test==somelongname", "testfile.dll", "--where", "test==somelongname", "--arg2")] // NOTE: The next is not valid. Where clause is spread over several args and therefore won't parse. Quotes are required. [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where test == somelongname", "testfile.dll", "--where", "test", "==", "somelongname", "--arg2")] [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where \"test == somelongname\"", "testfile.dll", "--where", "test == somelongname", "--arg2")] [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where\n \"test == somelongname\"", "testfile.dll", "--where", "test == somelongname", "--arg2")] [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where\n \"test == somelongname or test == /another long name/ or cat == SomeCategory\"", "testfile.dll", "--where", "test == somelongname or test == /another long name/ or cat == SomeCategory", "--arg2")] [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where\n \"test == somelongname or\ntest == /another long name/ or\ncat == SomeCategory\"", "testfile.dll", "--where", "test == somelongname or test == /another long name/ or cat == SomeCategory", "--arg2")] [TestCase("testfile.dll @file1.txt --arg2", "file1.txt:--where\n \"test == somelongname ||\ntest == /another long name/ ||\ncat == SomeCategory\"", "testfile.dll", "--where", "test == somelongname || test == /another long name/ || cat == SomeCategory", "--arg2")] public void GetArgsFromFiles(string commandLine, string files, params string[] expectedArgs) { var filespecs = files.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries); var testFiles = new TestFile[filespecs.Length]; for (int ix = 0; ix < filespecs.Length; ++ix) { var filespec = filespecs[ix]; var split = filespec.IndexOf( ':' ); if (split < 0) throw new Exception("Invalid test data"); var fileName = filespec.Substring(0, split); var fileContent = filespec.Substring(split + 1); testFiles[ix] = new TestFile(Path.Combine(TestContext.CurrentContext.TestDirectory, fileName), fileContent, true); } var options = new NUnitLiteOptions(); string[] expandedArgs; try { expandedArgs = options.PreParse(CommandLineOptions.GetArgs(commandLine)).ToArray(); } finally { foreach (var tf in testFiles) tf.Dispose(); } Assert.AreEqual(expectedArgs, expandedArgs); Assert.Zero(options.ErrorMessages.Count); } [TestCase("--arg1 @file1.txt --arg2", "The file \"file1.txt\" was not found.")] [TestCase("--arg1 @ --arg2", "You must include a file name after @.")] public void GetArgsFromFiles_FailureTests(string args, string errorMessage) { var options = new NUnitLiteOptions(); options.PreParse(CommandLineOptions.GetArgs(args)); Assert.That(options.ErrorMessages, Is.EqualTo(new object[] { errorMessage })); } //[Test] public void GetArgsFromFiles_NestingOverflow() { var options = new NUnitLiteOptions(); var args = new[] { "--arg1", "@file1.txt", "--arg2" }; var expectedErrors = new string[] { "@ nesting exceeds maximum depth of 3." }; using (new TestFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "file1.txt"), "@file1.txt", true)) { var expandedArgs = options.PreParse(args); Assert.AreEqual(args, expandedArgs); Assert.AreEqual(expectedErrors, options.ErrorMessages); } } #endregion #region General Tests [Test] public void NoInputFiles() { var options = new NUnitLiteOptions(); Assert.True(options.Validate()); Assert.Null(options.InputFile); } [TestCase("ShowHelp", "help|h")] [TestCase("ShowVersion", "version|V")] [TestCase("StopOnError", "stoponerror")] [TestCase("WaitBeforeExit", "wait")] [TestCase("NoHeader", "noheader|noh")] [TestCase("TeamCity", "teamcity")] public void CanRecognizeBooleanOptions(string propertyName, string pattern) { Console.WriteLine("Testing " + propertyName); string[] prototypes = pattern.Split('|'); PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(bool), property.PropertyType, "Property '{0}' is wrong type", propertyName); NUnitLiteOptions options; foreach (string option in prototypes) { if (option.Length == 1) { options = new NUnitLiteOptions("-" + option); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize -" + option); } else { options = new NUnitLiteOptions("--" + option); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize --" + option); } options = new NUnitLiteOptions("/" + option); Assert.AreEqual(true, (bool)property.GetValue(options, null), "Didn't recognize /" + option); } } [TestCase("WhereClause", "where", new string[] { "cat==Fast" }, new string[0])] [TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "Before", "After", "All" }, new string[] { "JUNK" })] [TestCase("OutFile", "output|out", new string[] { "output.txt" }, new string[0])] [TestCase("ErrFile", "err", new string[] { "error.txt" }, new string[0])] [TestCase("WorkDirectory", "work", new string[] { "results" }, new string[0])] [TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" }, new string[] { "JUNK" })] public void CanRecognizeStringOptions(string propertyName, string pattern, string[] goodValues, string[] badValues) { string[] prototypes = pattern.Split('|'); PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(string), property.PropertyType); foreach (string option in prototypes) { foreach (string value in goodValues) { string optionPlusValue = string.Format("--{0}:{1}", option, value); var options = new NUnitLiteOptions(optionPlusValue); Assert.True(options.Validate(), "Should be valid: " + optionPlusValue); Assert.AreEqual(value, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue); } foreach (string value in badValues) { string optionPlusValue = string.Format("--{0}:{1}", option, value); var options = new NUnitLiteOptions(optionPlusValue); Assert.False(options.Validate(), "Should not be valid: " + optionPlusValue); } } } [TestCase("DisplayTestLabels", "labels", new string[] { "Off", "On", "All" })] [TestCase("InternalTraceLevel", "trace", new string[] { "Off", "Error", "Warning", "Info", "Debug", "Verbose" })] public void CanRecognizeLowerCaseOptionValues(string propertyName, string optionName, string[] canonicalValues) { PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(string), property.PropertyType); foreach (string canonicalValue in canonicalValues) { string lowercaseValue = canonicalValue.ToLowerInvariant(); string optionPlusValue = string.Format("--{0}:{1}", optionName, lowercaseValue); var options = new NUnitLiteOptions(optionPlusValue); Assert.True(options.Validate(), "Should be valid: " + optionPlusValue); Assert.AreEqual(canonicalValue, (string)property.GetValue(options, null), "Didn't recognize " + optionPlusValue); } } #if !NETCOREAPP1_1 [TestCase("DefaultTimeout", "timeout")] #endif [TestCase("RandomSeed", "seed")] #if PARALLEL [TestCase("NumberOfTestWorkers", "workers")] #endif public void CanRecognizeIntOptions(string propertyName, string pattern) { string[] prototypes = pattern.Split('|'); PropertyInfo property = GetPropertyInfo(propertyName); Assert.AreEqual(typeof(int), property.PropertyType); foreach (string option in prototypes) { var options = new NUnitLiteOptions("--" + option + ":42"); Assert.AreEqual(42, (int)property.GetValue(options, null), "Didn't recognize --" + option + ":text"); } } [TestCase("TestList", "--test=Some.Name.Space.TestFixture", "Some.Name.Space.TestFixture")] [TestCase("TestList", "--test=A.B.C,E.F.G", "A.B.C", "E.F.G")] [TestCase("TestList", "--test=A.B.C|--test=E.F.G", "A.B.C", "E.F.G")] [TestCase("PreFilters", "--prefilter=Some.Name.Space.TestFixture", "Some.Name.Space.TestFixture")] [TestCase("PreFilters", "--prefilter=A.B.C,E.F.G", "A.B.C", "E.F.G")] [TestCase("PreFilters", "--prefilter=A.B.C|--prefilter=E.F.G", "A.B.C", "E.F.G")] public void CanRecognizeTestSelectionOptions(string propertyName, string args, params string[] expected) { var property = GetPropertyInfo(propertyName); Assert.That(property.PropertyType, Is.EqualTo(typeof(IList<string>))); var options = new NUnitLiteOptions(args.Split(new char[] { '|' })); var list = (IList<string>)property.GetValue(options, null); Assert.That(list, Is.EqualTo(expected)); } // [TestCase("InternalTraceLevel", "trace", typeof(InternalTraceLevel))] // public void CanRecognizeEnumOptions(string propertyName, string pattern, Type enumType) // { // string[] prototypes = pattern.Split('|'); // PropertyInfo property = GetPropertyInfo(propertyName); // Assert.IsNotNull(property, "Property {0} not found", propertyName); // Assert.IsTrue(property.PropertyType.IsEnum, "Property {0} is not an enum", propertyName); // Assert.AreEqual(enumType, property.PropertyType); // foreach (string option in prototypes) // { // foreach (string name in Enum.GetNames(enumType)) // { // { // ConsoleOptions options = new ConsoleOptions("--" + option + ":" + name); // Assert.AreEqual(name, property.GetValue(options, null).ToString(), "Didn't recognize -" + option + ":" + name); // } // } // } // } [TestCase("--where")] [TestCase("--output")] [TestCase("--err")] [TestCase("--work")] [TestCase("--trace")] [TestCase("--test")] [TestCase("--prefilter")] #if !NETCOREAPP1_1 [TestCase("--timeout")] #endif public void MissingValuesAreReported(string option) { var options = new NUnitLiteOptions(option + "="); Assert.False(options.Validate(), "Missing value should not be valid"); Assert.AreEqual("Missing required value for option '" + option + "'.", options.ErrorMessages[0]); } [Test] public void AssemblyIsInvalidByDefault() { var options = new NUnitLiteOptions("nunit.tests.dll"); Assert.False(options.Validate()); Assert.AreEqual(1, options.ErrorMessages.Count); Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: nunit.tests.dll")); } [Test] public void MultipleAssembliesAreInvalidByDefault() { var options = new NUnitLiteOptions("nunit.tests.dll", "another.dll"); Assert.False(options.Validate()); Assert.AreEqual(2, options.ErrorMessages.Count); Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: nunit.tests.dll")); Assert.That(options.ErrorMessages[1], Contains.Substring("Invalid entry: another.dll")); } [Test] public void AssemblyIsValidIfAllowed() { var options = new NUnitLiteOptions(true, "nunit.tests.dll"); Assert.True(options.Validate()); Assert.AreEqual(0, options.ErrorMessages.Count); } [Test] public void MultipleAssembliesAreInvalidEvenIfOneIsAllowed() { var options = new NUnitLiteOptions(true, "nunit.tests.dll", "another.dll"); Assert.False(options.Validate()); Assert.AreEqual(1, options.ErrorMessages.Count); Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: another.dll")); } [Test] public void InvalidOption() { var options = new NUnitLiteOptions("-asembly:nunit.tests.dll"); Assert.False(options.Validate()); Assert.AreEqual(1, options.ErrorMessages.Count); Assert.AreEqual("Invalid argument: -asembly:nunit.tests.dll", options.ErrorMessages[0]); } [Test] public void InvalidCommandLineParms() { var options = new NUnitLiteOptions("-garbage:TestFixture", "-assembly:Tests.dll"); Assert.False(options.Validate()); Assert.AreEqual(2, options.ErrorMessages.Count); Assert.AreEqual("Invalid argument: -garbage:TestFixture", options.ErrorMessages[0]); Assert.AreEqual("Invalid argument: -assembly:Tests.dll", options.ErrorMessages[1]); } #endregion #region Timeout Option [Test] public void TimeoutIsMinusOneIfNoOptionIsProvided() { var options = new NUnitLiteOptions(); Assert.True(options.Validate()); Assert.AreEqual(-1, options.DefaultTimeout); } #if !NETCOREAPP1_1 [Test] public void TimeoutThrowsExceptionIfOptionHasNoValue() { Assert.Throws<OptionException>(() => new NUnitLiteOptions("-timeout")); } [Test] public void TimeoutParsesIntValueCorrectly() { var options = new NUnitLiteOptions("-timeout:5000"); Assert.True(options.Validate()); Assert.AreEqual(5000, options.DefaultTimeout); } [Test] public void TimeoutCausesErrorIfValueIsNotInteger() { var options = new NUnitLiteOptions("-timeout:abc"); Assert.False(options.Validate()); Assert.AreEqual(-1, options.DefaultTimeout); } #endif #endregion #region EngineResult Option [Test] public void FileNameWithoutResultOptionLooksLikeParameter() { var options = new NUnitLiteOptions(true, "results.xml"); Assert.True(options.Validate()); Assert.AreEqual(0, options.ErrorMessages.Count); //Assert.That(options.ErrorMessages[0], Contains.Substring("Invalid entry: results.xml")); Assert.AreEqual("results.xml", options.InputFile); } [Test] public void ResultOptionWithFilePath() { var options = new NUnitLiteOptions("-result:results.xml"); Assert.True(options.Validate()); OutputSpecification spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("nunit3", spec.Format); } [Test] public void ResultOptionWithFilePathAndFormat() { var options = new NUnitLiteOptions("-result:results.xml;format=nunit2"); Assert.True(options.Validate()); OutputSpecification spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("nunit2", spec.Format); } [Test] public void ResultOptionWithoutFileNameIsInvalid() { var options = new NUnitLiteOptions("-result:"); Assert.False(options.Validate(), "Should not be valid"); Assert.AreEqual(1, options.ErrorMessages.Count, "An error was expected"); } [Test] public void ResultOptionMayBeRepeated() { var options = new NUnitLiteOptions("-result:results.xml", "-result:nunit2results.xml;format=nunit2"); Assert.True(options.Validate(), "Should be valid"); var specs = options.ResultOutputSpecifications; Assert.That(specs, Has.Count.EqualTo(2)); var spec1 = specs[0]; Assert.AreEqual("results.xml", spec1.OutputPath); Assert.AreEqual("nunit3", spec1.Format); var spec2 = specs[1]; Assert.AreEqual("nunit2results.xml", spec2.OutputPath); Assert.AreEqual("nunit2", spec2.Format); } [Test] public void DefaultResultSpecification() { var options = new NUnitLiteOptions(); Assert.AreEqual(1, options.ResultOutputSpecifications.Count); var spec = options.ResultOutputSpecifications[0]; Assert.AreEqual("TestResult.xml", spec.OutputPath); Assert.AreEqual("nunit3", spec.Format); } [Test] public void NoResultSuppressesDefaultResultSpecification() { var options = new NUnitLiteOptions("-noresult"); Assert.AreEqual(0, options.ResultOutputSpecifications.Count); } [Test] public void NoResultSuppressesAllResultSpecifications() { var options = new NUnitLiteOptions("-result:results.xml", "-noresult", "-result:nunit2results.xml;format=nunit2"); Assert.AreEqual(0, options.ResultOutputSpecifications.Count); } [Test] public void InvalidResultSpecRecordsError() { var options = new NUnitLiteOptions("test.dll", "-result:userspecifed.xml;format=nunit2;format=nunit3"); Assert.That(options.ResultOutputSpecifications, Has.Exactly(1).Items .And.Exactly(1).Property(nameof(OutputSpecification.OutputPath)).EqualTo("TestResult.xml")); Assert.That(options.ErrorMessages, Has.Exactly(1).Contains("invalid output spec").IgnoreCase); } #endregion #region Explore Option [Test] public void ExploreOptionWithoutPath() { var options = new NUnitLiteOptions("-explore"); Assert.True(options.Validate()); Assert.True(options.Explore); } [Test] public void ExploreOptionWithFilePath() { var options = new NUnitLiteOptions("-explore:results.xml"); Assert.True(options.Validate()); Assert.True(options.Explore); OutputSpecification spec = options.ExploreOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("nunit3", spec.Format); } [Test] public void ExploreOptionWithFilePathAndFormat() { var options = new NUnitLiteOptions("-explore:results.xml;format=cases"); Assert.True(options.Validate()); Assert.True(options.Explore); OutputSpecification spec = options.ExploreOutputSpecifications[0]; Assert.AreEqual("results.xml", spec.OutputPath); Assert.AreEqual("cases", spec.Format); } [Test] public void ExploreOptionWithFilePathUsingEqualSign() { var options = new NUnitLiteOptions("-explore=C:/nunit/tests/bin/Debug/console-test.xml"); Assert.True(options.Validate()); Assert.True(options.Explore); Assert.AreEqual("C:/nunit/tests/bin/Debug/console-test.xml", options.ExploreOutputSpecifications[0].OutputPath); } [TestCase(true, null, true)] [TestCase(false, null, false)] [TestCase(true, false, true)] [TestCase(false, false, false)] [TestCase(true, true, true)] [TestCase(false, true, true)] public void ShouldSetTeamCityFlagAccordingToArgsAndDefaults(bool hasTeamcityInCmd, bool? defaultTeamcity, bool expectedTeamCity) { // Given List<string> args = new List<string> { "tests.dll" }; if (hasTeamcityInCmd) { args.Add("--teamcity"); } CommandLineOptions options; if (defaultTeamcity.HasValue) { options = new NUnitLiteOptions(new DefaultOptionsProviderStub(defaultTeamcity.Value), args.ToArray()); } else { options = new NUnitLiteOptions(args.ToArray()); } // When var actualTeamCity = options.TeamCity; // Then Assert.AreEqual(actualTeamCity, expectedTeamCity); } #endregion #region Test Parameters [Test] public void SingleTestParameter() { var options = new NUnitLiteOptions("--params=X=5"); Assert.That(options.ErrorMessages, Is.Empty); Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { {"X", "5" } })); } [Test] public void TwoTestParametersInOneOption() { var options = new NUnitLiteOptions("--params:X=5;Y=7"); Assert.That(options.ErrorMessages, Is.Empty); Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { { "X", "5" }, { "Y", "7" } })); } [Test] public void TwoTestParametersInSeparateOptions() { var options = new NUnitLiteOptions("-p:X=5", "-p:Y=7"); Assert.That(options.ErrorMessages, Is.Empty); Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { { "X", "5" }, { "Y", "7" } })); } [Test] public void ThreeTestParametersInTwoOptions() { var options = new NUnitLiteOptions("--params:X=5;Y=7", "-p:Z=3"); Assert.That(options.ErrorMessages, Is.Empty); Assert.That(options.TestParameters, Is.EqualTo(new Dictionary<string, string> { { "X", "5" }, { "Y", "7" }, { "Z", "3" } })); } [Test] public void ParameterWithoutEqualSignIsInvalid() { var options = new NUnitLiteOptions("--params=X5"); Assert.That(options.ErrorMessages.Count, Is.EqualTo(1)); } [Test] public void DisplayTestParameters() { if (TestContext.Parameters.Count == 0) { Console.WriteLine("No Test Parameters were passed"); return; } Console.WriteLine("Test Parameters---"); foreach (var name in TestContext.Parameters.Names) Console.WriteLine(" Name: {0} Value: {1}", name, TestContext.Parameters[name]); } #endregion #region Helper Methods //private static FieldInfo GetFieldInfo(string fieldName) //{ // FieldInfo field = typeof(NUnitLiteOptions).GetField(fieldName); // Assert.IsNotNull(field, "The field '{0}' is not defined", fieldName); // return field; //} private static PropertyInfo GetPropertyInfo(string propertyName) { PropertyInfo property = typeof(NUnitLiteOptions).GetProperty(propertyName); Assert.IsNotNull(property, "The property '{0}' is not defined", propertyName); return property; } #endregion internal sealed class DefaultOptionsProviderStub : IDefaultOptionsProvider { public DefaultOptionsProviderStub(bool teamCity) { TeamCity = teamCity; } public bool TeamCity { get; } } } }
namespace Microsoft.Protocols.TestSuites.MS_OXNSPI { using System; using System.Collections.Generic; using System.Net; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; /// <summary> /// The MapiHttpAdapter class contains the MAPIHTTP implements for the interfaces of IMS_OXNSPIAdapter. /// </summary> public class NspiMapiHttpAdapter { #region Variables /// <summary> /// The Site instance. /// </summary> private ITestSite site; /// <summary> /// The Mailbox userName which can be used by client to connect to the SUT. /// </summary> private string userName; /// <summary> /// The user password which can be used by client to access to the SUT. /// </summary> private string password; /// <summary> /// Define the name of domain where the server belongs to. /// </summary> private string domainName; /// <summary> /// The URL that a client can use to connect with a NSPI server through MAPI over HTTP. /// </summary> private string addressBookUrl; #endregion /// <summary> /// Initializes a new instance of the <see cref="NspiMapiHttpAdapter" /> class. /// </summary> /// <param name="site">The Site instance.</param> /// <param name="userName">The Mailbox userName which can be used by client to connect to the SUT.</param> /// <param name="password">The user password which can be used by client to access to the SUT.</param> /// <param name="domainName">Define the name of domain where the server belongs to.</param> /// <param name="addressBookUrl">The URL that a client can use to connect with a NSPI server through MAPI over HTTP.</param> public NspiMapiHttpAdapter(ITestSite site, string userName, string password, string domainName, string addressBookUrl) { this.site = site; this.userName = userName; this.password = password; this.domainName = domainName; this.addressBookUrl = addressBookUrl; } #region Instance interface /// <summary> /// The NspiBind method initiates a session between a client and the server. /// </summary> /// <param name="flags">A DWORD value that contains a set of bit flags.</param> /// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param> /// <param name="serverGuid">The value NULL or a pointer to a GUID value that is associated with the specific server.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue Bind(uint flags, STAT stat, ref FlatUID_r? serverGuid) { ErrorCodeValue result; BindRequestBody bindRequestBody = this.BuildBindRequestBody(stat, flags); byte[] rawBuffer = null; ChunkedResponse chunkedResponse = null; BindResponseBody bindResponseBody = null; // Send the execute HTTP request and get the response HttpWebResponse response = MapiHttpAdapter.SendMAPIHttpRequest(this.site, this.addressBookUrl, this.userName, this.domainName, this.password, bindRequestBody, RequestType.Bind.ToString(), AdapterHelper.SessionContextCookies); // Read the HTTP response buffer and parse the response to correct format rawBuffer = MapiHttpAdapter.ReadHttpResponse(response); result = (ErrorCodeValue)int.Parse(response.Headers["X-ResponseCode"]); if (result == ErrorCodeValue.Success) { chunkedResponse = ChunkedResponse.ParseChunkedResponse(rawBuffer); bindResponseBody = BindResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)bindResponseBody.ErrorCode; if (bindResponseBody.ServerGuid != null) { FlatUID_r newGuid = new FlatUID_r(); newGuid.Ab = bindResponseBody.ServerGuid.ToByteArray(); serverGuid = newGuid; } else { serverGuid = null; } } response.GetResponseStream().Close(); AdapterHelper.SessionContextCookies = response.Cookies; return result; } /// <summary> /// The NspiUnbind method destroys the context handle. No other action is taken. /// </summary> /// <param name="reserved">A DWORD [MS-DTYP] value reserved for future use. This property is ignored by the server.</param> /// <returns>A DWORD value that specifies the return status of the method.</returns> public uint Unbind(uint reserved) { uint result; UnbindRequestBody unbindRequest = this.BuildUnbindRequestBody(); ChunkedResponse chunkedResponse = this.SendAddressBookRequest(unbindRequest, RequestType.Unbind); AdapterHelper.SessionContextCookies = new CookieCollection(); UnbindResponseBody unbindResponseBody = UnbindResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = unbindResponseBody.ErrorCode; return result; } /// <summary> /// The NspiGetSpecialTable method returns the rows of a special table to the client. /// </summary> /// <param name="flags">A DWORD value that contains a set of bit flags.</param> /// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param> /// <param name="version">A reference to a DWORD. On input, it holds the value of the version number of /// the address book hierarchy table that the client has. On output, it holds the version of the server's address book hierarchy table.</param> /// <param name="rows">A PropertyRowSet_r structure. On return, it holds the rows for the table that the client is requesting.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue GetSpecialTable(uint flags, ref STAT stat, ref uint version, out PropertyRowSet_r? rows) { ErrorCodeValue result; byte[] auxIn = new byte[] { }; GetSpecialTableRequestBody getSpecialTableRequestBody = new GetSpecialTableRequestBody() { Flags = flags, HasState = true, State = stat, HasVersion = true, Version = version, AuxiliaryBuffer = auxIn, AuxiliaryBufferSize = (uint)auxIn.Length }; ChunkedResponse chunkedResponse = this.SendAddressBookRequest(getSpecialTableRequestBody, RequestType.GetSpecialTable); GetSpecialTableResponseBody getSpecialTableResponseBody = GetSpecialTableResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)getSpecialTableResponseBody.ErrorCode; if (getSpecialTableResponseBody.HasRows) { PropertyRowSet_r newRows = AdapterHelper.ParsePropertyRowSet_r(getSpecialTableResponseBody.RowCount.Value, getSpecialTableResponseBody.Rows); rows = newRows; } else { rows = null; } if (getSpecialTableResponseBody.HasVersion) { version = getSpecialTableResponseBody.Version.Value; } return result; } /// <summary> /// The NspiUpdateStat method updates the STAT block that represents the position in a table /// to reflect positioning changes requested by the client. /// </summary> /// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param> /// <param name="delta">The value NULL or a pointer to a LONG value that indicates movement /// within the address book container specified by the input parameter stat.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue UpdateStat(ref STAT stat, ref int? delta) { ErrorCodeValue result; UpdateStatRequestBody updateStatRequestBody = this.BuildUpdateStatRequestBody(stat); if (delta == null) { updateStatRequestBody.DeltaRequested = false; } ChunkedResponse chunkedResponse = this.SendAddressBookRequest(updateStatRequestBody, RequestType.UpdateStat); UpdateStatResponseBody updateStatResponseBody = UpdateStatResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)updateStatResponseBody.ErrorCode; if (updateStatResponseBody.HasDelta) { delta = updateStatResponseBody.Delta; } if (updateStatResponseBody.HasState) { stat = updateStatResponseBody.State.Value; } return result; } /// <summary> /// The NspiQueryColumns method returns a list of all the properties that the server is aware of. /// </summary> /// <param name="flags">A DWORD value that contains a set of bit flags.</param> /// <param name="columns">A PropertyTagArray_r structure that contains a list of proptags.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue QueryColumns(uint flags, out PropertyTagArray_r? columns) { ErrorCodeValue result; QueryColumnsRequestBody queryColumnsRequestBody = this.BuildQueryColumnsRequestBody(flags); ChunkedResponse chunkedResponse = this.SendAddressBookRequest(queryColumnsRequestBody, RequestType.QueryColumns); QueryColumnsResponseBody queryColumnsResponseBody = QueryColumnsResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)queryColumnsResponseBody.ErrorCode; if (queryColumnsResponseBody.HasColumns) { PropertyTagArray_r propertyTagArray = new PropertyTagArray_r(); propertyTagArray.CValues = queryColumnsResponseBody.Columns.Value.PropertyTagCount; propertyTagArray.AulPropTag = new uint[propertyTagArray.CValues]; for (int i = 0; i < propertyTagArray.CValues; i++) { propertyTagArray.AulPropTag[i] = (uint)((queryColumnsResponseBody.Columns.Value.PropertyTags[i].PropertyId * 65536) | queryColumnsResponseBody.Columns.Value.PropertyTags[i].PropertyType); } columns = propertyTagArray; } else { columns = null; } return result; } /// <summary> /// The NspiGetPropList method returns a list of all the properties that have values on a specified object. /// </summary> /// <param name="flags">A DWORD value that contains a set of bit flags.</param> /// <param name="mid">A DWORD value that contains a Minimal Entry ID.</param> /// <param name="codePage">The code page in which the client wants the server to express string values properties.</param> /// <param name="propTags">A PropertyTagArray_r value. On return, it holds a list of properties.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue GetPropList(uint flags, uint mid, uint codePage, out PropertyTagArray_r? propTags) { ErrorCodeValue result; GetPropListRequestBody getPropListRequestBody = this.BuildGetPropListRequestBody(flags, mid, codePage); ChunkedResponse chunkedResponse = this.SendAddressBookRequest(getPropListRequestBody, RequestType.GetPropList); GetPropListResponseBody getPropListResponseBody = GetPropListResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)getPropListResponseBody.ErrorCode; if (getPropListResponseBody.HasPropertyTags) { PropertyTagArray_r propertyTagArray = new PropertyTagArray_r(); propertyTagArray.CValues = getPropListResponseBody.PropertyTags.Value.PropertyTagCount; propertyTagArray.AulPropTag = new uint[propertyTagArray.CValues]; for (int i = 0; i < propertyTagArray.CValues; i++) { propertyTagArray.AulPropTag[i] = (uint)((getPropListResponseBody.PropertyTags.Value.PropertyTags[i].PropertyId * 65536) | getPropListResponseBody.PropertyTags.Value.PropertyTags[i].PropertyType); } propTags = propertyTagArray; } else { propTags = null; } return result; } /// <summary> /// The NspiGetProps method returns an address book row that contains a set of the properties /// and values that exist on an object. /// </summary> /// <param name="flags">A DWORD value that contains a set of bit flags.</param> /// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param> /// <param name="propTags">The value NULL or a reference to a PropertyTagArray_r value. /// It contains a list of the proptags of the properties that the client wants to be returned.</param> /// <param name="rows">A nullable PropertyRow_r value. /// It contains the address book container row the server returns in response to the request.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue GetProps(uint flags, STAT stat, PropertyTagArray_r? propTags, out PropertyRow_r? rows) { ErrorCodeValue result; GetPropsRequestBody getPropertyRequestBody = null; LargePropTagArray propetyTags = new LargePropTagArray(); if (propTags != null) { propetyTags.PropertyTagCount = propTags.Value.CValues; propetyTags.PropertyTags = new PropertyTag[propetyTags.PropertyTagCount]; for (int i = 0; i < propTags.Value.CValues; i++) { propetyTags.PropertyTags[i].PropertyId = (ushort)((propTags.Value.AulPropTag[i] & 0xFFFF0000) >> 16); propetyTags.PropertyTags[i].PropertyType = (ushort)(propTags.Value.AulPropTag[i] & 0x0000FFFF); } getPropertyRequestBody = this.BuildGetPropsRequestBody(flags, true, stat, true, propetyTags); } else { getPropertyRequestBody = this.BuildGetPropsRequestBody(flags, true, stat, false, propetyTags); } ChunkedResponse chunkedResponse = this.SendAddressBookRequest(getPropertyRequestBody, RequestType.GetProps); GetPropsResponseBody getPropsResponseBody = GetPropsResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)getPropsResponseBody.ErrorCode; if (getPropsResponseBody.HasPropertyValues) { PropertyRow_r propertyRow = AdapterHelper.ParsePropertyRow_r(getPropsResponseBody.PropertyValues.Value); rows = propertyRow; } else { rows = null; } return result; } /// <summary> /// The NspiQueryRows method returns a number of rows from a specified table to the client. /// </summary> /// <param name="flags">A DWORD value that contains a set of bit flags.</param> /// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param> /// <param name="tableCount">A DWORD value that contains the number values in the input parameter table. /// This value is limited to 100,000.</param> /// <param name="table">An array of DWORD values, representing an Explicit Table.</param> /// <param name="count">A DWORD value that contains the number of rows the client is requesting.</param> /// <param name="propTags">The value NULL or a reference to a PropertyTagArray_r value, /// containing a list of the proptags of the properties that the client requires to be returned for each row returned.</param> /// <param name="rows">A nullable PropertyRowSet_r value, it contains the address book container rows that the server returns in response to the request.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue QueryRows(uint flags, ref STAT stat, uint tableCount, uint[] table, uint count, PropertyTagArray_r? propTags, out PropertyRowSet_r? rows) { ErrorCodeValue result; QueryRowsRequestBody queryRowsRequestBody = new QueryRowsRequestBody(); LargePropTagArray propetyTags = new LargePropTagArray(); if (propTags != null) { propetyTags.PropertyTagCount = propTags.Value.CValues; propetyTags.PropertyTags = new PropertyTag[propetyTags.PropertyTagCount]; for (int i = 0; i < propTags.Value.CValues; i++) { propetyTags.PropertyTags[i].PropertyId = (ushort)((propTags.Value.AulPropTag[i] & 0xFFFF0000) >> 16); propetyTags.PropertyTags[i].PropertyType = (ushort)(propTags.Value.AulPropTag[i] & 0x0000FFFF); } queryRowsRequestBody.HasColumns = true; queryRowsRequestBody.Columns = propetyTags; } queryRowsRequestBody.Flags = flags; queryRowsRequestBody.HasState = true; queryRowsRequestBody.State = stat; queryRowsRequestBody.ExplicitTableCount = tableCount; queryRowsRequestBody.ExplicitTable = table; queryRowsRequestBody.RowCount = count; byte[] auxIn = new byte[] { }; queryRowsRequestBody.AuxiliaryBuffer = auxIn; queryRowsRequestBody.AuxiliaryBufferSize = (uint)auxIn.Length; ChunkedResponse chunkedResponse = this.SendAddressBookRequest(queryRowsRequestBody, RequestType.QueryRows); QueryRowsResponseBody queryRowsResponseBody = QueryRowsResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)queryRowsResponseBody.ErrorCode; if (queryRowsResponseBody.RowCount != null) { PropertyRowSet_r newRows = AdapterHelper.ParsePropertyRowSet_r(queryRowsResponseBody.Columns.Value, queryRowsResponseBody.RowCount.Value, queryRowsResponseBody.RowData); rows = newRows; } else { rows = null; } if (queryRowsResponseBody.HasState) { stat = queryRowsResponseBody.State.Value; } return result; } /// <summary> /// The NspiSeekEntries method searches for and sets the logical position in a specific table /// to the first entry greater than or equal to a specified value. /// </summary> /// <param name="reserved">A DWORD value that is reserved for future use. Ignored by the server.</param> /// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param> /// <param name="target">A PropertyValue_r value holding the value that is being sought.</param> /// <param name="table">The value NULL or a PropertyTagArray_r value. /// It holds a list of Minimal Entry IDs that comprise a restricted address book container.</param> /// <param name="propTags">It contains a list of the proptags of the columns /// that client wants to be returned for each row returned.</param> /// <param name="rows">It contains the address book container rows the server returns in response to the request.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue SeekEntries(uint reserved, ref STAT stat, PropertyValue_r target, PropertyTagArray_r? table, PropertyTagArray_r? propTags, out PropertyRowSet_r? rows) { ErrorCodeValue result; SeekEntriesRequestBody seekEntriesRequestBody = new SeekEntriesRequestBody(); TaggedPropertyValue targetValue = new TaggedPropertyValue(); targetValue.PropertyTag = new PropertyTag((ushort)((target.PropTag & 0xFFFF0000) >> 16), (ushort)(target.PropTag & 0x0000FFFF)); targetValue.Value = new byte[target.Serialize().Length - 8]; Array.Copy(target.Serialize(), 8, targetValue.Value, 0, target.Serialize().Length - 8); // Reserved. The client MUST set this field to 0x00000000 and the server MUST ignore this field. seekEntriesRequestBody.Reserved = reserved; seekEntriesRequestBody.HasState = true; seekEntriesRequestBody.State = stat; seekEntriesRequestBody.HasTarget = true; seekEntriesRequestBody.Target = targetValue; if (table != null) { seekEntriesRequestBody.HasExplicitTable = true; seekEntriesRequestBody.ExplicitTable = table.Value.AulPropTag; } LargePropTagArray propetyTags = new LargePropTagArray(); if (propTags != null) { propetyTags.PropertyTagCount = propTags.Value.CValues; propetyTags.PropertyTags = new PropertyTag[propetyTags.PropertyTagCount]; for (int i = 0; i < propTags.Value.CValues; i++) { propetyTags.PropertyTags[i].PropertyId = (ushort)((propTags.Value.AulPropTag[i] & 0xFFFF0000) >> 16); propetyTags.PropertyTags[i].PropertyType = (ushort)(propTags.Value.AulPropTag[i] & 0x0000FFFF); } seekEntriesRequestBody.HasColumns = true; seekEntriesRequestBody.Columns = propetyTags; } seekEntriesRequestBody.AuxiliaryBufferSize = 0; seekEntriesRequestBody.AuxiliaryBuffer = new byte[] { }; ChunkedResponse chunkedResponse = this.SendAddressBookRequest(seekEntriesRequestBody, RequestType.SeekEntries); SeekEntriesResponseBody seekEntriesResponseBody = SeekEntriesResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)seekEntriesResponseBody.ErrorCode; if (seekEntriesResponseBody.HasColumnsAndRows) { PropertyRowSet_r newRows = AdapterHelper.ParsePropertyRowSet_r(seekEntriesResponseBody.Columns.Value, seekEntriesResponseBody.RowCount.Value, seekEntriesResponseBody.RowData); rows = newRows; } else { rows = null; } if (seekEntriesResponseBody.HasState) { stat = seekEntriesResponseBody.State.Value; } return result; } /// <summary> /// The NspiGetMatches method returns an Explicit Table. /// </summary> /// <param name="reserved">A DWORD value reserved for future use.</param> /// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param> /// <param name="proReserved">A PropertyTagArray_r reserved for future use.</param> /// <param name="reserved2">A DWORD value reserved for future use. Ignored by the server.</param> /// <param name="filter">The value NULL or a Restriction_r value. /// It holds a logical restriction to apply to the rows in the address book container specified in the stat parameter.</param> /// <param name="propName">The value NULL or a PropertyName_r value. /// It holds the property to be opened as a restricted address book container.</param> /// <param name="requested">A DWORD value. It contains the maximum number of rows to return in a restricted address book container.</param> /// <param name="outMids">A PropertyTagArray_r value. On return, it holds a list of Minimal Entry IDs that comprise a restricted address book container.</param> /// <param name="propTags">The value NULL or a reference to a PropertyTagArray_r value. /// It contains a list of the proptags of the columns that client wants to be returned for each row returned.</param> /// <param name="rows">A reference to a PropertyRowSet_r value. It contains the address book container rows the server returns in response to the request.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue GetMatches(uint reserved, ref STAT stat, PropertyTagArray_r? proReserved, uint reserved2, Restriction_r? filter, PropertyName_r? propName, uint requested, out PropertyTagArray_r? outMids, PropertyTagArray_r? propTags, out PropertyRowSet_r? rows) { ErrorCodeValue result; byte[] auxIn = new byte[] { }; GetMatchesRequestBody getMatchesRequestBody = new GetMatchesRequestBody() { Reserved = reserved, HasState = true, State = stat, InterfaceOptionFlags = reserved2, HasPropertyName = false, RowCount = requested, AuxiliaryBuffer = auxIn, AuxiliaryBufferSize = (uint)auxIn.Length }; if (propTags != null) { LargePropTagArray propetyTags = new LargePropTagArray(); propetyTags.PropertyTagCount = propTags.Value.CValues; propetyTags.PropertyTags = new PropertyTag[propetyTags.PropertyTagCount]; for (int i = 0; i < propTags.Value.CValues; i++) { propetyTags.PropertyTags[i].PropertyId = (ushort)((propTags.Value.AulPropTag[i] & 0xFFFF0000) >> 16); propetyTags.PropertyTags[i].PropertyType = (ushort)(propTags.Value.AulPropTag[i] & 0x0000FFFF); } getMatchesRequestBody.HasColumns = true; getMatchesRequestBody.Columns = propetyTags; } if (proReserved != null) { getMatchesRequestBody.HasMinimalIds = true; getMatchesRequestBody.MinimalIdCount = proReserved.Value.CValues; getMatchesRequestBody.MinimalIds = proReserved.Value.AulPropTag; } if (filter != null) { getMatchesRequestBody.HasFilter = true; getMatchesRequestBody.Filter = AdapterHelper.ConvertRestriction_rToRestriction(filter.Value); } ChunkedResponse chunkedResponse = this.SendAddressBookRequest(getMatchesRequestBody, RequestType.GetMatches); GetMatchesResponseBody getMatchesResponseBody = GetMatchesResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)getMatchesResponseBody.ErrorCode; if (getMatchesResponseBody.HasMinimalIds) { PropertyTagArray_r propertyTagArray = new PropertyTagArray_r(); propertyTagArray.CValues = getMatchesResponseBody.MinimalIdCount.Value; propertyTagArray.AulPropTag = getMatchesResponseBody.MinimalIds; outMids = propertyTagArray; } else { outMids = null; } if (getMatchesResponseBody.RowCount != null) { PropertyRowSet_r newRows = AdapterHelper.ParsePropertyRowSet_r(getMatchesResponseBody.Columns.Value, getMatchesResponseBody.RowCount.Value, getMatchesResponseBody.RowData); rows = newRows; } else { rows = null; } if (getMatchesResponseBody.HasState) { stat = getMatchesResponseBody.State.Value; } return result; } /// <summary> /// The NspiResortRestriction method applies to a sort order to the objects in a restricted address book container. /// </summary> /// <param name="reserved">A DWORD value reserved for future use. Ignored by the server.</param> /// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param> /// <param name="proInMIds">A PropertyTagArray_r value. /// It holds a list of Minimal Entry IDs that comprise a restricted address book container.</param> /// <param name="outMIds">A PropertyTagArray_r value. On return, it holds a list of Minimal Entry IDs /// that comprise a restricted address book container.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue ResortRestriction(uint reserved, ref STAT stat, PropertyTagArray_r proInMIds, ref PropertyTagArray_r? outMIds) { ErrorCodeValue result; byte[] auxIn = new byte[] { }; ResortRestrictionRequestBody resortRestrictionRequestBody = new ResortRestrictionRequestBody() { // Reserved. The client MUST set this field to 0x00000000 and the server MUST ignore this field. Reserved = reserved, HasState = true, State = stat, HasMinimalIds = true, MinimalIdCount = proInMIds.CValues, MinimalIds = proInMIds.AulPropTag, AuxiliaryBuffer = auxIn, AuxiliaryBufferSize = (uint)auxIn.Length }; ChunkedResponse chunkedResponse = this.SendAddressBookRequest(resortRestrictionRequestBody, RequestType.ResortRestriction); ResortRestrictionResponseBody resortRestrictionResponseBody = ResortRestrictionResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)resortRestrictionResponseBody.ErrorCode; if (resortRestrictionResponseBody.HasMinimalIds) { PropertyTagArray_r propertyTagArray = AdapterHelper.ParsePropertyTagArray_r(resortRestrictionResponseBody.MinimalIdCount.Value, resortRestrictionResponseBody.MinimalIds); outMIds = propertyTagArray; } else { outMIds = null; } if (resortRestrictionResponseBody.HasState) { stat = resortRestrictionResponseBody.State.Value; } return result; } /// <summary> /// The NspiCompareMIds method compares the position in an address book container of two objects /// identified by Minimal Entry ID and returns the value of the comparison. /// </summary> /// <param name="reserved">A DWORD value reserved for future use. Ignored by the server.</param> /// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param> /// <param name="mid1">The mid1 is a DWORD value containing a Minimal Entry ID.</param> /// <param name="mid2">The mid2 is a DWORD value containing a Minimal Entry ID.</param> /// <param name="results">A DWORD value. On return, it contains the result of the comparison.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue CompareMIds(uint reserved, STAT stat, uint mid1, uint mid2, out int results) { ErrorCodeValue result; byte[] auxIn = new byte[] { }; CompareMinIdsRequestBody compareMinIdsRequestBody = new CompareMinIdsRequestBody() { // Reserved. The client MUST set this field to 0x00000000 and the server MUST ignore this field. Reserved = reserved, HasState = true, State = stat, MinimalId1 = mid1, MinimalId2 = mid2, AuxiliaryBuffer = auxIn, AuxiliaryBufferSize = (uint)auxIn.Length }; ChunkedResponse chunkedResponse = this.SendAddressBookRequest(compareMinIdsRequestBody, RequestType.CompareMIds); CompareMinIdsResponseBody compareMinIdsResponseBody = CompareMinIdsResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)compareMinIdsResponseBody.ErrorCode; results = compareMinIdsResponseBody.Result; return result; } /// <summary> /// The NspiDNToMId method maps a set of DN to a set of Minimal Entry ID. /// </summary> /// <param name="reserved">A DWORD value reserved for future use. Ignored by the server.</param> /// <param name="names">A StringsArray_r value. It holds a list of strings that contain DNs.</param> /// <param name="mids">A PropertyTagArray_r value. On return, it holds a list of Minimal Entry IDs.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue DNToMId(uint reserved, StringsArray_r names, out PropertyTagArray_r? mids) { ErrorCodeValue result; byte[] auxIn = new byte[] { }; StringArray_r nameArray = new StringArray_r(); nameArray.CValues = names.CValues; nameArray.LppszA = names.LppszA; DNToMinIdRequestBody requestBodyOfdnToMId = new DNToMinIdRequestBody() { Reserved = reserved, HasNames = true, Names = nameArray, AuxiliaryBuffer = auxIn, AuxiliaryBufferSize = (uint)auxIn.Length }; ChunkedResponse chunkedResponse = this.SendAddressBookRequest(requestBodyOfdnToMId, RequestType.DNToMId); DnToMinIdResponseBody distinguishedNameToMinIdResponseBody = DnToMinIdResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)distinguishedNameToMinIdResponseBody.ErrorCode; if (distinguishedNameToMinIdResponseBody.HasMinimalIds) { PropertyTagArray_r propertyTagArray = AdapterHelper.ParsePropertyTagArray_r(distinguishedNameToMinIdResponseBody.MinimalIdCount.Value, distinguishedNameToMinIdResponseBody.MinimalIds); mids = propertyTagArray; } else { mids = null; } return result; } /// <summary> /// The NspiModProps method is used to modify the properties of an object in the address book. /// </summary> /// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param> /// <param name="propTags">The value NULL or a reference to a PropertyTagArray_r. /// It contains a list of the proptags of the columns from which the client requests all the values to be removed.</param> /// <param name="row">A PropertyRow_r value. It contains an address book row.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue ModProps(STAT stat, PropertyTagArray_r? propTags, PropertyRow_r row) { ErrorCodeValue result; ModPropsRequestBody modPropsRequestBody = new ModPropsRequestBody(); modPropsRequestBody.HasState = true; modPropsRequestBody.State = stat; if (propTags != null) { LargePropTagArray largePropTagArray = new LargePropTagArray(); largePropTagArray.PropertyTagCount = propTags.Value.CValues; largePropTagArray.PropertyTags = new PropertyTag[propTags.Value.CValues]; for (int i = 0; i < propTags.Value.CValues; i++) { largePropTagArray.PropertyTags[i].PropertyId = (ushort)((propTags.Value.AulPropTag[i] & 0xFFFF0000) >> 16); largePropTagArray.PropertyTags[i].PropertyType = (ushort)(propTags.Value.AulPropTag[i] & 0x0000FFFF); } modPropsRequestBody.HasPropertyTagsToRemove = true; modPropsRequestBody.PropertyTagsToRemove = largePropTagArray; } else { modPropsRequestBody.HasPropertyTagsToRemove = false; } modPropsRequestBody.HasPropertyValues = true; AddressBookPropValueList addressBookPropValueList = new AddressBookPropValueList(); addressBookPropValueList.PropertyValueCount = row.CValues; addressBookPropValueList.PropertyValues = new TaggedPropertyValue[row.CValues]; for (int i = 0; i < row.CValues; i++) { addressBookPropValueList.PropertyValues[i] = new TaggedPropertyValue(); byte[] propertyBytes = new byte[row.LpProps[i].Serialize().Length - 8]; Array.Copy(row.LpProps[i].Serialize(), 8, propertyBytes, 0, row.LpProps[i].Serialize().Length - 8); addressBookPropValueList.PropertyValues[i].Value = propertyBytes; PropertyTag propertyTagOfRow = new PropertyTag(); propertyTagOfRow.PropertyId = (ushort)((row.LpProps[i].PropTag & 0xFFFF0000) >> 16); propertyTagOfRow.PropertyType = (ushort)(row.LpProps[i].PropTag & 0x0000FFFF); addressBookPropValueList.PropertyValues[i].PropertyTag = propertyTagOfRow; } modPropsRequestBody.PropertyVaules = addressBookPropValueList; byte[] auxIn = new byte[] { }; modPropsRequestBody.AuxiliaryBuffer = auxIn; modPropsRequestBody.AuxiliaryBufferSize = (uint)auxIn.Length; ChunkedResponse chunkedResponse = this.SendAddressBookRequest(modPropsRequestBody, RequestType.ModProps); ModPropsResponseBody modPropsResponseBody = ModPropsResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)modPropsResponseBody.ErrorCode; return result; } /// <summary> /// The NspiModLinkAtt method modifies the values of a specific property of a specific row in the address book. /// </summary> /// <param name="flags">A DWORD value that contains a set of bit flags.</param> /// <param name="propTag">A DWORD value. It contains the proptag of the property that the client wants to modify.</param> /// <param name="mid">A DWORD value that contains the Minimal Entry ID of the address book row that the client wants to modify.</param> /// <param name="entryIds">A BinaryArray value. It contains a list of EntryIDs to be used to modify the requested property on the requested address book row.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue ModLinkAtt(uint flags, uint propTag, uint mid, BinaryArray_r entryIds) { ErrorCodeValue result; ModLinkAttRequestBody modLinkAttRequestBody = new ModLinkAttRequestBody(); modLinkAttRequestBody.Flags = flags; modLinkAttRequestBody.PropertyTag = new PropertyTag() { PropertyId = (ushort)((propTag & 0xFFFF0000) >> 16), PropertyType = (ushort)(propTag & 0x0000FFFF) }; modLinkAttRequestBody.MinimalId = mid; if (entryIds.CValues != 0) { modLinkAttRequestBody.HasEntryIds = true; modLinkAttRequestBody.EntryIdCount = entryIds.CValues; modLinkAttRequestBody.EntryIDs = new byte[entryIds.CValues][]; for (int i = 0; i < entryIds.CValues; i++) { List<byte> entryIDBytes = new List<byte>(); entryIDBytes.AddRange(BitConverter.GetBytes((uint)entryIds.Lpbin[i].Lpb.Length)); entryIDBytes.AddRange(entryIds.Lpbin[i].Lpb); modLinkAttRequestBody.EntryIDs[i] = entryIDBytes.ToArray(); } } else { modLinkAttRequestBody.HasEntryIds = false; } byte[] auxIn = new byte[] { }; modLinkAttRequestBody.AuxiliaryBuffer = auxIn; modLinkAttRequestBody.AuxiliaryBufferSize = (uint)auxIn.Length; ChunkedResponse chunkedResponse = this.SendAddressBookRequest(modLinkAttRequestBody, RequestType.ModLinkAtt); ModLinkAttResponseBody modLinkAttResponseBody = ModLinkAttResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)modLinkAttResponseBody.ErrorCode; return result; } /// <summary> /// The NspiResolveNamesW method takes a set of string values in the Unicode character set /// and performs ANR on those strings. /// </summary> /// <param name="reserved">A DWORD value that is reserved for future use.</param> /// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param> /// <param name="propTags">The value NULL or a reference to a PropertyTagArray_r containing a list of the proptags of the columns /// that the client requests to be returned for each row returned.</param> /// <param name="wstr">A WStringsArray_r value. It specifies the values on which the client is requesting the server to perform ANR.</param> /// <param name="mids">A PropertyTagArray_r value. On return, it contains a list of Minimal Entry IDs that match the array of strings.</param> /// <param name="rows">A reference to a PropertyRowSet_r structure. It contains the address book container rows that the server returns in response to the request.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue ResolveNames(uint reserved, STAT stat, PropertyTagArray_r? propTags, WStringsArray_r? wstr, out PropertyTagArray_r? mids, out PropertyRowSet_r? rows) { ErrorCodeValue result; byte[] auxIn = new byte[] { }; ResolveNamesRequestBody resolveNamesRequestBody = new ResolveNamesRequestBody() { Reserved = reserved, HasState = true, State = stat, AuxiliaryBuffer = auxIn, AuxiliaryBufferSize = (uint)auxIn.Length }; if (propTags != null) { LargePropTagArray propetyTags = new LargePropTagArray(); propetyTags.PropertyTagCount = propTags.Value.CValues; propetyTags.PropertyTags = new PropertyTag[propetyTags.PropertyTagCount]; for (int i = 0; i < propTags.Value.CValues; i++) { propetyTags.PropertyTags[i].PropertyId = (ushort)((propTags.Value.AulPropTag[i] & 0xFFFF0000) >> 16); propetyTags.PropertyTags[i].PropertyType = (ushort)(propTags.Value.AulPropTag[i] & 0x0000FFFF); } resolveNamesRequestBody.HasPropertyTags = true; resolveNamesRequestBody.PropertyTags = propetyTags; } else { resolveNamesRequestBody.HasPropertyTags = false; resolveNamesRequestBody.PropertyTags = new LargePropTagArray(); } if (wstr != null) { resolveNamesRequestBody.HasNames = true; resolveNamesRequestBody.Names = wstr.Value; } else { resolveNamesRequestBody.HasNames = false; } ChunkedResponse chunkedResponse = this.SendAddressBookRequest(resolveNamesRequestBody, RequestType.ResolveNames); ResolveNamesResponseBody resolveNamesResponseBody = ResolveNamesResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)resolveNamesResponseBody.ErrorCode; if (resolveNamesResponseBody.RowCount != null) { PropertyRowSet_r newRows = AdapterHelper.ParsePropertyRowSet_r(resolveNamesResponseBody.PropertyTags.Value, resolveNamesResponseBody.RowCount.Value, resolveNamesResponseBody.RowData); rows = newRows; } else { rows = null; } if (resolveNamesResponseBody.HasMinimalIds) { PropertyTagArray_r propertyTagArray = new PropertyTagArray_r(); propertyTagArray.CValues = resolveNamesResponseBody.MinimalIdCount.Value; propertyTagArray.AulPropTag = resolveNamesResponseBody.MinimalIds; mids = propertyTagArray; } else { mids = null; } return result; } /// <summary> /// The NspiGetTemplateInfo method returns information about template objects. /// </summary> /// <param name="flags">A DWORD value that contains a set of bit flags.</param> /// <param name="type">A DWORD value. It specifies the display type of the template for which the information is requested.</param> /// <param name="dn">The value NULL or the DN of the template requested. The value is NULL-terminated.</param> /// <param name="codePage">A DWORD value. It specifies the code page of the template for which the information is requested.</param> /// <param name="localeID">A DWORD value. It specifies the LCID of the template for which the information is requested.</param> /// <param name="data">A reference to a PropertyRow_r value. On return, it contains the information requested.</param> /// <returns>Status of NSPI method.</returns> public ErrorCodeValue GetTemplateInfo(uint flags, uint type, string dn, uint codePage, uint localeID, out PropertyRow_r? data) { ErrorCodeValue result; byte[] auxIn = new byte[] { }; GetTemplateInfoRequestBody getTemplateInfoRequestBody = new GetTemplateInfoRequestBody() { Flags = flags, DisplayType = type, CodePage = codePage, LocaleId = localeID, AuxiliaryBuffer = auxIn, AuxiliaryBufferSize = (uint)auxIn.Length }; if (!string.IsNullOrEmpty(dn)) { getTemplateInfoRequestBody.HasTemplateDn = true; getTemplateInfoRequestBody.TemplateDn = dn; } ChunkedResponse chunkedResponse = this.SendAddressBookRequest(getTemplateInfoRequestBody, RequestType.GetTemplateInfo); GetTemplateInfoResponseBody getTemplateInfoResponseBody = GetTemplateInfoResponseBody.Parse(chunkedResponse.ResponseBodyRawData); result = (ErrorCodeValue)getTemplateInfoResponseBody.ErrorCode; if (getTemplateInfoResponseBody.HasRow) { PropertyRow_r propertyRow = AdapterHelper.ParsePropertyRow_r(getTemplateInfoResponseBody.Row.Value); data = propertyRow; } else { data = null; } return result; } #endregion #region Private method /// <summary> /// Send the request to address book server endpoint. /// </summary> /// <param name="requestBody">The request body.</param> /// <param name="requestType">The type of the request.</param> /// <param name="cookieChange">Whether the session context cookie is changed.</param> /// <returns>The returned chunked response.</returns> private ChunkedResponse SendAddressBookRequest(IRequestBody requestBody, RequestType requestType, bool cookieChange = true) { byte[] rawBuffer = null; ChunkedResponse chunkedResponse = null; // Send the execute HTTP request and get the response HttpWebResponse response = MapiHttpAdapter.SendMAPIHttpRequest(this.site, this.addressBookUrl, this.userName, this.domainName, this.password, requestBody, requestType.ToString(), AdapterHelper.SessionContextCookies); rawBuffer = MapiHttpAdapter.ReadHttpResponse(response); string responseCode = response.Headers["X-ResponseCode"]; this.site.Assert.AreEqual<uint>(0, uint.Parse(responseCode), "The request to the address book server should be executed successfully!"); // Read the HTTP response buffer and parse the response to correct format chunkedResponse = ChunkedResponse.ParseChunkedResponse(rawBuffer); response.GetResponseStream().Close(); if (cookieChange) { AdapterHelper.SessionContextCookies = response.Cookies; } return chunkedResponse; } /// <summary> /// Initialize Bind request body. /// </summary> /// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param> /// <param name="flags">A set of bit flags that specify options to the server.</param> /// <returns>An instance of the Bind request body.</returns> private BindRequestBody BuildBindRequestBody(STAT stat, uint flags) { BindRequestBody bindRequestBody = new BindRequestBody(); bindRequestBody.State = stat; bindRequestBody.Flags = flags; bindRequestBody.HasState = true; byte[] auxIn = new byte[] { }; bindRequestBody.AuxiliaryBuffer = auxIn; bindRequestBody.AuxiliaryBufferSize = (uint)auxIn.Length; return bindRequestBody; } /// <summary> /// Initialize the Unbind request body. /// </summary> /// <returns>The Unbind request body</returns> private UnbindRequestBody BuildUnbindRequestBody() { UnbindRequestBody unbindRequest = new UnbindRequestBody(); unbindRequest.Reserved = 0x00000000; byte[] auxIn = new byte[] { }; unbindRequest.AuxiliaryBuffer = auxIn; unbindRequest.AuxiliaryBufferSize = (uint)auxIn.Length; return unbindRequest; } /// <summary> /// Build UpdateStat request body. /// </summary> /// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param> /// <returns>An instance of the UpdateStat request body.</returns> private UpdateStatRequestBody BuildUpdateStatRequestBody(STAT stat) { UpdateStatRequestBody updateStatRequestBody = new UpdateStatRequestBody(); updateStatRequestBody.Reserved = 0x0; updateStatRequestBody.HasState = true; updateStatRequestBody.State = stat; updateStatRequestBody.DeltaRequested = true; byte[] auxIn = new byte[] { }; updateStatRequestBody.AuxiliaryBuffer = auxIn; updateStatRequestBody.AuxiliaryBufferSize = (uint)auxIn.Length; return updateStatRequestBody; } /// <summary> /// Initialize the QueryColumns request body. /// </summary> /// <param name="flag">A set of bit flags that specify options to the server.</param> /// <returns>An instance of the QueryColumns request body.</returns> private QueryColumnsRequestBody BuildQueryColumnsRequestBody(uint flag) { QueryColumnsRequestBody queryColumnsRequestBody = new QueryColumnsRequestBody(); queryColumnsRequestBody.MapiFlags = flag; queryColumnsRequestBody.Reserved = 0x0; byte[] auxIn = new byte[] { }; queryColumnsRequestBody.AuxiliaryBuffer = auxIn; queryColumnsRequestBody.AuxiliaryBufferSize = (uint)auxIn.Length; return queryColumnsRequestBody; } /// <summary> /// Initialize the GetPropList request body. /// </summary> /// <param name="flag">A set of bit flags that specify options to the server.</param> /// <param name="mid">A minimal Entry ID structure that specifies the object for which to return properties.</param> /// <param name="codePage">An unsigned integer that specifies the code page that the server is being requested to use for string values of properties.</param> /// <returns>An instance of the GetPropList request body.</returns> private GetPropListRequestBody BuildGetPropListRequestBody(uint flag, uint mid, uint codePage) { GetPropListRequestBody getPropListRequestBody = new GetPropListRequestBody(); getPropListRequestBody.Flags = flag; getPropListRequestBody.CodePage = codePage; getPropListRequestBody.MinmalId = mid; byte[] auxIn = new byte[] { }; getPropListRequestBody.AuxiliaryBufferSize = (uint)auxIn.Length; getPropListRequestBody.AuxiliaryBuffer = auxIn; return getPropListRequestBody; } /// <summary> /// Initialize the GetProps request body. /// </summary> /// <param name="flags">A set of bit flags that specify options to the server.</param> /// <param name="hasState">A Boolean value that specifies whether the State field is present.</param> /// <param name="stat">A STAT block that describes a logical position in a specific address book container.</param> /// <param name="hasPropertyTags">A Boolean value that specifies whether the PropertyTags field is present.</param> /// <param name="propetyTags">A LargePropertyTagArray structure that contains the property tags of the properties that the client is requesting.</param> /// <returns>An instance of the GetProps request body.</returns> private GetPropsRequestBody BuildGetPropsRequestBody(uint flags, bool hasState, STAT? stat, bool hasPropertyTags, LargePropTagArray propetyTags) { GetPropsRequestBody getPropertyRequestBody = new GetPropsRequestBody(); getPropertyRequestBody.Flags = flags; byte[] auxIn = new byte[] { }; getPropertyRequestBody.AuxiliaryBuffer = auxIn; getPropertyRequestBody.AuxiliaryBufferSize = (uint)auxIn.Length; if (hasState) { getPropertyRequestBody.HasState = true; if (stat != null) { getPropertyRequestBody.State = (STAT)stat; } } else { getPropertyRequestBody.HasState = false; STAT statNew = new STAT(); getPropertyRequestBody.State = statNew; } if (hasPropertyTags) { getPropertyRequestBody.HasPropertyTags = true; getPropertyRequestBody.PropertyTags = propetyTags; } else { getPropertyRequestBody.HasPropertyTags = false; LargePropTagArray propetyTagsNew = new LargePropTagArray(); getPropertyRequestBody.PropertyTags = propetyTagsNew; } return getPropertyRequestBody; } #endregion } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type GraphServiceDirectoryRoleTemplatesCollectionRequest. /// </summary> public partial class GraphServiceDirectoryRoleTemplatesCollectionRequest : BaseRequest, IGraphServiceDirectoryRoleTemplatesCollectionRequest { /// <summary> /// Constructs a new GraphServiceDirectoryRoleTemplatesCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public GraphServiceDirectoryRoleTemplatesCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified DirectoryRoleTemplate to the collection via POST. /// </summary> /// <param name="directoryRoleTemplate">The DirectoryRoleTemplate to add.</param> /// <returns>The created DirectoryRoleTemplate.</returns> public System.Threading.Tasks.Task<DirectoryRoleTemplate> AddAsync(DirectoryRoleTemplate directoryRoleTemplate) { return this.AddAsync(directoryRoleTemplate, CancellationToken.None); } /// <summary> /// Adds the specified DirectoryRoleTemplate to the collection via POST. /// </summary> /// <param name="directoryRoleTemplate">The DirectoryRoleTemplate to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created DirectoryRoleTemplate.</returns> public System.Threading.Tasks.Task<DirectoryRoleTemplate> AddAsync(DirectoryRoleTemplate directoryRoleTemplate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<DirectoryRoleTemplate>(directoryRoleTemplate, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IGraphServiceDirectoryRoleTemplatesCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IGraphServiceDirectoryRoleTemplatesCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<GraphServiceDirectoryRoleTemplatesCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDirectoryRoleTemplatesCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDirectoryRoleTemplatesCollectionRequest Expand(Expression<Func<DirectoryRoleTemplate, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDirectoryRoleTemplatesCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDirectoryRoleTemplatesCollectionRequest Select(Expression<Func<DirectoryRoleTemplate, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDirectoryRoleTemplatesCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDirectoryRoleTemplatesCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDirectoryRoleTemplatesCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IGraphServiceDirectoryRoleTemplatesCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
// -------------------------------- // Auto Identifiers // -------------------------------- using System; using NUnit.Framework; namespace Markdig.Tests.Specs.AutoIdentifiers { [TestFixture] public class TestExtensionsHeadingAutoIdentifiers { // # Extensions // // This section describes the auto identifier extension // // ## Heading Auto Identifiers // // Allows to automatically creates an identifier for a heading: [Test] public void ExtensionsHeadingAutoIdentifiers_Example001() { // Example 1 // Section: Extensions / Heading Auto Identifiers // // The following Markdown: // # This is a heading // // Should be rendered as: // <h1 id="this-is-a-heading">This is a heading</h1> Console.WriteLine("Example 1\nSection Extensions / Heading Auto Identifiers\n"); TestParser.TestSpec("# This is a heading", "<h1 id=\"this-is-a-heading\">This is a heading</h1>", "autoidentifiers|advanced"); } // Only punctuation `-`, `_` and `.` is kept, all other non letter characters are discarded. // Consecutive same character `-`, `_` or `.` are rendered into a single one // Characters `-`, `_` and `.` at the end of the string are also discarded. [Test] public void ExtensionsHeadingAutoIdentifiers_Example002() { // Example 2 // Section: Extensions / Heading Auto Identifiers // // The following Markdown: // # This - is a &@! heading _ with . and ! - // // Should be rendered as: // <h1 id="this-is-a-heading_with.and">This - is a &amp;@! heading _ with . and ! -</h1> Console.WriteLine("Example 2\nSection Extensions / Heading Auto Identifiers\n"); TestParser.TestSpec("# This - is a &@! heading _ with . and ! -", "<h1 id=\"this-is-a-heading_with.and\">This - is a &amp;@! heading _ with . and ! -</h1>", "autoidentifiers|advanced"); } // Formatting (emphasis) are also discarded: [Test] public void ExtensionsHeadingAutoIdentifiers_Example003() { // Example 3 // Section: Extensions / Heading Auto Identifiers // // The following Markdown: // # This is a *heading* // // Should be rendered as: // <h1 id="this-is-a-heading">This is a <em>heading</em></h1> Console.WriteLine("Example 3\nSection Extensions / Heading Auto Identifiers\n"); TestParser.TestSpec("# This is a *heading*", "<h1 id=\"this-is-a-heading\">This is a <em>heading</em></h1>", "autoidentifiers|advanced"); } // Links are also removed: [Test] public void ExtensionsHeadingAutoIdentifiers_Example004() { // Example 4 // Section: Extensions / Heading Auto Identifiers // // The following Markdown: // # This is a [heading](/url) // // Should be rendered as: // <h1 id="this-is-a-heading">This is a <a href="/url">heading</a></h1> Console.WriteLine("Example 4\nSection Extensions / Heading Auto Identifiers\n"); TestParser.TestSpec("# This is a [heading](/url)", "<h1 id=\"this-is-a-heading\">This is a <a href=\"/url\">heading</a></h1>", "autoidentifiers|advanced"); } // If multiple heading have the same text, -1, -2...-n will be postfix to the header id. [Test] public void ExtensionsHeadingAutoIdentifiers_Example005() { // Example 5 // Section: Extensions / Heading Auto Identifiers // // The following Markdown: // # This is a heading // # This is a heading // // Should be rendered as: // <h1 id="this-is-a-heading">This is a heading</h1> // <h1 id="this-is-a-heading-1">This is a heading</h1> Console.WriteLine("Example 5\nSection Extensions / Heading Auto Identifiers\n"); TestParser.TestSpec("# This is a heading\n# This is a heading", "<h1 id=\"this-is-a-heading\">This is a heading</h1>\n<h1 id=\"this-is-a-heading-1\">This is a heading</h1>", "autoidentifiers|advanced"); } // The heading Id will start on the first letter character of the heading, all previous characters will be discarded: [Test] public void ExtensionsHeadingAutoIdentifiers_Example006() { // Example 6 // Section: Extensions / Heading Auto Identifiers // // The following Markdown: // # 1.0 This is a heading // // Should be rendered as: // <h1 id="this-is-a-heading">1.0 This is a heading</h1> Console.WriteLine("Example 6\nSection Extensions / Heading Auto Identifiers\n"); TestParser.TestSpec("# 1.0 This is a heading", "<h1 id=\"this-is-a-heading\">1.0 This is a heading</h1>", "autoidentifiers|advanced"); } // If the heading is all stripped by the previous rules, the id `section` will be used instead: [Test] public void ExtensionsHeadingAutoIdentifiers_Example007() { // Example 7 // Section: Extensions / Heading Auto Identifiers // // The following Markdown: // # 1.0 & ^ % * // # 1.0 & ^ % * // // Should be rendered as: // <h1 id="section">1.0 &amp; ^ % *</h1> // <h1 id="section-1">1.0 &amp; ^ % *</h1> Console.WriteLine("Example 7\nSection Extensions / Heading Auto Identifiers\n"); TestParser.TestSpec("# 1.0 & ^ % *\n# 1.0 & ^ % *", "<h1 id=\"section\">1.0 &amp; ^ % *</h1>\n<h1 id=\"section-1\">1.0 &amp; ^ % *</h1>", "autoidentifiers|advanced"); } // When the options "AutoLink" is setup, it is possible to link to an existing heading by using the // exact same Label text as the heading: [Test] public void ExtensionsHeadingAutoIdentifiers_Example008() { // Example 8 // Section: Extensions / Heading Auto Identifiers // // The following Markdown: // # This is a heading // [This is a heading] // // Should be rendered as: // <h1 id="this-is-a-heading">This is a heading</h1> // <p><a href="#this-is-a-heading">This is a heading</a></p> Console.WriteLine("Example 8\nSection Extensions / Heading Auto Identifiers\n"); TestParser.TestSpec("# This is a heading\n[This is a heading]", "<h1 id=\"this-is-a-heading\">This is a heading</h1>\n<p><a href=\"#this-is-a-heading\">This is a heading</a></p>", "autoidentifiers|advanced"); } // Links before the heading are also working: [Test] public void ExtensionsHeadingAutoIdentifiers_Example009() { // Example 9 // Section: Extensions / Heading Auto Identifiers // // The following Markdown: // [This is a heading] // # This is a heading // // Should be rendered as: // <p><a href="#this-is-a-heading">This is a heading</a></p> // <h1 id="this-is-a-heading">This is a heading</h1> Console.WriteLine("Example 9\nSection Extensions / Heading Auto Identifiers\n"); TestParser.TestSpec("[This is a heading]\n# This is a heading", "<p><a href=\"#this-is-a-heading\">This is a heading</a></p>\n<h1 id=\"this-is-a-heading\">This is a heading</h1>", "autoidentifiers|advanced"); } // The text of the link can be changed: [Test] public void ExtensionsHeadingAutoIdentifiers_Example010() { // Example 10 // Section: Extensions / Heading Auto Identifiers // // The following Markdown: // [With a new text][This is a heading] // # This is a heading // // Should be rendered as: // <p><a href="#this-is-a-heading">With a new text</a></p> // <h1 id="this-is-a-heading">This is a heading</h1> Console.WriteLine("Example 10\nSection Extensions / Heading Auto Identifiers\n"); TestParser.TestSpec("[With a new text][This is a heading]\n# This is a heading", "<p><a href=\"#this-is-a-heading\">With a new text</a></p>\n<h1 id=\"this-is-a-heading\">This is a heading</h1>", "autoidentifiers|advanced"); } // An autoidentifier should not conflict with an existing link: [Test] public void ExtensionsHeadingAutoIdentifiers_Example011() { // Example 11 // Section: Extensions / Heading Auto Identifiers // // The following Markdown: // ![scenario image][scenario] // ## Scenario // [scenario]: ./scenario.png // // Should be rendered as: // <p><img src="./scenario.png" alt="scenario image" /></p> // <h2 id="scenario">Scenario</h2> Console.WriteLine("Example 11\nSection Extensions / Heading Auto Identifiers\n"); TestParser.TestSpec("![scenario image][scenario]\n## Scenario\n[scenario]: ./scenario.png", "<p><img src=\"./scenario.png\" alt=\"scenario image\" /></p>\n<h2 id=\"scenario\">Scenario</h2>", "autoidentifiers|advanced"); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // The instantiation for the numerical analysis, based on the optimistic heap abstraction using System; using Generics = System.Collections.Generic; using Microsoft.Research.AbstractDomains.Expressions; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using Microsoft.Research.AbstractDomains.Numerical; using Microsoft.Research.DataStructures; namespace Microsoft.Research.CodeAnalysis { /// <summary> /// The decoder for the BoxedExpression class stores the decoder of the InternalExpression and ExternalExpression classes /// and apply them (for instance it uses the ExternalExpression decoder if the passed BoxedExpression contains an ExternalExpression, /// and it boxes the result obtained) /// </summary> public class BoxedExpressionDecoder<Type, Variable, ExternalExpression> : BoxedExpressionDecoder<Variable> { #region Private fields private IFullExpressionDecoder<Type, Variable, ExternalExpression> outdecoder; #endregion protected TypeSeeker typeseeker; public IFullExpressionDecoder<Type, Variable, ExternalExpression> Outdecoder { get { return this.outdecoder; } } #region Constructor /// <summary> /// In order to be instantiated it requires a decoder for the external expressions /// </summary> public BoxedExpressionDecoder(IFullExpressionDecoder<Type, Variable, ExternalExpression> outdecoder, TypeSeeker typeseeker) { this.outdecoder = outdecoder; this.typeseeker = typeseeker; } public BoxedExpressionDecoder(IFullExpressionDecoder<Type, Variable, ExternalExpression> outdecoder) { this.outdecoder = outdecoder; this.typeseeker = null; } #endregion #region Public methods implementing IExpressionDecoder //Usually the decoder just checks the type of the passed expression(s) and applies the InternalExpression decoder or the ExternalExpression one //[DebuggerStepThrough()] public override ExpressionOperator OperatorFor(BoxedExpression exp) { if (exp.IsVariable) return ExpressionOperator.Variable; if (exp.IsConstant) return ExpressionOperator.Constant; if (exp.IsSizeOf) return ExpressionOperator.SizeOf; if (exp.IsUnary) { #region All the cases switch (exp.UnaryOp) { case UnaryOperator.Conv_i2: return ExpressionOperator.ConvertToInt8; case UnaryOperator.Conv_i4: case UnaryOperator.Conv_i: case UnaryOperator.Conv_i8: return ExpressionOperator.ConvertToInt32; case UnaryOperator.Conv_u: case UnaryOperator.Conv_u4: case UnaryOperator.Conv_u8: return ExpressionOperator.ConvertToUInt32; case UnaryOperator.Conv_r4: return ExpressionOperator.ConvertToFloat32; case UnaryOperator.Conv_r8: return ExpressionOperator.ConvertToFloat64; case UnaryOperator.Conv_u2: return ExpressionOperator.ConvertToUInt16; case UnaryOperator.Conv_u1: return ExpressionOperator.ConvertToUInt8; case UnaryOperator.Neg: return ExpressionOperator.UnaryMinus; case UnaryOperator.Not: return ExpressionOperator.Not; case UnaryOperator.WritableBytes: return ExpressionOperator.WritableBytes; default: return ExpressionOperator.Unknown; } #endregion } if (exp.IsBinary) { #region all the cases switch (exp.BinaryOp) { case BinaryOperator.Add: return ExpressionOperator.Addition; case BinaryOperator.Add_Ovf: case BinaryOperator.Add_Ovf_Un: return ExpressionOperator.Addition_Overflow; case BinaryOperator.And: return ExpressionOperator.And; case BinaryOperator.Ceq: return ExpressionOperator.Equal; case BinaryOperator.Cobjeq: return ExpressionOperator.Equal_Obj; case BinaryOperator.Cge: return ExpressionOperator.GreaterEqualThan; case BinaryOperator.Cge_Un: return ExpressionOperator.GreaterEqualThan_Un; case BinaryOperator.Cgt: return ExpressionOperator.GreaterThan; case BinaryOperator.Cgt_Un: return ExpressionOperator.GreaterThan_Un; case BinaryOperator.Cle: return ExpressionOperator.LessEqualThan; case BinaryOperator.Cle_Un: return ExpressionOperator.LessEqualThan_Un; case BinaryOperator.Clt: return ExpressionOperator.LessThan; case BinaryOperator.Clt_Un: return ExpressionOperator.LessThan_Un; case BinaryOperator.Cne_Un: return ExpressionOperator.NotEqual; case BinaryOperator.Div: case BinaryOperator.Div_Un: return ExpressionOperator.Division; case BinaryOperator.LogicalAnd: return ExpressionOperator.LogicalAnd; case BinaryOperator.LogicalOr: return ExpressionOperator.LogicalOr; case BinaryOperator.Mul: return ExpressionOperator.Multiplication; case BinaryOperator.Mul_Ovf: case BinaryOperator.Mul_Ovf_Un: return ExpressionOperator.Multiplication_Overflow; case BinaryOperator.Or: return ExpressionOperator.Or; case BinaryOperator.Rem: case BinaryOperator.Rem_Un: return ExpressionOperator.Modulus; case BinaryOperator.Shl: return ExpressionOperator.ShiftLeft; case BinaryOperator.Shr: case BinaryOperator.Shr_Un: return ExpressionOperator.ShiftRight; case BinaryOperator.Sub: return ExpressionOperator.Subtraction; case BinaryOperator.Sub_Ovf: case BinaryOperator.Sub_Ovf_Un: return ExpressionOperator.Subtraction_Overflow; case BinaryOperator.Xor: return ExpressionOperator.Xor; default: return ExpressionOperator.Unknown; } #endregion } return ExpressionOperator.Unknown; } public override BoxedExpression LeftExpressionFor(BoxedExpression exp) { if (exp.IsBinary) { return exp.BinaryLeft; } if (exp.IsUnary) { return exp.UnaryArgument; } throw new InvalidOperationException(); } public override BoxedExpression RightExpressionFor(BoxedExpression exp) { if (exp.IsBinary) { return exp.BinaryRight; } throw new InvalidOperationException(); } public override ExpressionType TypeOf(BoxedExpression exp) { if (exp.IsConstant) { object value = exp.Constant; if (value == null) return ExpressionType.Unknown; IConvertible ic = value as IConvertible; if (ic != null) { switch (ic.GetTypeCode()) { case TypeCode.Boolean: return ExpressionType.Bool; case TypeCode.Byte: return ExpressionType.UInt8; case TypeCode.Single: return ExpressionType.Float32; case TypeCode.Double: return ExpressionType.Float64; case TypeCode.Int16: return ExpressionType.Int16; case TypeCode.Int32: return ExpressionType.Int32; case TypeCode.Int64: return ExpressionType.Int64; case TypeCode.SByte: return ExpressionType.Int8; case TypeCode.String: return ExpressionType.String; case TypeCode.UInt16: return ExpressionType.UInt16; case TypeCode.UInt32: return ExpressionType.UInt32; } } return ExpressionType.Unknown; } if (exp.IsUnary) { switch (exp.UnaryOp) { case UnaryOperator.Not: return ExpressionType.Bool; case UnaryOperator.Conv_i1: return ExpressionType.Int8; case UnaryOperator.Conv_i2: return ExpressionType.Int16; case UnaryOperator.Conv_i4: return ExpressionType.Int32; case UnaryOperator.Conv_i8: return ExpressionType.Int64; case UnaryOperator.Conv_u1: return ExpressionType.UInt8; case UnaryOperator.Conv_u2: return ExpressionType.UInt16; case UnaryOperator.Conv_u4: return ExpressionType.UInt32; case UnaryOperator.Conv_u8: return ExpressionType.UInt64; case UnaryOperator.Conv_r4: return ExpressionType.Float32; case UnaryOperator.Conv_r8: case UnaryOperator.Conv_r_un: return ExpressionType.Float64; default: return ExpressionType.Int32; } } if (exp.IsBinary) { switch (exp.BinaryOp) { case BinaryOperator.Ceq: case BinaryOperator.Cobjeq: case BinaryOperator.Cge: case BinaryOperator.Cge_Un: case BinaryOperator.Cgt: case BinaryOperator.Cgt_Un: case BinaryOperator.Cle: case BinaryOperator.Cle_Un: case BinaryOperator.Clt: case BinaryOperator.Clt_Un: case BinaryOperator.Cne_Un: return ExpressionType.Bool; case BinaryOperator.Add: case BinaryOperator.Add_Ovf: case BinaryOperator.Add_Ovf_Un: case BinaryOperator.Div: case BinaryOperator.Div_Un: case BinaryOperator.Mul: case BinaryOperator.Mul_Ovf: case BinaryOperator.Mul_Ovf_Un: case BinaryOperator.Rem: case BinaryOperator.Rem_Un: case BinaryOperator.Sub: case BinaryOperator.Sub_Ovf: case BinaryOperator.Sub_Ovf_Un: return Join(TypeOf(exp.BinaryLeft), TypeOf(exp.BinaryRight)); case BinaryOperator.Shl: case BinaryOperator.Shr: case BinaryOperator.Shr_Un: default: return ExpressionType.Int32; } } if (exp.IsVariable && this.typeseeker != null) { return this.typeseeker(exp); } return ExpressionType.Unknown; } private ExpressionType Join(ExpressionType e1, ExpressionType e2) { if (e1 == e2) { return e1; } if (e1 == ExpressionType.Unknown) { return e2; } if (e2 == ExpressionType.Unknown) { return e1; } if (e1 == ExpressionType.Float64 || e2 == ExpressionType.Float64) { return ExpressionType.Float64; } if (e1 == ExpressionType.Float32 || e2 == ExpressionType.Float32) { return ExpressionType.Float32; } return e1; } public override bool IsVariable(BoxedExpression exp) { return exp.IsVariable; } public override bool IsSlackVariable(BoxedVariable<Variable> var) { return var.IsSlackVariable; } public override bool IsFrameworkVariable(BoxedVariable<Variable> var) { return var.IsFrameworkVariable; } public override BoxedVariable<Variable> UnderlyingVariable(BoxedExpression exp) { // F: HACK: should be changed var embedded = exp.UnderlyingVariable; if (embedded is Variable) { return new BoxedVariable<Variable>((Variable) exp.UnderlyingVariable); } else if (exp.UnderlyingVariable is BoxedVariable<Variable>) { return (BoxedVariable<Variable>) embedded; } else { return new BoxedVariable<Variable>(false); } } public override bool IsConstant(BoxedExpression exp) { return exp != null && exp.IsConstant; } public override bool IsConstantInt(BoxedExpression exp, out int value) { return exp.IsConstantIntOrNull(out value); } public override bool IsNaN(BoxedExpression exp) { if (!exp.IsConstant) return false; object constant = exp.Constant; if (constant is float) { return ((float)constant).Equals(float.NaN); } if (constant is double) { return ((double)constant).Equals(double.NaN); } return false; } public override object Constant(BoxedExpression exp) { return exp.Constant; } public override bool IsWritableBytes(BoxedExpression exp) { return exp.IsUnary && exp.UnaryOp == UnaryOperator.WritableBytes; } public override bool IsNull(BoxedExpression exp) { return exp.IsConstant && exp.IsNull; } public override bool IsUnaryExpression(BoxedExpression exp) { return exp.IsUnary; } public override bool IsBinaryExpression(BoxedExpression exp) { return exp.IsBinary; } public override Set<BoxedVariable<Variable>> VariablesIn(BoxedExpression exp) { var retExp = new Set<BoxedExpression>(); exp.AddFreeVariables(retExp); var result = new Set<BoxedVariable<Variable>>(); foreach (var e in retExp) { BoxedVariable<Variable> bv; if (e.UnderlyingVariable is Variable) { bv = new BoxedVariable<Variable>((Variable)e.UnderlyingVariable); } else if (e.UnderlyingVariable is BoxedVariable<Variable>) { bv = (BoxedVariable<Variable>)e.UnderlyingVariable; } else { continue; } result.Add(bv); } return result; } public override bool TryValueOf<T>(BoxedExpression exp, ExpressionType aiType, out T value) { if (exp.IsConstant) { object tmpValue = exp.Constant; if (tmpValue != null) { if (tmpValue is T) { value = (T)tmpValue; return true; } if (tmpValue is String) { // early out to avoid format exceptions value = default(T); return false; } IConvertible ic = tmpValue as IConvertible; if (ic != null) { try { value = (T)ic.ToType(typeof(T), null); return true; } catch { } } } } value = default(T); return false; } public override string NameOf(BoxedVariable<Variable> var) { return var.ToString(); } public override bool IsSizeOf(BoxedExpression exp) { return exp.IsSizeOf; } public override bool TrySizeOf(BoxedExpression exp, out int value) { return exp.SizeOf(out value); } public override bool TryGetAssociatedExpression(BoxedExpression e, AssociatedInfo infoKind, out BoxedExpression info) { return e.TryGetAssociatedInfo(infoKind, out info); } public override bool TryGetAssociatedExpression(APC atPC, BoxedExpression e, AssociatedInfo infoKind, out BoxedExpression info) { return e.TryGetAssociatedInfo(atPC, infoKind, out info); } public override BoxedExpression Stripped(BoxedExpression exp) { if (exp.IsUnary) { switch (exp.UnaryOp) { case UnaryOperator.Conv_i: case UnaryOperator.Conv_i1: case UnaryOperator.Conv_i2: case UnaryOperator.Conv_i4: case UnaryOperator.Conv_i8: case UnaryOperator.Conv_r_un: case UnaryOperator.Conv_r4: case UnaryOperator.Conv_r8: case UnaryOperator.Conv_u: case UnaryOperator.Conv_u1: case UnaryOperator.Conv_u2: case UnaryOperator.Conv_u4: case UnaryOperator.Conv_u8: return exp.UnaryArgument; default: break; } } return exp; } #endregion } public abstract class BoxedExpressionDecoder<Variable> : IExpressionDecoder<BoxedVariable<Variable>, BoxedExpression> { public delegate ExpressionType TypeSeeker(object o); public static BoxedExpressionDecoder<Type, Variable, Expression> Decoder<Type, Expression>(IFullExpressionDecoder<Type, Variable, Expression> decoder, TypeSeeker typeseeker) where Expression : IEquatable<Expression> { Contract.Ensures(Contract.Result<BoxedExpressionDecoder<Type, Variable, Expression>>() != null); return new BoxedExpressionDecoder<Type, Variable, Expression>(decoder, typeseeker); } public static BoxedExpressionDecoder<Type, Variable, Expression> Decoder<Type, Expression>(IFullExpressionDecoder<Type, Variable, Expression> decoder) where Expression : IEquatable<Expression> { return new BoxedExpressionDecoder<Type, Variable, Expression>(decoder); } #region IExpressionDecoder<BoxedVariable<Expression>, BoxedExpression> Members public abstract ExpressionOperator OperatorFor(BoxedExpression exp); public abstract BoxedExpression LeftExpressionFor(BoxedExpression exp); public abstract BoxedExpression RightExpressionFor(BoxedExpression exp); public abstract bool IsNull(BoxedExpression exp); public abstract ExpressionType TypeOf(BoxedExpression exp); public abstract bool TryGetAssociatedExpression(BoxedExpression exp, AssociatedInfo infoKind, out BoxedExpression info); public abstract bool TryGetAssociatedExpression(APC atPC, BoxedExpression exp, AssociatedInfo infoKind, out BoxedExpression info); public abstract bool IsVariable(BoxedExpression exp); public abstract bool IsSlackVariable(BoxedVariable<Variable> var); public abstract bool IsFrameworkVariable(BoxedVariable<Variable> var); public abstract BoxedVariable<Variable> UnderlyingVariable(BoxedExpression exp); public abstract bool IsConstant(BoxedExpression exp); public abstract bool IsConstantInt(BoxedExpression exp, out int value); public abstract bool IsNaN(BoxedExpression exp); public abstract object Constant(BoxedExpression exp); public abstract bool IsWritableBytes(BoxedExpression exp); public abstract bool IsUnaryExpression(BoxedExpression exp); public abstract bool IsBinaryExpression(BoxedExpression exp); public abstract bool IsSizeOf(BoxedExpression exp); public abstract bool TrySizeOf(BoxedExpression type, out int value); public abstract Set<BoxedVariable<Variable>> VariablesIn(BoxedExpression exp); public abstract bool TryValueOf<T>(BoxedExpression exp, ExpressionType aiType, out T value); public abstract string NameOf(BoxedVariable<Variable> var); public abstract BoxedExpression Stripped(BoxedExpression exp); #endregion public IEnumerable<BoxedExpression> Disjunctions(BoxedExpression exp) { return exp.SplitDisjunctions(); } public bool IsSlackOrFrameworkVariable(BoxedVariable<Variable> v) { return this.IsFrameworkVariable(v) || this.IsSlackVariable(v); } } public abstract class BoxedExpressionEncoder<Variable> : IExpressionEncoder<BoxedVariable<Variable>, BoxedExpression> { public static IExpressionEncoder<BoxedVariable<Variable>, BoxedExpression> Encoder<Local, Parameter, Method, Field, Property, Event, Type, Expression, /*Variable,*/ Attribute, Assembly>( IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder, IExpressionContext<Local, Parameter, Method, Field, Type, Expression, Variable> context ) where Expression : IEquatable<Expression> where Type : IEquatable<Type> { Contract.Ensures(Contract.Result<IExpressionEncoder<BoxedVariable<Variable>, BoxedExpression>>() != null); return new BoxedExpressionEncoder<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Variable>(mdDecoder); } #region IExpressionEncoder<BoxedVariable<Variable>, BoxedExpression> Members // F: This is only for debugging public abstract void ResetFreshVariableCounter(); public abstract BoxedVariable<Variable> FreshVariable<T>(); public abstract BoxedExpression ConstantFor(object value); public abstract BoxedExpression VariableFor(BoxedVariable<Variable> v); public abstract BoxedExpression CompoundExpressionFor(ExpressionType type, ExpressionOperator op, BoxedExpression left); public abstract BoxedExpression CompoundExpressionFor(ExpressionType type, ExpressionOperator op, BoxedExpression left, BoxedExpression right); public abstract BoxedExpression Substitute(BoxedExpression source, BoxedExpression x, BoxedExpression exp); #endregion } /// <summary> /// The encoder for the BoxedExpression class that creates no external boxes /// </summary> public class BoxedExpressionEncoder<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly, Variable> : BoxedExpressionEncoder<Variable> { #region Private fields readonly IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder; private class VariableRep : IEquatable<VariableRep> { private static int idgen; private readonly int id; public VariableRep() { this.id = ++idgen; } public override string ToString() { return "x" + this.id.ToString(); } #region IEquatable<VariableRep> Members public bool Equals(VariableRep other) { return this.id == other.id; } #endregion } #endregion #region Constructor public BoxedExpressionEncoder(IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> mdDecoder) { this.mdDecoder = mdDecoder; } #endregion #region Public methods implementing IExpressionEncoder public override void ResetFreshVariableCounter() { BoxedVariable<Variable>.ResetFreshVariableCounter(); } public override BoxedVariable<Variable> FreshVariable<T>() { return new BoxedVariable<Variable>(true); } public override BoxedExpression ConstantFor(object value) { Contract.Assume(!(value is Rational)); if (value is Int32) { return BoxedExpression.Const(value, mdDecoder.System_Int32, mdDecoder); } if (value is Int64) { long l = (long)value; if (l < Int32.MaxValue && l > Int32.MinValue) { int i = (int)l; return BoxedExpression.Const(i, mdDecoder.System_Int32, mdDecoder); } return BoxedExpression.Const(value, mdDecoder.System_Int64, mdDecoder); } if (value is Int16) { return BoxedExpression.Const(value, mdDecoder.System_Int16, mdDecoder); } if (value is SByte) { return BoxedExpression.Const(value, mdDecoder.System_Int8, mdDecoder); } if (value is bool) { return BoxedExpression.Const(value, mdDecoder.System_Boolean, mdDecoder); } // default: // Value and type must agree, otherwise we fail later. throw new NotImplementedException(); } public override BoxedExpression VariableFor(BoxedVariable<Variable> v) { return BoxedExpression.Var(v); } public override BoxedExpression CompoundExpressionFor(ExpressionType type, ExpressionOperator op, BoxedExpression arg) { return BoxedExpression.Unary(ConvertToUnary(op), arg); } public override BoxedExpression CompoundExpressionFor(ExpressionType type, ExpressionOperator op, BoxedExpression left, BoxedExpression right) { return BoxedExpression.Binary(ConvertToBinary(op), left, right); } public override BoxedExpression Substitute(BoxedExpression source, BoxedExpression x, BoxedExpression exp) { return source.Substitute(x, exp); } #endregion #region Helpers internal static UnaryOperator ConvertToUnary(ExpressionOperator op) { switch (op) { case ExpressionOperator.ConvertToInt32: return UnaryOperator.Conv_i4; case ExpressionOperator.ConvertToUInt16: return UnaryOperator.Conv_u2; case ExpressionOperator.ConvertToUInt32: return UnaryOperator.Conv_u4; case ExpressionOperator.ConvertToUInt8: return UnaryOperator.Conv_u1; case ExpressionOperator.ConvertToFloat32: return UnaryOperator.Conv_r4; case ExpressionOperator.ConvertToFloat64: return UnaryOperator.Conv_r8; case ExpressionOperator.Not: return UnaryOperator.Not; case ExpressionOperator.UnaryMinus: return UnaryOperator.Neg; case ExpressionOperator.WritableBytes: return UnaryOperator.WritableBytes; default: throw new NotImplementedException(); } } internal static BinaryOperator ConvertToBinary(ExpressionOperator op) { switch (op) { case ExpressionOperator.Addition: return BinaryOperator.Add; case ExpressionOperator.And: return BinaryOperator.And; case ExpressionOperator.Division: return BinaryOperator.Div; case ExpressionOperator.Equal: return BinaryOperator.Ceq; case ExpressionOperator.Equal_Obj: return BinaryOperator.Cobjeq; case ExpressionOperator.GreaterEqualThan: return BinaryOperator.Cge; case ExpressionOperator.GreaterEqualThan_Un: return BinaryOperator.Cge_Un; case ExpressionOperator.GreaterThan: return BinaryOperator.Cgt; case ExpressionOperator.GreaterThan_Un: return BinaryOperator.Cgt_Un; case ExpressionOperator.LessEqualThan: return BinaryOperator.Cle; case ExpressionOperator.LessEqualThan_Un: return BinaryOperator.Cle_Un; case ExpressionOperator.LessThan: return BinaryOperator.Clt; case ExpressionOperator.LessThan_Un: return BinaryOperator.Clt_Un; case ExpressionOperator.Modulus: return BinaryOperator.Rem; case ExpressionOperator.Multiplication: return BinaryOperator.Mul; case ExpressionOperator.Multiplication_Overflow: return BinaryOperator.Mul_Ovf; case ExpressionOperator.NotEqual: return BinaryOperator.Cne_Un; case ExpressionOperator.Or: return BinaryOperator.Or; case ExpressionOperator.ShiftLeft: return BinaryOperator.Shl; case ExpressionOperator.ShiftRight: return BinaryOperator.Shr; case ExpressionOperator.Subtraction: return BinaryOperator.Sub; case ExpressionOperator.Xor: return BinaryOperator.Xor; default: throw new NotImplementedException(); } } #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.Diagnostics; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { internal sealed partial class ExpressionBinder { // ---------------------------------------------------------------------------- // BindExplicitConversion // ---------------------------------------------------------------------------- private sealed class ExplicitConversion { private readonly ExpressionBinder _binder; private Expr _exprSrc; private readonly CType _typeSrc; private readonly CType _typeDest; private readonly ExprClass _exprTypeDest; // This is for lambda error reporting. The reason we have this is because we // store errors for lambda conversions, and then we don't bind the conversion // again to report errors. Consider the following case: // // int? x = () => null; // // When we try to convert the lambda to the nullable type int?, we first // attempt the conversion to int. If that fails, then we know there is no // conversion to int?, since int is a predef type. We then look for UserDefined // conversions, and fail. When we report the errors, we ask the lambda for its // conversion errors. But since we attempted its conversion to int and not int?, // we report the wrong error. This field is to keep track of the right type // to report the error on, so that when the lambda conversion fails, it reports // errors on the correct type. private readonly CType _pDestinationTypeForLambdaErrorReporting; private Expr _exprDest; private readonly bool _needsExprDest; private readonly CONVERTTYPE _flags; // ---------------------------------------------------------------------------- // BindExplicitConversion // ---------------------------------------------------------------------------- public ExplicitConversion(ExpressionBinder binder, Expr exprSrc, CType typeSrc, ExprClass typeDest, CType pDestinationTypeForLambdaErrorReporting, bool needsExprDest, CONVERTTYPE flags) { _binder = binder; _exprSrc = exprSrc; _typeSrc = typeSrc; _typeDest = typeDest.Type; _pDestinationTypeForLambdaErrorReporting = pDestinationTypeForLambdaErrorReporting; _exprTypeDest = typeDest; _needsExprDest = needsExprDest; _flags = flags; _exprDest = null; } public Expr ExprDest { get { return _exprDest; } } /* * BindExplicitConversion * * This is a complex routine with complex parameter. Generally, this should * be called through one of the helper methods that insulates you * from the complexity of the interface. This routine handles all the logic * associated with explicit conversions. * * Note that this function calls BindImplicitConversion first, so the main * logic is only concerned with conversions that can be made explicitly, but * not implicitly. */ public bool Bind() { // To test for a standard conversion, call canConvert(exprSrc, typeDest, STANDARDANDCONVERTTYPE.NOUDC) and // canConvert(typeDest, typeSrc, STANDARDANDCONVERTTYPE.NOUDC). Debug.Assert((_flags & CONVERTTYPE.STANDARD) == 0); // 13.2 Explicit conversions // // The following conversions are classified as explicit conversions: // // * All implicit conversions // * Explicit numeric conversions // * Explicit enumeration conversions // * Explicit reference conversions // * Explicit interface conversions // * Unboxing conversions // * Explicit type parameter conversions // * User-defined explicit conversions // * Explicit nullable conversions // * Lifted user-defined explicit conversions // // Explicit conversions can occur in cast expressions (14.6.6). // // The explicit conversions that are not implicit conversions are conversions that cannot be // proven always to succeed, conversions that are known possibly to lose information, and // conversions across domains of types sufficiently different to merit explicit notation. // The set of explicit conversions includes all implicit conversions. // Don't try user-defined conversions now because we'll try them again later. if (_binder.BindImplicitConversion(_exprSrc, _typeSrc, _exprTypeDest, _pDestinationTypeForLambdaErrorReporting, _needsExprDest, out _exprDest, _flags | CONVERTTYPE.ISEXPLICIT)) { return true; } if (_typeSrc == null || _typeDest == null || _typeSrc is ErrorType || _typeDest is ErrorType || _typeDest.IsNeverSameType()) { return false; } if (_typeDest is NullableType) { // This is handled completely by BindImplicitConversion. return false; } if (_typeSrc is NullableType) { return bindExplicitConversionFromNub(); } if (bindExplicitConversionFromArrayToIList()) { return true; } // if we were casting an integral constant to another constant type, // then, if the constant were in range, then the above call would have succeeded. // But it failed, and so we know that the constant is not in range switch (_typeDest.GetTypeKind()) { default: Debug.Fail($"Bad type kind: {_typeDest.GetTypeKind()}"); return false; case TypeKind.TK_VoidType: return false; // Can't convert to a method group or anon method. case TypeKind.TK_NullType: return false; // Can never convert TO the null type. case TypeKind.TK_ArrayType: if (bindExplicitConversionToArray((ArrayType)_typeDest)) { return true; } break; case TypeKind.TK_PointerType: if (bindExplicitConversionToPointer()) { return true; } break; case TypeKind.TK_AggregateType: { AggCastResult result = bindExplicitConversionToAggregate(_typeDest as AggregateType); if (result == AggCastResult.Success) { return true; } if (result == AggCastResult.Abort) { return false; } break; } } // No built-in conversion was found. Maybe a user-defined conversion? if (0 == (_flags & CONVERTTYPE.NOUDC)) { return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, false); } return false; } private bool bindExplicitConversionFromNub() { Debug.Assert(_typeSrc != null); Debug.Assert(_typeDest != null); // If S and T are value types and there is a builtin conversion from S => T then there is an // explicit conversion from S? => T that throws on null. if (_typeDest.IsValType() && _binder.BindExplicitConversion(null, _typeSrc.StripNubs(), _exprTypeDest, _pDestinationTypeForLambdaErrorReporting, _flags | CONVERTTYPE.NOUDC)) { if (_needsExprDest) { Expr valueSrc = _exprSrc; if (valueSrc.Type is NullableType) { valueSrc = _binder.BindNubValue(valueSrc); } Debug.Assert(valueSrc.Type == _typeSrc.StripNubs()); if (!_binder.BindExplicitConversion(valueSrc, valueSrc.Type, _exprTypeDest, _pDestinationTypeForLambdaErrorReporting, _needsExprDest, out _exprDest, _flags | CONVERTTYPE.NOUDC)) { Debug.Fail("BindExplicitConversion failed unexpectedly"); return false; } if (_exprDest is ExprUserDefinedConversion udc) { udc.Argument = _exprSrc; } } return true; } if ((_flags & CONVERTTYPE.NOUDC) == 0) { return _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, _typeDest, _needsExprDest, out _exprDest, false); } return false; } private bool bindExplicitConversionFromArrayToIList() { // 13.2.2 // // The explicit reference conversions are: // // * From a one-dimensional array-type S[] to System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and // their base interfaces, provided there is an explicit reference conversion from S to T. Debug.Assert(_typeSrc != null); Debug.Assert(_typeDest != null); if (!(_typeSrc is ArrayType arrSrc) || !arrSrc.IsSZArray || !(_typeDest is AggregateType aggDest) || !aggDest.isInterfaceType() || aggDest.GetTypeArgsAll().Count != 1) { return false; } AggregateSymbol aggIList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_ILIST); AggregateSymbol aggIReadOnlyList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_IREADONLYLIST); if ((aggIList == null || !SymbolLoader.IsBaseAggregate(aggIList, aggDest.getAggregate())) && (aggIReadOnlyList == null || !SymbolLoader.IsBaseAggregate(aggIReadOnlyList, aggDest.getAggregate()))) { return false; } CType typeArr = arrSrc.GetElementType(); CType typeLst = aggDest.GetTypeArgsAll()[0]; if (!CConversions.FExpRefConv(GetSymbolLoader(), typeArr, typeLst)) { return false; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } private bool bindExplicitConversionFromIListToArray(ArrayType arrayDest) { // 13.2.2 // // The explicit reference conversions are: // // * From System.Collections.Generic.IList<T>, System.Collections.Generic.IReadOnlyList<T> and their base interfaces // to a one-dimensional array-type S[], provided there is an implicit or explicit reference conversion from // S[] to System.Collections.Generic.IList<T> or System.Collections.Generic.IReadOnlyList<T>. This is precisely when either S and T // are the same type or there is an implicit or explicit reference conversion from S to T. if (!arrayDest.IsSZArray || !(_typeSrc is AggregateType aggSrc) || !aggSrc.isInterfaceType() || aggSrc.GetTypeArgsAll().Count != 1) { return false; } AggregateSymbol aggIList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_ILIST); AggregateSymbol aggIReadOnlyList = GetSymbolLoader().GetPredefAgg(PredefinedType.PT_G_IREADONLYLIST); if ((aggIList == null || !SymbolLoader.IsBaseAggregate(aggIList, aggSrc.getAggregate())) && (aggIReadOnlyList == null || !SymbolLoader.IsBaseAggregate(aggIReadOnlyList, aggSrc.getAggregate()))) { return false; } CType typeArr = arrayDest.GetElementType(); CType typeLst = aggSrc.GetTypeArgsAll()[0]; Debug.Assert(!typeArr.IsNeverSameType()); if (typeArr != typeLst && !CConversions.FExpRefConv(GetSymbolLoader(), typeArr, typeLst)) { return false; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } private bool bindExplicitConversionFromArrayToArray(ArrayType arraySrc, ArrayType arrayDest) { // 13.2.2 // // The explicit reference conversions are: // // * From an array-type S with an element type SE to an array-type T with an element type // TE, provided all of the following are true: // // * S and T differ only in element type. (In other words, S and T have the same number // of dimensions.) // // * An explicit reference conversion exists from SE to TE. if (arraySrc.rank != arrayDest.rank || arraySrc.IsSZArray != arrayDest.IsSZArray) { return false; // Ranks do not match. } if (CConversions.FExpRefConv(GetSymbolLoader(), arraySrc.GetElementType(), arrayDest.GetElementType())) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } return false; } private bool bindExplicitConversionToArray(ArrayType arrayDest) { Debug.Assert(_typeSrc != null); Debug.Assert(arrayDest != null); if (_typeSrc is ArrayType arrSrc) { return bindExplicitConversionFromArrayToArray(arrSrc, arrayDest); } if (bindExplicitConversionFromIListToArray(arrayDest)) { return true; } // 13.2.2 // // The explicit reference conversions are: // // * From System.Array and the interfaces it implements, to any array-type. if (_binder.canConvert(_binder.GetPredefindType(PredefinedType.PT_ARRAY), _typeSrc, CONVERTTYPE.NOUDC)) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK); return true; } return false; } private bool bindExplicitConversionToPointer() { // 27.4 Pointer conversions // // in an unsafe context, the set of available explicit conversions (13.2) is extended to // include the following explicit pointer conversions: // // * From any pointer-type to any other pointer-type. // * From sbyte, byte, short, ushort, int, uint, long, or ulong to any pointer-type. if (_typeSrc is PointerType || _typeSrc.fundType() <= FUNDTYPE.FT_LASTINTEGRAL && _typeSrc.isNumericType()) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return true; } return false; } // 13.2.2 Explicit enumeration conversions // // The explicit enumeration conversions are: // // * From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or // decimal to any enum-type. // // * From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, char, // float, double, or decimal. // // * From any enum-type to any other enum-type. // // * An explicit enumeration conversion between two types is processed by treating any // participating enum-type as the underlying type of that enum-type, and then performing // an implicit or explicit numeric conversion between the resulting types. private AggCastResult bindExplicitConversionFromEnumToAggregate(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!_typeSrc.isEnumType()) { return AggCastResult.Failure; } AggregateSymbol aggDest = aggTypeDest.getAggregate(); if (aggDest.isPredefAgg(PredefinedType.PT_DECIMAL)) { return bindExplicitConversionFromEnumToDecimal(aggTypeDest); } if (!aggDest.getThisType().isNumericType() && !aggDest.IsEnum() && !(aggDest.IsPredefined() && aggDest.GetPredefType() == PredefinedType.PT_CHAR)) { return AggCastResult.Failure; } if (_exprSrc.GetConst() != null) { ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; } else if (result == ConstCastResult.CheckFailure) { return AggCastResult.Abort; } } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return AggCastResult.Success; } private AggCastResult bindExplicitConversionFromDecimalToEnum(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(_typeSrc.isPredefType(PredefinedType.PT_DECIMAL)); // There is an explicit conversion from decimal to all integral types. if (_exprSrc.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } // All casts from decimal to integer types are bound as user-defined conversions. bool bIsConversionOK = true; if (_needsExprDest) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. CType underlyingType = aggTypeDest.underlyingType(); bIsConversionOK = _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, underlyingType, _needsExprDest, out _exprDest, false); if (bIsConversionOK) { // upcast to the Enum type _binder.bindSimpleCast(_exprDest, _exprTypeDest, out _exprDest); } } return bIsConversionOK ? AggCastResult.Success : AggCastResult.Failure; } private AggCastResult bindExplicitConversionFromEnumToDecimal(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); Debug.Assert(aggTypeDest.isPredefType(PredefinedType.PT_DECIMAL)); AggregateType underlyingType = _typeSrc.underlyingType() as AggregateType; // Need to first cast the source expr to its underlying type. Expr exprCast; if (_exprSrc == null) { exprCast = null; } else { ExprClass underlyingExpr = GetExprFactory().CreateClass(underlyingType); _binder.bindSimpleCast(_exprSrc, underlyingExpr, out exprCast); } // There is always an implicit conversion from any integral type to decimal. if (exprCast.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(exprCast, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } // Conversions from integral types to decimal are always bound as a user-defined conversion. if (_needsExprDest) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. bool ok = _binder.bindUserDefinedConversion(exprCast, underlyingType, aggTypeDest, _needsExprDest, out _exprDest, false); Debug.Assert(ok); } return AggCastResult.Success; } private AggCastResult bindExplicitConversionToEnum(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); AggregateSymbol aggDest = aggTypeDest.getAggregate(); if (!aggDest.IsEnum()) { return AggCastResult.Failure; } if (_typeSrc.isPredefType(PredefinedType.PT_DECIMAL)) { return bindExplicitConversionFromDecimalToEnum(aggTypeDest); } if (_typeSrc.isNumericType() || (_typeSrc.isPredefined() && _typeSrc.getPredefType() == PredefinedType.PT_CHAR)) { // Transform constant to constant. if (_exprSrc.GetConst() != null) { ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; } if (result == ConstCastResult.CheckFailure) { return AggCastResult.Abort; } } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return AggCastResult.Success; } else if (_typeSrc.isPredefined() && (_typeSrc.isPredefType(PredefinedType.PT_OBJECT) || _typeSrc.isPredefType(PredefinedType.PT_VALUE) || _typeSrc.isPredefType(PredefinedType.PT_ENUM))) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_UNBOX); return AggCastResult.Success; } return AggCastResult.Failure; } private AggCastResult bindExplicitConversionBetweenSimpleTypes(AggregateType aggTypeDest) { // 13.2.1 // // Because the explicit conversions include all implicit and explicit numeric conversions, // it is always possible to convert from any numeric-type to any other numeric-type using // a cast expression (14.6.6). Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!_typeSrc.isSimpleType() || !aggTypeDest.isSimpleType()) { return AggCastResult.Failure; } AggregateSymbol aggDest = aggTypeDest.getAggregate(); Debug.Assert(_typeSrc.isPredefined() && aggDest.IsPredefined()); PredefinedType ptSrc = _typeSrc.getPredefType(); PredefinedType ptDest = aggDest.GetPredefType(); Debug.Assert((int)ptSrc < NUM_SIMPLE_TYPES && (int)ptDest < NUM_SIMPLE_TYPES); ConvKind convertKind = GetConvKind(ptSrc, ptDest); // Identity and implicit conversions should already have been handled. Debug.Assert(convertKind != ConvKind.Implicit); Debug.Assert(convertKind != ConvKind.Identity); if (convertKind != ConvKind.Explicit) { return AggCastResult.Failure; } if (_exprSrc.GetConst() != null) { // Fold the constant cast if possible. ConstCastResult result = _binder.bindConstantCast(_exprSrc, _exprTypeDest, _needsExprDest, out _exprDest, true); if (result == ConstCastResult.Success) { return AggCastResult.Success; // else, don't fold and use a regular cast, below. } if (result == ConstCastResult.CheckFailure && 0 == (_flags & CONVERTTYPE.CHECKOVERFLOW)) { return AggCastResult.Abort; } } bool bConversionOk = true; if (_needsExprDest) { // Explicit conversions involving decimals are bound as user-defined conversions. if (isUserDefinedConversion(ptSrc, ptDest)) { // According the language, this is a standard conversion, but it is implemented // through a user-defined conversion. Because it's a standard conversion, we don't // test the CONVERTTYPE.NOUDC flag here. bConversionOk = _binder.bindUserDefinedConversion(_exprSrc, _typeSrc, aggTypeDest, _needsExprDest, out _exprDest, false); } else { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, (_flags & CONVERTTYPE.CHECKOVERFLOW) != 0 ? EXPRFLAG.EXF_CHECKOVERFLOW : 0); } } return bConversionOk ? AggCastResult.Success : AggCastResult.Failure; } private AggCastResult bindExplicitConversionBetweenAggregates(AggregateType aggTypeDest) { // 13.2.3 // // The explicit reference conversions are: // // * From object to any reference-type. // * From any class-type S to any class-type T, provided S is a base class of T. // * From any class-type S to any interface-type T, provided S is not sealed and // provided S does not implement T. // * From any interface-type S to any class-type T, provided T is not sealed or provided // T implements S. // * From any interface-type S to any interface-type T, provided S is not derived from T. Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); if (!(_typeSrc is AggregateType atSrc)) { return AggCastResult.Failure; } AggregateSymbol aggSrc = atSrc.getAggregate(); AggregateSymbol aggDest = aggTypeDest.getAggregate(); if (GetSymbolLoader().HasBaseConversion(aggTypeDest, atSrc)) { if (_needsExprDest) { if (aggDest.IsValueType() && aggSrc.getThisType().fundType() == FUNDTYPE.FT_REF) { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_UNBOX); } else { _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK | (_exprSrc?.Flags & EXPRFLAG.EXF_CANTBENULL ?? 0)); } } return AggCastResult.Success; } if ((aggSrc.IsClass() && !aggSrc.IsSealed() && aggDest.IsInterface()) || (aggSrc.IsInterface() && aggDest.IsClass() && !aggDest.IsSealed()) || (aggSrc.IsInterface() && aggDest.IsInterface()) || CConversions.HasGenericDelegateExplicitReferenceConversion(GetSymbolLoader(), _typeSrc, aggTypeDest)) { if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest, EXPRFLAG.EXF_REFCHECK | (_exprSrc?.Flags & EXPRFLAG.EXF_CANTBENULL ?? 0)); return AggCastResult.Success; } return AggCastResult.Failure; } private AggCastResult bindExplicitConversionFromPointerToInt(AggregateType aggTypeDest) { // 27.4 Pointer conversions // in an unsafe context, the set of available explicit conversions (13.2) is extended to include // the following explicit pointer conversions: // // * From any pointer-type to sbyte, byte, short, ushort, int, uint, long, or ulong. if (!(_typeSrc is PointerType) || aggTypeDest.fundType() > FUNDTYPE.FT_LASTINTEGRAL || !aggTypeDest.isNumericType()) { return AggCastResult.Failure; } if (_needsExprDest) _binder.bindSimpleCast(_exprSrc, _exprTypeDest, out _exprDest); return AggCastResult.Success; } private AggCastResult bindExplicitConversionToAggregate(AggregateType aggTypeDest) { Debug.Assert(_typeSrc != null); Debug.Assert(aggTypeDest != null); AggCastResult result = bindExplicitConversionFromEnumToAggregate(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionToEnum(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionBetweenSimpleTypes(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionBetweenAggregates(aggTypeDest); if (result != AggCastResult.Failure) { return result; } result = bindExplicitConversionFromPointerToInt(aggTypeDest); if (result != AggCastResult.Failure) { return result; } if (_typeSrc is VoidType) { // No conversion is allowed to or from a void type (user defined or otherwise) // This is most likely the result of a failed anonymous method or member group conversion return AggCastResult.Abort; } return AggCastResult.Failure; } private SymbolLoader GetSymbolLoader() { return _binder.GetSymbolLoader(); } private ExprFactory GetExprFactory() { return _binder.GetExprFactory(); } } } }
using System; using System.Collections.Generic; using Loon.Utils; using Loon.Utils.Xml; using Loon.Java; namespace Loon.Action.Sprite.Node { public class DefinitionReader { private Type curClass; public const string flag_source = "src"; public const string flag_type = "type"; protected internal string _classType; protected internal string _source; public DefinitionObject currentDefinitionObject = null; private bool isCurrentElementDefined = false; private static DefinitionReader instance; private static readonly Dictionary<string, Type> change = new Dictionary<string, Type>(10); static DefinitionReader() { CollectionUtils.Put(change, "image", typeof(DefImage)); CollectionUtils.Put(change, "animation", typeof(DefAnimation)); } public static DefinitionReader Get() { lock (typeof(DefinitionReader)) { if (instance == null) { instance = new DefinitionReader(); } return instance; } } private readonly DefListener listener; private DefinitionReader() { listener = new DefListener(this); } protected internal string _path; public virtual string GetCurrentPath() { return this._path; } private void StopElement(string name) { Type clazz = (Type)CollectionUtils.Get(change, name.ToLower()); if (clazz != null && clazz.Equals(this.curClass)) { this.currentDefinitionObject.DefinitionObjectDidFinishParsing(); if (this.currentDefinitionObject.parentDefinitionObject != null) { this.currentDefinitionObject.parentDefinitionObject.ChildDefinitionObjectDidFinishParsing(this.currentDefinitionObject); } this.currentDefinitionObject = this.currentDefinitionObject.parentDefinitionObject; if (this.currentDefinitionObject != null) { this.curClass = this.currentDefinitionObject.GetType(); this.isCurrentElementDefined = true; } else { this.curClass = null; this.isCurrentElementDefined = false; } } else if (this.currentDefinitionObject != null) { this.currentDefinitionObject.UndefinedElementDidFinish(name); } } private void ParseContent(string str) { if (this.isCurrentElementDefined) { this.currentDefinitionObject.DefinitionObjectDidReceiveString(str); } else { this.currentDefinitionObject.UndefinedElementDidReceiveString(str); } } private class DefListener : XMLListener { private DefinitionReader _read; public DefListener(DefinitionReader read) { _read = read; } public virtual void AddHeader(int line, XMLProcessing xp) { } public virtual void AddData(int line, XMLData data) { if (data != null) { string content = data.ToString().Trim(); if (!"".Equals(content)) { _read.ParseContent(content); } } } public virtual void AddComment(int line, XMLComment c) { } public virtual void AddAttribute(int line, XMLAttribute a) { if (a != null) { XMLElement ele = a.GetElement(); if (flag_source.ToUpper() == a.GetName().ToUpper()) { _read._source = a.GetValue(); } else if (flag_type.ToUpper() == a.GetName().ToUpper()) { _read._classType = a.GetValue(); } else if (ele != null) { _read._classType = ele.GetName(); } } } public virtual void AddElement(int line, XMLElement e) { _read.StartElement(e != null ? e.GetName() : _read._classType); } public virtual void EndElement(int line, XMLElement e) { _read.StopElement(e != null ? e.GetName() : _read._classType); } } public virtual void Load(string resName) { this._path = resName; this._classType = null; this._source = null; this.currentDefinitionObject = null; this.isCurrentElementDefined = false; XMLParser.Parse(resName, listener); } public virtual void Load(InputStream res) { this._path = null; this._classType = null; this._source = null; this.currentDefinitionObject = null; this.isCurrentElementDefined = false; XMLParser.Parse(res, listener); } private void StartElement(string name) { Type clazz = (Type)CollectionUtils.Get(change,name.ToLower()); if (clazz != null) { DefinitionObject childObject = null; try { childObject = (DefinitionObject)JavaRuntime.NewInstance(clazz); if (_source != null) { childObject.fileName = _source; } } catch (Exception e) { Loon.Utils.Debugging.Log.Exception(e); } if (this.isCurrentElementDefined) { childObject.InitWithParentObject(this.currentDefinitionObject); } childObject.DefinitionObjectDidInit(); if (childObject.parentDefinitionObject != null) { childObject.parentDefinitionObject.ChildDefinitionObjectDidInit(childObject); } this.curClass = clazz; this.currentDefinitionObject = childObject; this.isCurrentElementDefined = true; } else { this.isCurrentElementDefined = false; if (this.currentDefinitionObject != null) { this.currentDefinitionObject.UndefinedElementDidStart(name); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Diagnostics; using System.Diagnostics.Contracts; using System.IO; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; namespace System.Net.Http { public abstract class HttpContent : IDisposable { private HttpContentHeaders _headers; private MemoryStream _bufferedContent; private object _contentReadStream; // Stream or Task<Stream> private bool _disposed; private bool _canCalculateLength; internal const int MaxBufferSize = int.MaxValue; internal static readonly Encoding DefaultStringEncoding = Encoding.UTF8; private const int UTF8CodePage = 65001; private const int UTF8PreambleLength = 3; private const byte UTF8PreambleByte0 = 0xEF; private const byte UTF8PreambleByte1 = 0xBB; private const byte UTF8PreambleByte2 = 0xBF; private const int UTF8PreambleFirst2Bytes = 0xEFBB; #if !uap // UTF32 not supported on Phone private const int UTF32CodePage = 12000; private const int UTF32PreambleLength = 4; private const byte UTF32PreambleByte0 = 0xFF; private const byte UTF32PreambleByte1 = 0xFE; private const byte UTF32PreambleByte2 = 0x00; private const byte UTF32PreambleByte3 = 0x00; #endif private const int UTF32OrUnicodePreambleFirst2Bytes = 0xFFFE; private const int UnicodeCodePage = 1200; private const int UnicodePreambleLength = 2; private const byte UnicodePreambleByte0 = 0xFF; private const byte UnicodePreambleByte1 = 0xFE; private const int BigEndianUnicodeCodePage = 1201; private const int BigEndianUnicodePreambleLength = 2; private const byte BigEndianUnicodePreambleByte0 = 0xFE; private const byte BigEndianUnicodePreambleByte1 = 0xFF; private const int BigEndianUnicodePreambleFirst2Bytes = 0xFEFF; #if DEBUG static HttpContent() { // Ensure the encoding constants used in this class match the actual data from the Encoding class AssertEncodingConstants(Encoding.UTF8, UTF8CodePage, UTF8PreambleLength, UTF8PreambleFirst2Bytes, UTF8PreambleByte0, UTF8PreambleByte1, UTF8PreambleByte2); #if !uap // UTF32 not supported on Phone AssertEncodingConstants(Encoding.UTF32, UTF32CodePage, UTF32PreambleLength, UTF32OrUnicodePreambleFirst2Bytes, UTF32PreambleByte0, UTF32PreambleByte1, UTF32PreambleByte2, UTF32PreambleByte3); #endif AssertEncodingConstants(Encoding.Unicode, UnicodeCodePage, UnicodePreambleLength, UTF32OrUnicodePreambleFirst2Bytes, UnicodePreambleByte0, UnicodePreambleByte1); AssertEncodingConstants(Encoding.BigEndianUnicode, BigEndianUnicodeCodePage, BigEndianUnicodePreambleLength, BigEndianUnicodePreambleFirst2Bytes, BigEndianUnicodePreambleByte0, BigEndianUnicodePreambleByte1); } private static void AssertEncodingConstants(Encoding encoding, int codePage, int preambleLength, int first2Bytes, params byte[] preamble) { Debug.Assert(encoding != null); Debug.Assert(preamble != null); Debug.Assert(codePage == encoding.CodePage, "Encoding code page mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.CodePage): {1}", codePage, encoding.CodePage); byte[] actualPreamble = encoding.GetPreamble(); Debug.Assert(preambleLength == actualPreamble.Length, "Encoding preamble length mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble().Length): {1}", preambleLength, actualPreamble.Length); Debug.Assert(actualPreamble.Length >= 2); int actualFirst2Bytes = actualPreamble[0] << 8 | actualPreamble[1]; Debug.Assert(first2Bytes == actualFirst2Bytes, "Encoding preamble first 2 bytes mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual: {1}", first2Bytes, actualFirst2Bytes); Debug.Assert(preamble.Length == actualPreamble.Length, "Encoding preamble mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", BitConverter.ToString(preamble), BitConverter.ToString(actualPreamble)); for (int i = 0; i < preamble.Length; i++) { Debug.Assert(preamble[i] == actualPreamble[i], "Encoding preamble mismatch for encoding: " + encoding.EncodingName, "Expected (constant): {0}, Actual (Encoding.GetPreamble()): {1}", BitConverter.ToString(preamble), BitConverter.ToString(actualPreamble)); } } #endif public HttpContentHeaders Headers { get { if (_headers == null) { _headers = new HttpContentHeaders(this); } return _headers; } } private bool IsBuffered { get { return _bufferedContent != null; } } internal void SetBuffer(byte[] buffer, int offset, int count) { _bufferedContent = new MemoryStream(buffer, offset, count, writable: false, publiclyVisible: true); } internal bool TryGetBuffer(out ArraySegment<byte> buffer) { return _bufferedContent != null && _bufferedContent.TryGetBuffer(out buffer); } protected HttpContent() { // Log to get an ID for the current content. This ID is used when the content gets associated to a message. if (NetEventSource.IsEnabled) NetEventSource.Enter(this); // We start with the assumption that we can calculate the content length. _canCalculateLength = true; if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } public Task<string> ReadAsStringAsync() { CheckDisposed(); return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => s.ReadBufferedContentAsString()); } private string ReadBufferedContentAsString() { Debug.Assert(IsBuffered); if (_bufferedContent.Length == 0) { return string.Empty; } ArraySegment<byte> buffer; if (!TryGetBuffer(out buffer)) { buffer = new ArraySegment<byte>(_bufferedContent.ToArray()); } return ReadBufferAsString(buffer, Headers); } internal static string ReadBufferAsString(ArraySegment<byte> buffer, HttpContentHeaders headers) { // We don't validate the Content-Encoding header: If the content was encoded, it's the caller's // responsibility to make sure to only call ReadAsString() on already decoded content. E.g. if the // Content-Encoding is 'gzip' the user should set HttpClientHandler.AutomaticDecompression to get a // decoded response stream. Encoding encoding = null; int bomLength = -1; // If we do have encoding information in the 'Content-Type' header, use that information to convert // the content to a string. if ((headers.ContentType != null) && (headers.ContentType.CharSet != null)) { try { encoding = Encoding.GetEncoding(headers.ContentType.CharSet); // Byte-order-mark (BOM) characters may be present even if a charset was specified. bomLength = GetPreambleLength(buffer, encoding); } catch (ArgumentException e) { throw new InvalidOperationException(SR.net_http_content_invalid_charset, e); } } // If no content encoding is listed in the ContentType HTTP header, or no Content-Type header present, // then check for a BOM in the data to figure out the encoding. if (encoding == null) { if (!TryDetectEncoding(buffer, out encoding, out bomLength)) { // Use the default encoding (UTF8) if we couldn't detect one. encoding = DefaultStringEncoding; // We already checked to see if the data had a UTF8 BOM in TryDetectEncoding // and DefaultStringEncoding is UTF8, so the bomLength is 0. bomLength = 0; } } // Drop the BOM when decoding the data. return encoding.GetString(buffer.Array, buffer.Offset + bomLength, buffer.Count - bomLength); } public Task<byte[]> ReadAsByteArrayAsync() { CheckDisposed(); return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => s.ReadBufferedContentAsByteArray()); } internal byte[] ReadBufferedContentAsByteArray() { // The returned array is exposed out of the library, so use ToArray rather // than TryGetBuffer in order to make a copy. return _bufferedContent.ToArray(); } public Task<Stream> ReadAsStreamAsync() { CheckDisposed(); // _contentReadStream will be either null (nothing yet initialized), a Stream (it was previously // initialized in TryReadAsStream), or a Task<Stream> (it was previously initialized here // in ReadAsStreamAsync). if (_contentReadStream == null) // don't yet have a Stream { Task<Stream> t = TryGetBuffer(out ArraySegment<byte> buffer) ? Task.FromResult<Stream>(new MemoryStream(buffer.Array, buffer.Offset, buffer.Count, writable: false)) : CreateContentReadStreamAsync(); _contentReadStream = t; return t; } else if (_contentReadStream is Task<Stream> t) // have a Task<Stream> { return t; } else { Debug.Assert(_contentReadStream is Stream, $"Expected a Stream, got ${_contentReadStream}"); Task<Stream> ts = Task.FromResult((Stream)_contentReadStream); _contentReadStream = ts; return ts; } } internal Stream TryReadAsStream() { CheckDisposed(); // _contentReadStream will be either null (nothing yet initialized), a Stream (it was previously // initialized here in TryReadAsStream), or a Task<Stream> (it was previously initialized // in ReadAsStreamAsync). if (_contentReadStream == null) // don't yet have a Stream { Stream s = TryGetBuffer(out ArraySegment<byte> buffer) ? new MemoryStream(buffer.Array, buffer.Offset, buffer.Count, writable: false) : TryCreateContentReadStream(); _contentReadStream = s; return s; } else if (_contentReadStream is Stream s) // have a Stream { return s; } else // have a Task<Stream> { Debug.Assert(_contentReadStream is Task<Stream>, $"Expected a Task<Stream>, got ${_contentReadStream}"); Task<Stream> t = (Task<Stream>)_contentReadStream; return t.Status == TaskStatus.RanToCompletion ? t.Result : null; } } protected abstract Task SerializeToStreamAsync(Stream stream, TransportContext context); public Task CopyToAsync(Stream stream, TransportContext context) { CheckDisposed(); if (stream == null) { throw new ArgumentNullException(nameof(stream)); } try { Task task = null; ArraySegment<byte> buffer; if (TryGetBuffer(out buffer)) { task = stream.WriteAsync(buffer.Array, buffer.Offset, buffer.Count); } else { task = SerializeToStreamAsync(stream, context); CheckTaskNotNull(task); } return CopyToAsyncCore(task); } catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e)) { return Task.FromException(GetStreamCopyException(e)); } } private static async Task CopyToAsyncCore(Task copyTask) { try { await copyTask.ConfigureAwait(false); } catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e)) { throw GetStreamCopyException(e); } } public Task CopyToAsync(Stream stream) { return CopyToAsync(stream, null); } public Task LoadIntoBufferAsync() { return LoadIntoBufferAsync(MaxBufferSize); } // No "CancellationToken" parameter needed since canceling the CTS will close the connection, resulting // in an exception being thrown while we're buffering. // If buffering is used without a connection, it is supposed to be fast, thus no cancellation required. public Task LoadIntoBufferAsync(long maxBufferSize) { CheckDisposed(); if (maxBufferSize > HttpContent.MaxBufferSize) { // This should only be hit when called directly; HttpClient/HttpClientHandler // will not exceed this limit. throw new ArgumentOutOfRangeException(nameof(maxBufferSize), maxBufferSize, string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_limit, HttpContent.MaxBufferSize)); } if (IsBuffered) { // If we already buffered the content, just return a completed task. return Task.CompletedTask; } Exception error = null; MemoryStream tempBuffer = CreateMemoryStream(maxBufferSize, out error); if (tempBuffer == null) { // We don't throw in LoadIntoBufferAsync(): return a faulted task. return Task.FromException(error); } try { Task task = SerializeToStreamAsync(tempBuffer, null); CheckTaskNotNull(task); return LoadIntoBufferAsyncCore(task, tempBuffer); } catch (Exception e) when (StreamCopyExceptionNeedsWrapping(e)) { return Task.FromException(GetStreamCopyException(e)); } // other synchronous exceptions from SerializeToStreamAsync/CheckTaskNotNull will propagate } private async Task LoadIntoBufferAsyncCore(Task serializeToStreamTask, MemoryStream tempBuffer) { try { await serializeToStreamTask.ConfigureAwait(false); } catch (Exception e) { tempBuffer.Dispose(); // Cleanup partially filled stream. Exception we = GetStreamCopyException(e); if (we != e) throw we; throw; } try { tempBuffer.Seek(0, SeekOrigin.Begin); // Rewind after writing data. _bufferedContent = tempBuffer; } catch (Exception e) { if (NetEventSource.IsEnabled) NetEventSource.Error(this, e); throw; } } protected virtual Task<Stream> CreateContentReadStreamAsync() { // By default just buffer the content to a memory stream. Derived classes can override this behavior // if there is a better way to retrieve the content as stream (e.g. byte array/string use a more efficient // way, like wrapping a read-only MemoryStream around the bytes/string) return WaitAndReturnAsync(LoadIntoBufferAsync(), this, s => (Stream)s._bufferedContent); } // As an optimization for internal consumers of HttpContent (e.g. HttpClient.GetStreamAsync), and for // HttpContent-derived implementations that override CreateContentReadStreamAsync in a way that always // or frequently returns synchronously-completed tasks, we can avoid the task allocation by enabling // callers to try to get the Stream first synchronously. internal virtual Stream TryCreateContentReadStream() => null; // Derived types return true if they're able to compute the length. It's OK if derived types return false to // indicate that they're not able to compute the length. The transport channel needs to decide what to do in // that case (send chunked, buffer first, etc.). protected internal abstract bool TryComputeLength(out long length); internal long? GetComputedOrBufferLength() { CheckDisposed(); if (IsBuffered) { return _bufferedContent.Length; } // If we already tried to calculate the length, but the derived class returned 'false', then don't try // again; just return null. if (_canCalculateLength) { long length = 0; if (TryComputeLength(out length)) { return length; } // Set flag to make sure next time we don't try to compute the length, since we know that we're unable // to do so. _canCalculateLength = false; } return null; } private MemoryStream CreateMemoryStream(long maxBufferSize, out Exception error) { Contract.Ensures((Contract.Result<MemoryStream>() != null) || (Contract.ValueAtReturn<Exception>(out error) != null)); error = null; // If we have a Content-Length allocate the right amount of buffer up-front. Also check whether the // content length exceeds the max. buffer size. long? contentLength = Headers.ContentLength; if (contentLength != null) { Debug.Assert(contentLength >= 0); if (contentLength > maxBufferSize) { error = new HttpRequestException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_buffersize_exceeded, maxBufferSize)); return null; } // We can safely cast contentLength to (int) since we just checked that it is <= maxBufferSize. return new LimitMemoryStream((int)maxBufferSize, (int)contentLength); } // We couldn't determine the length of the buffer. Create a memory stream with an empty buffer. return new LimitMemoryStream((int)maxBufferSize, 0); } #region IDisposable Members protected virtual void Dispose(bool disposing) { if (disposing && !_disposed) { _disposed = true; if (_contentReadStream != null) { Stream s = _contentReadStream as Stream ?? (_contentReadStream is Task<Stream> t && t.Status == TaskStatus.RanToCompletion ? t.Result : null); s?.Dispose(); _contentReadStream = null; } if (IsBuffered) { _bufferedContent.Dispose(); } } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion #region Helpers private void CheckDisposed() { if (_disposed) { throw new ObjectDisposedException(this.GetType().ToString()); } } private void CheckTaskNotNull(Task task) { if (task == null) { var e = new InvalidOperationException(SR.net_http_content_no_task_returned); if (NetEventSource.IsEnabled) NetEventSource.Error(this, e); throw e; } } private static bool StreamCopyExceptionNeedsWrapping(Exception e) => e is IOException || e is ObjectDisposedException; private static Exception GetStreamCopyException(Exception originalException) { // HttpContent derived types should throw HttpRequestExceptions if there is an error. However, since the stream // provided by CopyToAsync() can also throw, we wrap such exceptions in HttpRequestException. This way custom content // types don't have to worry about it. The goal is that users of HttpContent don't have to catch multiple // exceptions (depending on the underlying transport), but just HttpRequestExceptions // Custom stream should throw either IOException or HttpRequestException. // We don't want to wrap other exceptions thrown by Stream (e.g. InvalidOperationException), since we // don't want to hide such "usage error" exceptions in HttpRequestException. // ObjectDisposedException is also wrapped, since aborting HWR after a request is complete will result in // the response stream being closed. return StreamCopyExceptionNeedsWrapping(originalException) ? new HttpRequestException(SR.net_http_content_stream_copy_error, originalException) : originalException; } private static int GetPreambleLength(ArraySegment<byte> buffer, Encoding encoding) { byte[] data = buffer.Array; int offset = buffer.Offset; int dataLength = buffer.Count; Debug.Assert(data != null); Debug.Assert(encoding != null); switch (encoding.CodePage) { case UTF8CodePage: return (dataLength >= UTF8PreambleLength && data[offset + 0] == UTF8PreambleByte0 && data[offset + 1] == UTF8PreambleByte1 && data[offset + 2] == UTF8PreambleByte2) ? UTF8PreambleLength : 0; #if !uap // UTF32 not supported on Phone case UTF32CodePage: return (dataLength >= UTF32PreambleLength && data[offset + 0] == UTF32PreambleByte0 && data[offset + 1] == UTF32PreambleByte1 && data[offset + 2] == UTF32PreambleByte2 && data[offset + 3] == UTF32PreambleByte3) ? UTF32PreambleLength : 0; #endif case UnicodeCodePage: return (dataLength >= UnicodePreambleLength && data[offset + 0] == UnicodePreambleByte0 && data[offset + 1] == UnicodePreambleByte1) ? UnicodePreambleLength : 0; case BigEndianUnicodeCodePage: return (dataLength >= BigEndianUnicodePreambleLength && data[offset + 0] == BigEndianUnicodePreambleByte0 && data[offset + 1] == BigEndianUnicodePreambleByte1) ? BigEndianUnicodePreambleLength : 0; default: byte[] preamble = encoding.GetPreamble(); return BufferHasPrefix(buffer, preamble) ? preamble.Length : 0; } } private static bool TryDetectEncoding(ArraySegment<byte> buffer, out Encoding encoding, out int preambleLength) { byte[] data = buffer.Array; int offset = buffer.Offset; int dataLength = buffer.Count; Debug.Assert(data != null); if (dataLength >= 2) { int first2Bytes = data[offset + 0] << 8 | data[offset + 1]; switch (first2Bytes) { case UTF8PreambleFirst2Bytes: if (dataLength >= UTF8PreambleLength && data[offset + 2] == UTF8PreambleByte2) { encoding = Encoding.UTF8; preambleLength = UTF8PreambleLength; return true; } break; case UTF32OrUnicodePreambleFirst2Bytes: #if !uap // UTF32 not supported on Phone if (dataLength >= UTF32PreambleLength && data[offset + 2] == UTF32PreambleByte2 && data[offset + 3] == UTF32PreambleByte3) { encoding = Encoding.UTF32; preambleLength = UTF32PreambleLength; } else #endif { encoding = Encoding.Unicode; preambleLength = UnicodePreambleLength; } return true; case BigEndianUnicodePreambleFirst2Bytes: encoding = Encoding.BigEndianUnicode; preambleLength = BigEndianUnicodePreambleLength; return true; } } encoding = null; preambleLength = 0; return false; } private static bool BufferHasPrefix(ArraySegment<byte> buffer, byte[] prefix) { byte[] byteArray = buffer.Array; if (prefix == null || byteArray == null || prefix.Length > buffer.Count || prefix.Length == 0) return false; for (int i = 0, j = buffer.Offset; i < prefix.Length; i++, j++) { if (prefix[i] != byteArray[j]) return false; } return true; } #endregion Helpers private static async Task<TResult> WaitAndReturnAsync<TState, TResult>(Task waitTask, TState state, Func<TState, TResult> returnFunc) { await waitTask.ConfigureAwait(false); return returnFunc(state); } private static Exception CreateOverCapacityException(int maxBufferSize) { return new HttpRequestException(SR.Format(SR.net_http_content_buffersize_exceeded, maxBufferSize)); } internal sealed class LimitMemoryStream : MemoryStream { private readonly int _maxSize; public LimitMemoryStream(int maxSize, int capacity) : base(capacity) { Debug.Assert(capacity <= maxSize); _maxSize = maxSize; } public int MaxSize => _maxSize; public byte[] GetSizedBuffer() { ArraySegment<byte> buffer; return TryGetBuffer(out buffer) && buffer.Offset == 0 && buffer.Count == buffer.Array.Length ? buffer.Array : ToArray(); } public override void Write(byte[] buffer, int offset, int count) { CheckSize(count); base.Write(buffer, offset, count); } public override void WriteByte(byte value) { CheckSize(1); base.WriteByte(value); } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { CheckSize(count); return base.WriteAsync(buffer, offset, count, cancellationToken); } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) { CheckSize(count); return base.BeginWrite(buffer, offset, count, callback, state); } public override void EndWrite(IAsyncResult asyncResult) { base.EndWrite(asyncResult); } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { ArraySegment<byte> buffer; if (TryGetBuffer(out buffer)) { StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); long pos = Position; long length = Length; Position = length; long bytesToWrite = length - pos; return destination.WriteAsync(buffer.Array, (int)(buffer.Offset + pos), (int)bytesToWrite, cancellationToken); } return base.CopyToAsync(destination, bufferSize, cancellationToken); } private void CheckSize(int countToAdd) { if (_maxSize - Length < countToAdd) { throw CreateOverCapacityException(_maxSize); } } } internal sealed class LimitArrayPoolWriteStream : Stream { private const int MaxByteArrayLength = 0x7FFFFFC7; private const int InitialLength = 256; private readonly int _maxBufferSize; private byte[] _buffer; private int _length; public LimitArrayPoolWriteStream(int maxBufferSize) : this(maxBufferSize, InitialLength) { } public LimitArrayPoolWriteStream(int maxBufferSize, long capacity) { if (capacity < InitialLength) { capacity = InitialLength; } else if (capacity > maxBufferSize) { throw CreateOverCapacityException(maxBufferSize); } _maxBufferSize = maxBufferSize; _buffer = ArrayPool<byte>.Shared.Rent((int)capacity); } protected override void Dispose(bool disposing) { Debug.Assert(_buffer != null); ArrayPool<byte>.Shared.Return(_buffer); _buffer = null; base.Dispose(disposing); } public ArraySegment<byte> GetBuffer() => new ArraySegment<byte>(_buffer, 0, _length); public byte[] ToArray() { var arr = new byte[_length]; Buffer.BlockCopy(_buffer, 0, arr, 0, _length); return arr; } private void EnsureCapacity(int value) { if ((uint)value > (uint)_maxBufferSize) // value cast handles overflow to negative as well { throw CreateOverCapacityException(_maxBufferSize); } else if (value > _buffer.Length) { Grow(value); } } private void Grow(int value) { Debug.Assert(value > _buffer.Length); // Extract the current buffer to be replaced. byte[] currentBuffer = _buffer; _buffer = null; // Determine the capacity to request for the new buffer. It should be // at least twice as long as the current one, if not more if the requested // value is more than that. If the new value would put it longer than the max // allowed byte array, than shrink to that (and if the required length is actually // longer than that, we'll let the runtime throw). uint twiceLength = 2 * (uint)currentBuffer.Length; int newCapacity = twiceLength > MaxByteArrayLength ? (value > MaxByteArrayLength ? value : MaxByteArrayLength) : Math.Max(value, (int)twiceLength); // Get a new buffer, copy the current one to it, return the current one, and // set the new buffer as current. byte[] newBuffer = ArrayPool<byte>.Shared.Rent(newCapacity); Buffer.BlockCopy(currentBuffer, 0, newBuffer, 0, _length); ArrayPool<byte>.Shared.Return(currentBuffer); _buffer = newBuffer; } public override void Write(byte[] buffer, int offset, int count) { Debug.Assert(buffer != null); Debug.Assert(offset >= 0); Debug.Assert(count >= 0); EnsureCapacity(_length + count); Buffer.BlockCopy(buffer, offset, _buffer, _length, count); _length += count; } public override void Write(ReadOnlySpan<byte> source) { EnsureCapacity(_length + source.Length); source.CopyTo(new Span<byte>(_buffer, _length, source.Length)); _length += source.Length; } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { Write(buffer, offset, count); return Task.CompletedTask; } public override Task WriteAsync(ReadOnlyMemory<byte> source, CancellationToken cancellationToken = default) { Write(source.Span); return Task.CompletedTask; } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) => TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), asyncCallback, asyncState); public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public override void WriteByte(byte value) { int newLength = _length + 1; EnsureCapacity(newLength); _buffer[_length] = value; _length = newLength; } public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) => Task.CompletedTask; public override long Length => _length; public override bool CanWrite => true; public override bool CanRead => false; public override bool CanSeek => false; public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public override int Read(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } } } }
using System.Collections.Generic; using System.Text; using System.Linq; using UnityEngine; using UnityEngine.UI; using UnityEditor.AnimatedValues; namespace UnityEditor.UI { [CustomEditor(typeof(Selectable), true)] public class SelectableEditor : Editor { SerializedProperty m_Script; SerializedProperty m_InteractableProperty; SerializedProperty m_TargetGraphicProperty; SerializedProperty m_TransitionProperty; SerializedProperty m_ColorBlockProperty; SerializedProperty m_SpriteStateProperty; SerializedProperty m_AnimTriggerProperty; SerializedProperty m_NavigationProperty; GUIContent m_VisualizeNavigation = new GUIContent("Visualize", "Show navigation flows between selectable UI elements."); AnimBool m_ShowColorTint = new AnimBool(); AnimBool m_ShowSpriteTrasition = new AnimBool(); AnimBool m_ShowAnimTransition = new AnimBool(); private static List<SelectableEditor> s_Editors = new List<SelectableEditor>(); private static bool s_ShowNavigation = false; private static string s_ShowNavigationKey = "SelectableEditor.ShowNavigation"; // Whenever adding new SerializedProperties to the Selectable and SelectableEditor // Also update this guy in OnEnable. This makes the inherited classes from Selectable not require a CustomEditor. private string[] m_PropertyPathToExcludeForChildClasses; protected virtual void OnEnable() { m_Script = serializedObject.FindProperty("m_Script"); m_InteractableProperty = serializedObject.FindProperty("m_Interactable"); m_TargetGraphicProperty = serializedObject.FindProperty("m_TargetGraphic"); m_TransitionProperty = serializedObject.FindProperty("m_Transition"); m_ColorBlockProperty = serializedObject.FindProperty("m_Colors"); m_SpriteStateProperty = serializedObject.FindProperty("m_SpriteState"); m_AnimTriggerProperty = serializedObject.FindProperty("m_AnimationTriggers"); m_NavigationProperty = serializedObject.FindProperty("m_Navigation"); m_PropertyPathToExcludeForChildClasses = new[] { m_Script.propertyPath, m_NavigationProperty.propertyPath, m_TransitionProperty.propertyPath, m_ColorBlockProperty.propertyPath, m_SpriteStateProperty.propertyPath, m_AnimTriggerProperty.propertyPath, m_InteractableProperty.propertyPath, m_TargetGraphicProperty.propertyPath, }; var trans = GetTransition(m_TransitionProperty); m_ShowColorTint.value = (trans == Selectable.Transition.ColorTint); m_ShowSpriteTrasition.value = (trans == Selectable.Transition.SpriteSwap); m_ShowAnimTransition.value = (trans == Selectable.Transition.Animation); m_ShowColorTint.valueChanged.AddListener(Repaint); m_ShowSpriteTrasition.valueChanged.AddListener(Repaint); s_Editors.Add(this); RegisterStaticOnSceneGUI(); s_ShowNavigation = EditorPrefs.GetBool(s_ShowNavigationKey); } protected virtual void OnDisable() { m_ShowColorTint.valueChanged.RemoveListener(Repaint); m_ShowSpriteTrasition.valueChanged.RemoveListener(Repaint); s_Editors.Remove(this); RegisterStaticOnSceneGUI(); } private void RegisterStaticOnSceneGUI() { SceneView.onSceneGUIDelegate -= StaticOnSceneGUI; if (s_Editors.Count > 0) SceneView.onSceneGUIDelegate += StaticOnSceneGUI; } static Selectable.Transition GetTransition(SerializedProperty transition) { return (Selectable.Transition)transition.enumValueIndex; } public override void OnInspectorGUI() { serializedObject.Update(); if (!IsDerivedSelectableEditor()) EditorGUILayout.PropertyField(m_Script); EditorGUILayout.PropertyField(m_InteractableProperty); var trans = GetTransition(m_TransitionProperty); var graphic = m_TargetGraphicProperty.objectReferenceValue as Graphic; if (graphic == null) graphic = (target as Selectable).GetComponent<Graphic>(); var animator = (target as Selectable).GetComponent<Animator>(); m_ShowColorTint.target = (!m_TransitionProperty.hasMultipleDifferentValues && trans == Button.Transition.ColorTint); m_ShowSpriteTrasition.target = (!m_TransitionProperty.hasMultipleDifferentValues && trans == Button.Transition.SpriteSwap); m_ShowAnimTransition.target = (!m_TransitionProperty.hasMultipleDifferentValues && trans == Button.Transition.Animation); EditorGUILayout.PropertyField(m_TransitionProperty); ++EditorGUI.indentLevel; { if (trans == Selectable.Transition.ColorTint || trans == Selectable.Transition.SpriteSwap) { EditorGUILayout.PropertyField(m_TargetGraphicProperty); } switch (trans) { case Selectable.Transition.ColorTint: if (graphic == null) EditorGUILayout.HelpBox("You must have a Graphic target in order to use a color transition.", MessageType.Warning); break; case Selectable.Transition.SpriteSwap: if (graphic as Image == null) EditorGUILayout.HelpBox("You must have a Image target in order to use a sprite swap transition.", MessageType.Warning); break; } if (EditorGUILayout.BeginFadeGroup(m_ShowColorTint.faded)) { EditorGUILayout.PropertyField(m_ColorBlockProperty); } EditorGUILayout.EndFadeGroup(); if (EditorGUILayout.BeginFadeGroup(m_ShowSpriteTrasition.faded)) { EditorGUILayout.PropertyField(m_SpriteStateProperty); } EditorGUILayout.EndFadeGroup(); if (EditorGUILayout.BeginFadeGroup(m_ShowAnimTransition.faded)) { EditorGUILayout.PropertyField(m_AnimTriggerProperty); if (animator == null || animator.runtimeAnimatorController == null) { Rect buttonRect = EditorGUILayout.GetControlRect(); buttonRect.xMin += EditorGUIUtility.labelWidth; if (GUI.Button(buttonRect, "Auto Generate Animation", EditorStyles.miniButton)) { var controller = GenerateSelectableAnimatorContoller((target as Selectable).animationTriggers, target as Selectable); if (controller != null) { if (animator == null) animator = (target as Selectable).gameObject.AddComponent<Animator>(); Animations.AnimatorController.SetAnimatorController(animator, controller); } } } } EditorGUILayout.EndFadeGroup(); } --EditorGUI.indentLevel; EditorGUILayout.Space(); EditorGUILayout.PropertyField(m_NavigationProperty); EditorGUI.BeginChangeCheck(); Rect toggleRect = EditorGUILayout.GetControlRect(); toggleRect.xMin += EditorGUIUtility.labelWidth; s_ShowNavigation = GUI.Toggle(toggleRect, s_ShowNavigation, m_VisualizeNavigation, EditorStyles.miniButton); if (EditorGUI.EndChangeCheck()) { EditorPrefs.SetBool(s_ShowNavigationKey, s_ShowNavigation); SceneView.RepaintAll(); } // We do this here to avoid requiring the user to also write a Editor for their Selectable-derived classes. // This way if we are on a derived class we dont draw anything else, otherwise draw the remaining properties. ChildClassPropertiesGUI(); serializedObject.ApplyModifiedProperties(); } // Draw the extra SerializedProperties of the child class. // We need to make sure that m_PropertyPathToExcludeForChildClasses has all the Selectable properties and in the correct order. // TODO: find a nicer way of doing this. (creating a InheritedEditor class that automagically does this) private void ChildClassPropertiesGUI() { if (IsDerivedSelectableEditor()) return; DrawPropertiesExcluding(serializedObject, m_PropertyPathToExcludeForChildClasses); } private bool IsDerivedSelectableEditor() { return GetType() != typeof(SelectableEditor); } private static Animations.AnimatorController GenerateSelectableAnimatorContoller(AnimationTriggers animationTriggers, Selectable target) { if (target == null) return null; // Where should we create the controller? var path = GetSaveControllerPath(target); if (string.IsNullOrEmpty(path)) return null; // figure out clip names var normalName = string.IsNullOrEmpty(animationTriggers.normalTrigger) ? "Normal" : animationTriggers.normalTrigger; var highlightedName = string.IsNullOrEmpty(animationTriggers.highlightedTrigger) ? "Highlighted" : animationTriggers.highlightedTrigger; var pressedName = string.IsNullOrEmpty(animationTriggers.pressedTrigger) ? "Pressed" : animationTriggers.pressedTrigger; var disabledName = string.IsNullOrEmpty(animationTriggers.disabledTrigger) ? "Disabled" : animationTriggers.disabledTrigger; // Create controller and hook up transitions. var controller = Animations.AnimatorController.CreateAnimatorControllerAtPath(path); GenerateTriggerableTransition(normalName, controller); GenerateTriggerableTransition(highlightedName, controller); GenerateTriggerableTransition(pressedName, controller); GenerateTriggerableTransition(disabledName, controller); AssetDatabase.ImportAsset(path); return controller; } private static string GetSaveControllerPath(Selectable target) { var defaultName = target.gameObject.name; var message = string.Format("Create a new animator for the game object '{0}':", defaultName); return EditorUtility.SaveFilePanelInProject("New Animation Contoller", defaultName, "controller", message); } private static void SetUpCurves(AnimationClip highlightedClip, AnimationClip pressedClip, string animationPath) { string[] channels = { "m_LocalScale.x", "m_LocalScale.y", "m_LocalScale.z" }; var highlightedKeys = new[] { new Keyframe(0f, 1f), new Keyframe(0.5f, 1.1f), new Keyframe(1f, 1f) }; var highlightedCurve = new AnimationCurve(highlightedKeys); foreach (var channel in channels) AnimationUtility.SetEditorCurve(highlightedClip, EditorCurveBinding.FloatCurve(animationPath, typeof(Transform), channel), highlightedCurve); var pressedKeys = new[] { new Keyframe(0f, 1.15f) }; var pressedCurve = new AnimationCurve(pressedKeys); foreach (var channel in channels) AnimationUtility.SetEditorCurve(pressedClip, EditorCurveBinding.FloatCurve(animationPath, typeof(Transform), channel), pressedCurve); } private static string BuildAnimationPath(Selectable target) { // if no target don't hook up any curves. var highlight = target.targetGraphic; if (highlight == null) return string.Empty; var startGo = highlight.gameObject; var toFindGo = target.gameObject; var pathComponents = new Stack<string>(); while (toFindGo != startGo) { pathComponents.Push(startGo.name); // didn't exist in hierarchy! if (startGo.transform.parent == null) return string.Empty; startGo = startGo.transform.parent.gameObject; } // calculate path var animPath = new StringBuilder(); if (pathComponents.Count > 0) animPath.Append(pathComponents.Pop()); while (pathComponents.Count > 0) animPath.Append("/").Append(pathComponents.Pop()); return animPath.ToString(); } private static AnimationClip GenerateTriggerableTransition(string name, Animations.AnimatorController controller) { // Create the clip var clip = Animations.AnimatorController.AllocateAnimatorClip(name); AssetDatabase.AddObjectToAsset(clip, controller); // Create a state in the animatior controller for this clip var state = controller.AddMotion(clip); // Add a transition property controller.AddParameter(name, AnimatorControllerParameterType.Trigger); // Add an any state transition var stateMachine = controller.layers[0].stateMachine; var transition = stateMachine.AddAnyStateTransition(state); transition.AddCondition(Animations.AnimatorConditionMode.If, 0, name); return clip; } private static void StaticOnSceneGUI(SceneView view) { if (!s_ShowNavigation) return; for (int i = 0; i < Selectable.allSelectables.Count; i++) { DrawNavigationForSelectable(Selectable.allSelectables[i]); } } private static void DrawNavigationForSelectable(Selectable sel) { if (sel == null) return; Transform transform = sel.transform; bool active = Selection.transforms.Any(e => e == transform); Handles.color = new Color(1.0f, 0.9f, 0.1f, active ? 1.0f : 0.4f); DrawNavigationArrow(-Vector2.right, sel, sel.FindSelectableOnLeft()); DrawNavigationArrow(Vector2.right, sel, sel.FindSelectableOnRight()); DrawNavigationArrow(Vector2.up, sel, sel.FindSelectableOnUp()); DrawNavigationArrow(-Vector2.up, sel, sel.FindSelectableOnDown()); } const float kArrowThickness = 2.5f; const float kArrowHeadSize = 1.2f; private static void DrawNavigationArrow(Vector2 direction, Selectable fromObj, Selectable toObj) { if (fromObj == null || toObj == null) return; Transform fromTransform = fromObj.transform; Transform toTransform = toObj.transform; Vector2 sideDir = new Vector2(direction.y, -direction.x); Vector3 fromPoint = fromTransform.TransformPoint(GetPointOnRectEdge(fromTransform as RectTransform, direction)); Vector3 toPoint = toTransform.TransformPoint(GetPointOnRectEdge(toTransform as RectTransform, -direction)); float fromSize = HandleUtility.GetHandleSize(fromPoint) * 0.05f; float toSize = HandleUtility.GetHandleSize(toPoint) * 0.05f; fromPoint += fromTransform.TransformDirection(sideDir) * fromSize; toPoint += toTransform.TransformDirection(sideDir) * toSize; float length = Vector3.Distance(fromPoint, toPoint); Vector3 fromTangent = fromTransform.rotation * direction * length * 0.3f; Vector3 toTangent = toTransform.rotation * -direction * length * 0.3f; Handles.DrawBezier(fromPoint, toPoint, fromPoint + fromTangent, toPoint + toTangent, Handles.color, null, kArrowThickness); Handles.DrawAAPolyLine(kArrowThickness, toPoint, toPoint + toTransform.rotation * (-direction - sideDir) * toSize * kArrowHeadSize); Handles.DrawAAPolyLine(kArrowThickness, toPoint, toPoint + toTransform.rotation * (-direction + sideDir) * toSize * kArrowHeadSize); } private static Vector3 GetPointOnRectEdge(RectTransform rect, Vector2 dir) { if (rect == null) return Vector3.zero; if (dir != Vector2.zero) dir /= Mathf.Max(Mathf.Abs(dir.x), Mathf.Abs(dir.y)); dir = rect.rect.center + Vector2.Scale(rect.rect.size, dir * 0.5f); return dir; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using System.IO; using DeadCode.WME.Global; using DeadCode.WME.ScriptParser; using DeadCode.WME.DocMaker; namespace Integrator { public partial class ModSciTE : IntegratorModule { ////////////////////////////////////////////////////////////////////////// public ModSciTE() { InitializeComponent(); } ////////////////////////////////////////////////////////////////////////// private void OnDownloadLink(object sender, LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start("http://www.scintilla.org/"); } ////////////////////////////////////////////////////////////////////////// private void OnAssociate(object sender, EventArgs e) { string Exe; Exe = Path.Combine(WmeUtils.ToolsPath, "scite\\scite.exe"); if (!File.Exists(Exe)) { MessageBox.Show("The 'SciTE.exe' file was not found in the specified location. Please reinstall WME.", ParentForm.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } MakeAssocitations(Exe); } string FileHeader = "# this file is automatically generated by WME Integrator\n# do not modify; your changes will be overwritten\n"; ////////////////////////////////////////////////////////////////////////// private void OnIntegrate(object sender, EventArgs e) { string ScitePath = Path.Combine(WmeUtils.ToolsPath, "scite"); if (!Directory.Exists(ScitePath)) Directory.CreateDirectory(ScitePath); string[] Extensions = ParentForm.GetExtensions(); string Extensions2 = ""; foreach (string Ext in Extensions) { if (Extensions2 != "") Extensions2 += ";"; Extensions2 += "*." + Ext; } // generate syntax file try { // read XML docs ScriptInfo Info = new ScriptInfo(); Info.ReadXml(WmeUtils.XmlDocsPath); string KwdFile = Path.Combine(ScitePath, "wme_kwd.properties"); using (StreamWriter sw = new StreamWriter(KwdFile, false, Encoding.Default)) { sw.WriteLine(FileHeader); sw.WriteLine("file.patterns.script=" + Extensions2); sw.WriteLine("filter.script=WME Scripts|$(file.patterns.script)|"); sw.WriteLine(); WordHolder wh; // keywords sw.WriteLine("keywords.$(file.patterns.script)=\\"); wh = new WordHolder(); foreach (string Keyword in ScriptTokenizer.Keywords) { wh.AddWord(Keyword); } sw.WriteLine(wh.GetWords()); // methods sw.WriteLine("keywords2.$(file.patterns.script)=\\"); wh = new WordHolder(); foreach (ScriptObject Obj in Info.Objects) { foreach (ScriptMethod Method in Obj.Methods) { foreach (string Header in Method.Headers) { int Brace = Header.IndexOf("("); if (Brace >= 0) { wh.AddWord(Header.Substring(0, Brace).Trim()); } } } } sw.WriteLine(wh.GetWords()); // attributes sw.WriteLine("keywords4.$(file.patterns.script)=\\"); wh = new WordHolder(); foreach (ScriptObject Obj in Info.Objects) { foreach (ScriptAttribute Attr in Obj.Attributes) { if (Attr.Name.StartsWith("[")) continue; wh.AddWord(Attr.Name); } } sw.WriteLine(wh.GetWords()); } // tools string ToolsFile = Path.Combine(ScitePath, "wme_tools.properties"); using (StreamWriter sw = new StreamWriter(ToolsFile, false, Encoding.Default)) { sw.WriteLine(FileHeader); sw.WriteLine("command.compile.$(file.patterns.script)=\"" + WmeUtils.CompilerPath + "\" -script \"$(FilePath)\" -format scite"); sw.WriteLine("command.help.$(file.patterns.script)=reference!" + Path.Combine(WmeUtils.ToolsPath, "wme.chm")); sw.WriteLine("command.help.subsystem.$(file.patterns.script)=4"); sw.WriteLine("api.$(file.patterns.script)=" + Path.Combine(WmeUtils.ToolsPath, "SciTE\\wme.api")); } // api string ApiFile = Path.Combine(ScitePath, "wme.api"); using (StreamWriter sw = new StreamWriter(ApiFile, false, Encoding.Default)) { WordHolder wh; wh = new WordHolder(); foreach (ScriptObject Obj in Info.Objects) { foreach (ScriptMethod Method in Obj.Methods) { foreach (string Header in Method.Headers) { wh.AddWord(Header + Method.Desc); } } } foreach (ScriptObject Obj in Info.Objects) { foreach (ScriptAttribute Attr in Obj.Attributes) { if (Attr.Name.StartsWith("[")) continue; wh.AddWord(Attr.Name); } } sw.WriteLine(wh.GetWordsApi()); } } catch { } } ////////////////////////////////////////////////////////////////////////// private class WordHolder { List<string> Words = new List<string>(); ////////////////////////////////////////////////////////////////////////// public void AddWord(string Word) { if (Word == null || Word == string.Empty) return; if (!Words.Contains(Word)) Words.Add(Word); } ////////////////////////////////////////////////////////////////////////// public string GetWords() { string Ret = ""; Words.Sort(); int Counter = 0; foreach (string Word in Words) { if (Counter >= 10) { Ret = Ret + " \\\n"; Counter = 0; } else if (Counter > 0) Ret = Ret + " "; Ret = Ret + Word; Counter++; } return Ret; } ////////////////////////////////////////////////////////////////////////// public string GetWordsApi() { string Ret = ""; Words.Sort(); foreach(string Word in Words) { Ret += Word + "\n"; } return Ret; } }; } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace MonoMac.OpenGL { /// <summary>2-component Vector of the Half type. Occupies 4 Byte total.</summary> [Serializable, StructLayout(LayoutKind.Sequential)] public struct Vector2h : ISerializable, IEquatable<Vector2h> { #region Fields /// <summary>The X component of the Half2.</summary> public Half X; /// <summary>The Y component of the Half2.</summary> public Half Y; #endregion #region Constructors /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector2h(Half value) { X = value; Y = value; } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector2h(Single value) { X = new Half(value); Y = new Half(value); } /// <summary> /// The new Half2 instance will avoid conversion and copy directly from the Half parameters. /// </summary> /// <param name="x">An Half instance of a 16-bit half-precision floating-point number.</param> /// <param name="y">An Half instance of a 16-bit half-precision floating-point number.</param> public Vector2h(Half x, Half y) { X = x; Y = y; } /// <summary> /// The new Half2 instance will convert the 2 parameters into 16-bit half-precision floating-point. /// </summary> /// <param name="x">32-bit single-precision floating-point number.</param> /// <param name="y">32-bit single-precision floating-point number.</param> public Vector2h(Single x, Single y) { X = new Half(x); Y = new Half(y); } /// <summary> /// The new Half2 instance will convert the 2 parameters into 16-bit half-precision floating-point. /// </summary> /// <param name="x">32-bit single-precision floating-point number.</param> /// <param name="y">32-bit single-precision floating-point number.</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> public Vector2h(Single x, Single y, bool throwOnError) { X = new Half(x, throwOnError); Y = new Half(y, throwOnError); } /// <summary> /// The new Half2 instance will convert the Vector2 into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector2</param> [CLSCompliant(false)] public Vector2h(Vector2 v) { X = new Half(v.X); Y = new Half(v.Y); } /// <summary> /// The new Half2 instance will convert the Vector2 into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector2</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> [CLSCompliant(false)] public Vector2h(Vector2 v, bool throwOnError) { X = new Half(v.X, throwOnError); Y = new Half(v.Y, throwOnError); } /// <summary> /// The new Half2 instance will convert the Vector2 into 16-bit half-precision floating-point. /// This is the fastest constructor. /// </summary> /// <param name="v">OpenTK.Vector2</param> public Vector2h(ref Vector2 v) { X = new Half(v.X); Y = new Half(v.Y); } /// <summary> /// The new Half2 instance will convert the Vector2 into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector2</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> public Vector2h(ref Vector2 v, bool throwOnError) { X = new Half(v.X, throwOnError); Y = new Half(v.Y, throwOnError); } /// <summary> /// The new Half2 instance will convert the Vector2d into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector2d</param> public Vector2h(Vector2d v) { X = new Half(v.X); Y = new Half(v.Y); } /// <summary> /// The new Half2 instance will convert the Vector2d into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector2d</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> public Vector2h(Vector2d v, bool throwOnError) { X = new Half(v.X, throwOnError); Y = new Half(v.Y, throwOnError); } /// <summary> /// The new Half2 instance will convert the Vector2d into 16-bit half-precision floating-point. /// This is the faster constructor. /// </summary> /// <param name="v">OpenTK.Vector2d</param> [CLSCompliant(false)] public Vector2h(ref Vector2d v) { X = new Half(v.X); Y = new Half(v.Y); } /// <summary> /// The new Half2 instance will convert the Vector2d into 16-bit half-precision floating-point. /// </summary> /// <param name="v">OpenTK.Vector2d</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> [CLSCompliant(false)] public Vector2h(ref Vector2d v, bool throwOnError) { X = new Half(v.X, throwOnError); Y = new Half(v.Y, throwOnError); } #endregion Constructors #region Half -> Single /// <summary> /// Returns this Half2 instance's contents as Vector2. /// </summary> /// <returns>OpenTK.Vector2</returns> public Vector2 ToVector2() { return new Vector2(X, Y); } /// <summary> /// Returns this Half2 instance's contents as Vector2d. /// </summary> public Vector2d ToVector2d() { return new Vector2d(X, Y); } #endregion Half -> Single #region Conversions /// <summary>Converts OpenTK.Vector2 to OpenTK.Half2.</summary> /// <param name="v">The Vector2 to convert.</param> /// <returns>The resulting Half vector.</returns> public static explicit operator Vector2h(Vector2 v) { return new Vector2h(v); } /// <summary>Converts OpenTK.Vector2d to OpenTK.Half2.</summary> /// <param name="v">The Vector2d to convert.</param> /// <returns>The resulting Half vector.</returns> public static explicit operator Vector2h(Vector2d v) { return new Vector2h(v); } /// <summary>Converts OpenTK.Half2 to OpenTK.Vector2.</summary> /// <param name="h">The Half2 to convert.</param> /// <returns>The resulting Vector2.</returns> public static explicit operator Vector2(Vector2h h) { return new Vector2(h.X, h.Y); } /// <summary>Converts OpenTK.Half2 to OpenTK.Vector2d.</summary> /// <param name="h">The Half2 to convert.</param> /// <returns>The resulting Vector2d.</returns> public static explicit operator Vector2d(Vector2h h) { return new Vector2d(h.X, h.Y); } #endregion Conversions #region Constants /// <summary>The size in bytes for an instance of the Half2 struct is 4.</summary> public static readonly int SizeInBytes = 4; #endregion Constants #region ISerializable /// <summary>Constructor used by ISerializable to deserialize the object.</summary> /// <param name="info"></param> /// <param name="context"></param> public Vector2h(SerializationInfo info, StreamingContext context) { this.X = (Half)info.GetValue("X", typeof(Half)); this.Y = (Half)info.GetValue("Y", typeof(Half)); } /// <summary>Used by ISerialize to serialize the object.</summary> /// <param name="info"></param> /// <param name="context"></param> public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("X", this.X); info.AddValue("Y", this.Y); } #endregion ISerializable #region Binary dump /// <summary>Updates the X and Y components of this instance by reading from a Stream.</summary> /// <param name="bin">A BinaryReader instance associated with an open Stream.</param> public void FromBinaryStream(BinaryReader bin) { X.FromBinaryStream(bin); Y.FromBinaryStream(bin); } /// <summary>Writes the X and Y components of this instance into a Stream.</summary> /// <param name="bin">A BinaryWriter instance associated with an open Stream.</param> public void ToBinaryStream(BinaryWriter bin) { X.ToBinaryStream(bin); Y.ToBinaryStream(bin); } #endregion Binary dump #region IEquatable<Half2> Members /// <summary>Returns a value indicating whether this instance is equal to a specified OpenTK.Half2 vector.</summary> /// <param name="other">OpenTK.Half2 to compare to this instance..</param> /// <returns>True, if other is equal to this instance; false otherwise.</returns> public bool Equals(Vector2h other) { return (this.X.Equals(other.X) && this.Y.Equals(other.Y)); } #endregion #region ToString() /// <summary>Returns a string that contains this Half2's numbers in human-legible form.</summary> public override string ToString() { return String.Format("({0}, {1})", X.ToString(), Y.ToString()); } #endregion ToString() #region BitConverter /// <summary>Returns the Half2 as an array of bytes.</summary> /// <param name="h">The Half2 to convert.</param> /// <returns>The input as byte array.</returns> public static byte[] GetBytes(Vector2h h) { byte[] result = new byte[SizeInBytes]; byte[] temp = Half.GetBytes(h.X); result[0] = temp[0]; result[1] = temp[1]; temp = Half.GetBytes(h.Y); result[2] = temp[0]; result[3] = temp[1]; return result; } /// <summary>Converts an array of bytes into Half2.</summary> /// <param name="value">A Half2 in it's byte[] representation.</param> /// <param name="startIndex">The starting position within value.</param> /// <returns>A new Half2 instance.</returns> public static Vector2h FromBytes(byte[] value, int startIndex) { Vector2h h2 = new Vector2h(); h2.X = Half.FromBytes(value, startIndex); h2.Y = Half.FromBytes(value, startIndex + 2); return h2; } #endregion BitConverter } }
#region Using directives using System; using System.IO; using System.Xml; using System.Xml.Xsl; using System.Xml.XPath; using System.Xml.Serialization; using NUnit.Framework; using Commanigy.Iquomi.Api; using Commanigy.Iquomi.Data; using Commanigy.Iquomi.Store; using Commanigy.Iquomi.Services; #endregion namespace Commanigy.Iquomi.Test { /// <summary> /// Summary description for TestXmlStore. /// </summary> [TestFixture] public class TestXmlStore { private DbAccount account, account2; private DbAuthor author; private DbService service; private DbSubscription subscription; public TestXmlStore() { } [SetUp] public void Setup() { account = new DbAccount(); account.Iqid = "unittest-testiqid"; account.Email = "foo@bar.com"; account.Password = "iknownooooting"; account = DbAccount.DbCreate(account); account2 = new DbAccount(); account2.Iqid = "unittest-testiqid2"; account2.Email = "foo2@bar.com"; account2.Password = "iknownooooting"; account2 = DbAccount.DbCreate(account2); XmlDocument standardRoleTemplates = new XmlDocument(); standardRoleTemplates.LoadXml( @"<?xml version=""1.0"" encoding=""utf-8"" ?> <standardRoleTemplates> <scope name=""s0"" base=""t"" /> <scope name=""s1"" base=""nil""> <shape select=""//*[@creator='$callerId']"" type=""include"" /> </scope> <scope name=""s2"" base=""nil""> <shape select=""//notify[@creator='$callerId']"" type=""include"" /> </scope> <scope name=""s3"" base=""nil""> <shape select=""//*[cat/@ref='public']"" type=""include"" /> <shape select=""//notify[@creator='$callerId']"" type=""include"" /> </scope> <scope name=""s4"" base=""nil"" /> <roleTemplate name=""rt0""> <fullDescription xml:lang=""en-US"" dir=""ltr""> The purpose of this role template is to provide full access to all information. </fullDescription> <method name=""query"" scopeRef=""s0"" /> <method name=""insert"" scopeRef=""s0"" /> <method name=""replace"" scopeRef=""s0"" /> <method name=""delete"" scopeRef=""s0"" /> <method name=""update"" scopeRef=""s0"" /> </roleTemplate> <roleTemplate name=""rt1""> <fullDescription xml:lang=""en-US"" dir=""ltr""> The purpose of this role template is to provide full ability to read information with minimal ability to write. The caller can add information to the service, and can only delete information that is inserted or replaced. </fullDescription> <method name=""query"" scopeRef=""s0"" /> <method name=""insert"" scopeRef=""s1"" /> <method name=""replace"" scopeRef=""s1"" /> <method name=""delete"" scopeRef=""s1"" /> </roleTemplate> <roleTemplate name=""rt2""> <fullDescription xml:lang=""en-US"" dir=""ltr""> The purpose of this role template is to provide read-only access with ability to read and subscribe to all public information. </fullDescription> <method name=""query"" scopeRef=""s0"" /> <method name=""insert"" scopeRef=""s2"" /> <method name=""replace"" scopeRef=""s2"" /> <method name=""delete"" scopeRef=""s2"" /> </roleTemplate> <roleTemplate name=""rt3""> <fullDescription xml:lang=""en-US"" dir=""ltr""> The purpose of this role template is to provide read-only access with ability to subscribe to public events only. </fullDescription> <method name=""query"" scopeRef=""s0"" /> <method name=""insert"" scopeRef=""s3"" /> <method name=""replace"" scopeRef=""s3"" /> <method name=""delete"" scopeRef=""s3"" /> </roleTemplate> <roleTemplate name=""rt99""> <fullDescription xml:lang=""en-US"" dir=""ltr""> The purpose of this role template is to provide no access. </fullDescription> </roleTemplate> </standardRoleTemplates> "); author = new DbAuthor(); author.AccountId = account.Id; author.Name = "Test Author"; author.DbCreate(); service = new DbService(); service.Name = "Test Service"; service.Xsd = "<test />"; service.State = "P"; service.AuthorId = author.Id; // -- setup role templates, scopes and roles RoleMapType rmt = new RoleMapType(); /* RoleMapTypeScope s1 = new RoleMapTypeScope(); s1.Id = "1"; s1.Shape = new Services.ShapeType(); s1.Shape.Base = ShapeTypeBase.T; s1.Shape.BaseSpecified = true; RoleMapTypeScope s2 = new RoleMapTypeScope(); s2.Id = "2"; s2.Shape = new Services.ShapeType(); s2.Shape.Base = ShapeTypeBase.Nil; s2.Shape.BaseSpecified = true; ShapeAtomType sa2 = new ShapeAtomType(); sa2.Select = "//*[@creator='$callerId']"; s2.Shape.Include = new ShapeAtomType[] { sa2 }; RoleMapTypeScope s3 = new RoleMapTypeScope(); s3.Id = "3"; s3.Shape = new Services.ShapeType(); s3.Shape.Base = ShapeTypeBase.Nil; s3.Shape.BaseSpecified = true; ShapeAtomType sa3 = new ShapeAtomType(); sa3.Select = "//subscription[@creator='$callerId']"; s3.Shape.Include = new ShapeAtomType[] { sa3 }; RoleMapTypeScope s4 = new RoleMapTypeScope(); s4.Id = "4"; s4.Shape = new Services.ShapeType(); s4.Shape.Base = ShapeTypeBase.Nil; s4.Shape.BaseSpecified = true; ShapeAtomType sa4_1 = new ShapeAtomType(); sa4_1.Select = "//*[cat/@ref='iq:public']"; ShapeAtomType sa4_2 = new ShapeAtomType(); sa4_2.Select = "//subscription[@creator='$callerId']"; s4.Shape.Include = new ShapeAtomType[] { sa4_1, sa4_2 }; RoleTemplateTypeMethod rtm1 = new RoleTemplateTypeMethod(); rtm1.Name = "query"; rtm1.ScopeRef = "1"; RoleTemplateTypeMethod rtm2 = new RoleTemplateTypeMethod(); rtm2.Name = "insert"; rtm2.ScopeRef = "1"; RoleTemplateTypeMethod rtm3 = new RoleTemplateTypeMethod(); rtm3.Name = "replace"; rtm3.ScopeRef = "1"; RoleTemplateTypeMethod rtm4 = new RoleTemplateTypeMethod(); rtm4.Name = "delete"; rtm4.ScopeRef = "1"; RoleTemplateTypeMethod rtm5 = new RoleTemplateTypeMethod(); rtm5.Name = "update"; rtm5.ScopeRef = "1"; RoleTemplateType rt0 = new RoleTemplateType(); rt0.Name = "rt0"; rt0.Method = new RoleTemplateTypeMethod[] { rtm1, rtm2, rtm3, rtm4, rtm5 }; RoleTemplateType rt1 = new RoleTemplateType(); rt1.Name = "rt1"; rt1.Method = new RoleTemplateTypeMethod[] { rtm1 }; rmt.RoleTemplate = new RoleTemplateType[] { rt0, rt1 }; rmt.Scope = new RoleMapTypeScope[] { s1, s2, s3, s4 }; */ service.SetRoleMap(rmt); service.DbCreate(); // DbScope scope = new DbScope(); // scope.Name = "t"; // scope.Base = "t"; // service.DbCreateScope(scope); // // DbScope scope2 = new DbScope(); // scope2.Name = "nil"; // scope2.Base = "nil"; // service.DbCreateScope(scope2); // // DbShape shape = new DbShape(); // shape.Type = "I"; // shape.ScopeId = scope2.Id; // shape.Select = "/*/note[@Id='724334d8-dbc6-45db-b808-d6dbdc09a789']"; // shape.DbCreate(); // // DbScope scope3 = new DbScope(); // scope3.Name = "Only own information"; // scope3.Base = "nil"; // service.DbCreateScope(scope3); // // DbShape shape2 = new DbShape(); // shape2.Type = "I"; // shape2.ScopeId = scope3.Id; // shape2.Select = "//*/note[@creator='2']"; // shape2.DbCreate(); // // DbRoleTemplate rt = new DbRoleTemplate(); // rt.Name = "Full Access"; // rt.ServiceId = service.Id; // rt.DbCreate(); // // DbRoleTemplateMethod rtm = null; // rtm = new DbRoleTemplateMethod(); // rtm.RoleTemplateId = rt.Id; // rtm.ScopeId = scope.Id; // rtm.MethodTypeId = 1; // rtm.DbCreate(); // // rtm = new DbRoleTemplateMethod(); // rtm.RoleTemplateId = rt.Id; // rtm.ScopeId = scope.Id; // rtm.MethodTypeId = 2; // rtm.DbCreate(); // // rtm = new DbRoleTemplateMethod(); // rtm.RoleTemplateId = rt.Id; // rtm.ScopeId = scope.Id; // rtm.MethodTypeId = 3; // rtm.DbCreate(); // // rtm = new DbRoleTemplateMethod(); // rtm.RoleTemplateId = rt.Id; // rtm.ScopeId = scope.Id; // rtm.MethodTypeId = 4; // rtm.DbCreate(); // // rtm = new DbRoleTemplateMethod(); // rtm.RoleTemplateId = rt.Id; // rtm.ScopeId = scope.Id; // rtm.MethodTypeId = 5; // rtm.DbCreate(); // // DbRoleTemplate rt2 = new DbRoleTemplate(); // rt2.Name = "Limited Access"; // rt2.ServiceId = service.Id; // rt2.DbCreate(); // // rtm = new DbRoleTemplateMethod(); // rtm.RoleTemplateId = rt2.Id; // rtm.ScopeId = scope2.Id; // rtm.MethodTypeId = 5; // query // rtm.DbCreate(); // // rtm = new DbRoleTemplateMethod(); // rtm.RoleTemplateId = rt2.Id; // rtm.ScopeId = scope3.Id; // rtm.MethodTypeId = 1; // insert // rtm.DbCreate(); subscription = new DbSubscription(); subscription.Id = new Guid("18ed9bfa-1c2c-4974-be82-9a36bf480484"); subscription.AccountId = account.Id; subscription.ServiceId = service.Id; subscription.Name = service.Name; subscription.Xml = @" <notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""3""> <note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""1""> <title>Test</title> <description>asdf</description> </note> <note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""> <title>Test2</title> <description>asdf</description> </note> <note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""> <title>Test3</title> <description>asdf</description> </note> <note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""> <title>Test4</title> <description>asdf</description> </note> </notes> "; RoleListType rl = new RoleListType(); RoleType r1 = new RoleType(); r1.Subject = new SubjectType(); r1.Subject.UserId = "unittest-testiqid"; r1.RoleTemplateRef = "rt0"; r1.ScopeRef = "1"; RoleType r2 = new RoleType(); r2.Subject = new SubjectType(); r2.Subject.UserId = "unittest-testiqid2"; r2.RoleTemplateRef = "rt1"; r2.ScopeRef = "1"; rl.Role = new RoleType[] { r1, r2 }; /* RoleListScopeType rls = new RoleListScopeType(); rls.Id = "1"; rls.Shape = new Services.ShapeType(); rls.Shape.Base = ShapeTypeBase.T; rls.Shape.BaseSpecified = true; rl.Scope = new RoleListScopeType[] { rls }; */ subscription.SetRoleList(rl); NotifyListType notifyList = new NotifyListType(); notifyList.Listener = new ListenerType[1]; notifyList.Listener[0] = new ListenerType(); notifyList.Listener[0].To = "iq:iqAlerts"; notifyList.Listener[0].Trigger = new ListenerTypeTrigger(); notifyList.Listener[0].Trigger.Select = "/"; notifyList.Listener[0].Trigger.Mode = ListenerTypeTriggerMode.IncludeData; subscription.SetNotifyList(notifyList); subscription.DbCreate(); // DbRole r = new DbRole(); // r.AccountId = account.Id; // r.RoleTemplateId = rt.Id; // r.SubscriptionId = subscription.Id; // r.DbCreate(); // // r = new DbRole(); // r.AccountId = account2.Id; // r.RoleTemplateId = rt2.Id; // r.SubscriptionId = subscription.Id; // r.DbCreate(); } [TearDown] public void TearDown() { subscription.DbDelete(); service.DbDelete(); DbAccount.DbDelete(account); DbAccount.DbDelete(account2); } public IXmlStore GetXmlStore() { RequestType request = new RequestType(); RequestTypeKey rtk = new RequestTypeKey(); rtk.Puid = "unittest-testiqid"; request.Key = new RequestTypeKey[] { rtk }; request.Service = "Test Service"; return XmlStoreRepository.Instance.Find(request, null); } public SubjectType GetSubject() { SubjectType subject = new SubjectType(); subject.UserId = "unittest-testiqid"; subject.AppAndPlatformId = ""; subject.CredType = ""; return subject; } public SubjectType GetSubject2() { SubjectType subject = new SubjectType(); subject.UserId = "unittest-testiqid2"; subject.AppAndPlatformId = ""; subject.CredType = ""; return subject; } public XmlElement ToXmlElement(string xml) { XmlDocument d = new XmlDocument(); d.LoadXml(xml); return d.DocumentElement; } #region Test Cases for "Insert" method [Test] public void Insert_SelectAttribute() { InsertRequestType req = new InsertRequestType(); req.Select = "//note[@Id='a9df1410-69a0-4be3-ab91-c017f6a44b58']/@priority"; req.Any = new XmlElement[] { ToXmlElement("<d Id=\"3\" />") }; req.UseClientIdsSpecified = true; req.UseClientIds = true; InsertResponseType res = GetXmlStore().Insert(GetSubject(), req); Assert.IsTrue(res.SelectedNodeCount == 1); // fails since we can't target an attribute value - instead use 'attributes' Assert.IsTrue(res.Status == ResponseStatus.Failure); Assert.IsTrue("3".Equals(res.NewChangeNumber)); } [Test] public void Insert_InsertAttributes() { InsertRequestType req = new InsertRequestType(); req.Select = "/notes/note[@Id='f3492deb-b41d-4c98-8324-e550a6c42757']"; req.Any = new XmlElement[0]; RedAttributeType at = new RedAttributeType(); at.Name = "name"; at.Value = "Peter Theill"; RedAttributeType at2 = new RedAttributeType(); at2.Name = "age"; at2.Value = "26"; req.Attributes = new RedAttributeType[] { at, at2 }; req.UseClientIdsSpecified = true; req.UseClientIds = true; IXmlStore store = GetXmlStore(); InsertResponseType res = store.Insert(GetSubject(), req); Assert.IsTrue(res.SelectedNodeCount == 1); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue("4".Equals(res.NewChangeNumber)); Assert.IsTrue(store.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""4""><note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""4"" name=""Peter Theill"" age=""26""><title>Test</title><description>asdf</description></note><note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""><title>Test4</title><description>asdf</description></note></notes>" ) ); } [Test] public void Insert_UseClient() { InsertRequestType req = new InsertRequestType(); req.Select = "/notes"; req.Any = new XmlElement[] { ToXmlElement("<note Id=\"42\" ChangeNumber=\"\" />") }; req.UseClientIdsSpecified = true; req.UseClientIds = true; IXmlStore store = GetXmlStore(); InsertResponseType res = store.Insert(GetSubject(), req); ; Assert.IsTrue(res.SelectedNodeCount == 1); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue("4".Equals(res.NewChangeNumber)); Assert.IsTrue(store.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""4""><note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""1""><title>Test</title><description>asdf</description></note><note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""><title>Test4</title><description>asdf</description></note><note Id=""42"" ChangeNumber=""4"" /></notes>" ) ); } [Test] public void Insert_NoUseClientIds() { InsertRequestType req = new InsertRequestType(); req.Select = "/notes"; req.Any = new XmlElement[] { ToXmlElement("<note Id=\"\" ChangeNumber=\"\" />") }; req.UseClientIdsSpecified = true; req.UseClientIds = false; IXmlStore store = GetXmlStore(); InsertResponseType res = store.Insert(GetSubject(), req); ; Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue(res.SelectedNodeCount == 1); Assert.IsTrue(res.NewBlueId.Length == 1, "NewBlueId must contain one element"); Assert.IsTrue(store.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""4""><note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""1""><title>Test</title><description>asdf</description></note><note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""><title>Test4</title><description>asdf</description></note><note Id=""" + res.NewBlueId[0].Id + @""" ChangeNumber=""4"" /></notes>" )); } [Test] public void Insert_MultipleUseClientIds() { InsertRequestType req = new InsertRequestType(); req.Select = "/notes"; req.Any = new XmlElement[] { ToXmlElement(@"<note Id=""42"" ChangeNumber=""""><title Id=""43"" /></note>") }; req.UseClientIdsSpecified = true; req.UseClientIds = true; IXmlStore store = GetXmlStore(); InsertResponseType res = store.Insert(GetSubject(), req); ; Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue(res.SelectedNodeCount == 1); Assert.IsTrue("4".Equals(res.NewChangeNumber)); Assert.IsTrue(res.NewBlueId.Length == 0); Assert.IsTrue(store.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""4""><note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""1""><title>Test</title><description>asdf</description></note><note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""><title>Test4</title><description>asdf</description></note><note Id=""42"" ChangeNumber=""4""><title Id=""43"" /></note></notes>" )); } [Test] public void Insert_MultipleNoUseClientIds() { InsertRequestType req = new InsertRequestType(); req.Select = "/notes"; req.Any = new XmlElement[] { ToXmlElement(@"<note Id="""" ChangeNumber=""""><title Id="""" /><description>something</description></note>") }; req.UseClientIdsSpecified = true; req.UseClientIds = false; IXmlStore store = GetXmlStore(); InsertResponseType res = store.Insert(GetSubject(), req); ; Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue(res.SelectedNodeCount == 1); Assert.IsTrue(res.NewBlueId.Length == 1); Assert.IsTrue("4".Equals(res.NewChangeNumber)); Assert.IsTrue(store.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""4""><note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""1""><title>Test</title><description>asdf</description></note><note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""><title>Test4</title><description>asdf</description></note><note Id=""" + res.NewBlueId[0].Id + @""" ChangeNumber=""4""><title Id="""" /><description>something</description></note></notes>" )); } [Test] public void Insert_MultipleInsertsNoUseClientIds() { InsertRequestType req = new InsertRequestType(); req.Select = "//note"; req.Any = new XmlElement[] { ToXmlElement("<link>http://www.iquomi.com/</link>") }; req.UseClientIdsSpecified = true; req.UseClientIds = false; IXmlStore store = GetXmlStore(); InsertResponseType res = store.Insert(GetSubject(), req); ; Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue(res.SelectedNodeCount == 4); Assert.IsTrue(res.NewBlueId.Length == 0); Assert.IsTrue("4".Equals(res.NewChangeNumber)); Assert.IsTrue(store.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""4""><note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""4""><title>Test</title><description>asdf</description><link>http://www.iquomi.com/</link></note><note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""4""><title>Test2</title><description>asdf</description><link>http://www.iquomi.com/</link></note><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""4"" priority=""1""><title>Test3</title><description>asdf</description><link>http://www.iquomi.com/</link></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""4""><title>Test4</title><description>asdf</description><link>http://www.iquomi.com/</link></note></notes>" )); } [Test] public void Insert_MultipleInsertsMultipleNoUseClientIds() { InsertRequestType req = new InsertRequestType(); req.Select = "//note"; req.Any = new XmlElement[] { ToXmlElement(@"<link Id="""">http://www.iquomi.com/</link>") }; req.UseClientIdsSpecified = true; req.UseClientIds = false; IXmlStore store = GetXmlStore(); InsertResponseType res = store.Insert(GetSubject(), req); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue(res.SelectedNodeCount == 4); Assert.IsTrue("4".Equals(res.NewChangeNumber)); Assert.IsTrue(res.NewBlueId.Length == 4, "NewBlueIds must contain four elements but " + res.NewBlueId.Length + " found"); } //[Test] public void Insert_Role() { InsertRequestType req = new InsertRequestType(); req.Select = "/notes"; req.Any = new XmlElement[] { ToXmlElement(@"<note Id="""" />") }; req.UseClientIdsSpecified = true; req.UseClientIds = false; InsertResponseType res = GetXmlStore().Insert(GetSubject2(), req); Assert.IsTrue(res.SelectedNodeCount == 1); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue("4".Equals(res.NewChangeNumber)); Assert.IsTrue(res.NewBlueId.Length == 1, "One Blue Id expected but " + res.NewBlueId.Length + " returned"); } #endregion #region Test Cases for "Delete" method [Test] public void Delete_NoNodes() { DeleteRequestType req = new DeleteRequestType(); req.Select = "/foo"; DeleteResponseType res = GetXmlStore().Delete(GetSubject(), req); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue("3".Equals(res.NewChangeNumber)); } [Test] public void Delete_AllNodes() { DeleteRequestType req = new DeleteRequestType(); req.Select = "/notes"; IXmlStore store = GetXmlStore(); DeleteResponseType res = store.Delete(GetSubject(), req); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue("4".Equals(res.NewChangeNumber)); } [Test] public void Delete_Attribute() { DeleteRequestType req = new DeleteRequestType(); req.Select = "//note[@Id='a9df1410-69a0-4be3-ab91-c017f6a44b58']/@priority"; DeleteResponseType res = GetXmlStore().Delete(GetSubject(), req); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue(res.SelectedNodeCount == 1); Assert.IsTrue("4".Equals(res.NewChangeNumber)); } [Test] public void Delete_MaxOccursTooLow() { DeleteRequestType req = new DeleteRequestType(); req.Select = "//note"; req.MaxOccursSpecified = true; req.MaxOccurs = 1; DeleteResponseType res = GetXmlStore().Delete(GetSubject(), req); Assert.IsTrue(res.Status == ResponseStatus.Failure); Assert.IsTrue("3".Equals(res.NewChangeNumber)); } [Test] public void Delete_MaxOccursEqual() { DeleteRequestType req = new DeleteRequestType(); req.Select = "//note"; req.MaxOccursSpecified = true; req.MaxOccurs = 4; DeleteResponseType res = GetXmlStore().Delete(GetSubject(), req); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue("4".Equals(res.NewChangeNumber)); } [Test] public void Delete_MinOccursTooLow() { DeleteRequestType req = new DeleteRequestType(); req.Select = "//foobar"; req.MinOccursSpecified = true; req.MinOccurs = 2; DeleteResponseType res = GetXmlStore().Delete(GetSubject(), req); Assert.IsTrue(res.Status == ResponseStatus.Failure); Assert.IsTrue("3".Equals(res.NewChangeNumber)); } [Test] public void Delete_MinOccursEqual() { DeleteRequestType req = new DeleteRequestType(); req.Select = "//note[@Id='f3492deb-b41d-4c98-8324-e550a6c42757']"; req.MinOccursSpecified = true; req.MinOccurs = 1; IXmlStore xmlstore = GetXmlStore(); DeleteResponseType res = xmlstore.Delete(GetSubject(), req); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue("4".Equals(res.NewChangeNumber)); Assert.IsTrue(xmlstore.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""4""><note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""><title>Test4</title><description>asdf</description></note></notes>" ) ); } [Test] public void Delete_MinOccursMaxOccursEqual() { DeleteRequestType req = new DeleteRequestType(); req.Select = "//note"; req.MinOccursSpecified = true; req.MinOccurs = 4; req.MaxOccursSpecified = true; req.MaxOccurs = 4; DeleteResponseType res = GetXmlStore().Delete(GetSubject(), req); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue(res.SelectedNodeCount == 4); Assert.IsTrue("4".Equals(res.NewChangeNumber)); } [Test] public void Delete_MinOccursMaxOccursLowHigh() { DeleteRequestType req = new DeleteRequestType(); req.Select = "//note"; req.MinOccursSpecified = true; req.MinOccurs = 0; req.MaxOccursSpecified = true; req.MaxOccurs = 4; DeleteResponseType res = GetXmlStore().Delete(GetSubject(), req); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue(res.SelectedNodeCount == 4); Assert.IsTrue("4".Equals(res.NewChangeNumber)); } #endregion #region Test cases for "Replace" method [Test] public void Replace_UseClient() { ReplaceRequestType req = new ReplaceRequestType(); req.Select = "//note[@Id='f3492deb-b41d-4c98-8324-e550a6c42757']"; req.Any = new XmlElement[] { ToXmlElement(@"<d Id=""3""><e /></d>") }; req.UseClientIdsSpecified = true; req.UseClientIds = true; IXmlStore xmlstore = GetXmlStore(); ReplaceResponseType res = xmlstore.Replace(GetSubject(), req); Assert.IsTrue(res.SelectedNodeCount == 1); Assert.IsTrue(res.NewBlueId.Length == 0); Assert.IsTrue("4".Equals(res.NewChangeNumber)); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue(xmlstore.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""4""><d Id=""3""><e /></d><note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""><title>Test4</title><description>asdf</description></note></notes>" )); } [Test] public void Replace_WithEmpty() { ReplaceRequestType req = new ReplaceRequestType(); req.Select = "//note[@Id='f3492deb-b41d-4c98-8324-e550a6c42757']"; req.Any = new XmlElement[0]; req.UseClientIdsSpecified = true; req.UseClientIds = true; IXmlStore xmlstore = GetXmlStore(); ReplaceResponseType res = xmlstore.Replace(GetSubject(), req); Assert.IsTrue(res.SelectedNodeCount == 1); Assert.IsTrue(res.NewBlueId.Length == 0); Assert.IsTrue("4".Equals(res.NewChangeNumber)); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue(xmlstore.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""4""><note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""4""></note><note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""><title>Test4</title><description>asdf</description></note></notes>" ) ); } [Test] public void Replace_Multiple() { ReplaceRequestType req = new ReplaceRequestType(); req.Select = "//note"; req.Any = new XmlElement[] { ToXmlElement(@"<d name=""abc"" />") }; req.UseClientIdsSpecified = true; req.UseClientIds = true; IXmlStore xmlstore = GetXmlStore(); ReplaceResponseType res = xmlstore.Replace(GetSubject(), req); Assert.IsTrue(res.SelectedNodeCount == 4); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue("4".Equals(res.NewChangeNumber)); Assert.IsTrue(xmlstore.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""4""><d name=""abc"" /><d name=""abc"" /><d name=""abc"" /><d name=""abc"" /></notes>" ) ); } [Test] public void Replace_SingleSub() { ReplaceRequestType req = new ReplaceRequestType(); req.Select = "//note[@Id='724334d8-dbc6-45db-b808-d6dbdc09a789']"; req.Any = new XmlElement[] { ToXmlElement(@"<b Id=""2""><d name=""not_b"" /></b>") }; req.UseClientIdsSpecified = true; req.UseClientIds = true; IXmlStore xmlstore = GetXmlStore(); ReplaceResponseType res = xmlstore.Replace(GetSubject(), req); Assert.IsTrue(res.SelectedNodeCount == 1); Assert.IsTrue("4".Equals(res.NewChangeNumber)); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue(xmlstore.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""4""><note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""1""><title>Test</title><description>asdf</description></note><b Id=""2""><d name=""not_b"" /></b><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""><title>Test4</title><description>asdf</description></note></notes>" )); } [Test] public void Replace_SingleSubWithId() { ReplaceRequestType req = new ReplaceRequestType(); req.Select = "//note[@Id='724334d8-dbc6-45db-b808-d6dbdc09a789']"; req.Any = new XmlElement[] { ToXmlElement(@"<b Id="""" ChangeNumber=""""><d name=""not_b"" /></b>") }; req.UseClientIdsSpecified = true; req.UseClientIds = false; IXmlStore xmlstore = GetXmlStore(); ReplaceResponseType res = xmlstore.Replace(GetSubject(), req); Assert.IsTrue(res.SelectedNodeCount == 1); Assert.IsTrue(res.NewBlueId.Length == 1, "Got " + res.NewBlueId.Length + " but expected 1"); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue("4".Equals(res.NewChangeNumber)); Assert.IsTrue(xmlstore.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""4""><note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""1""><title>Test</title><description>asdf</description></note><b Id=""" + res.NewBlueId[0].Id + @""" ChangeNumber=""4""><d name=""not_b"" /></b><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""><title>Test4</title><description>asdf</description></note></notes>" ) ); } [Test] public void Replace_AttributeByAttributeSelect() { ReplaceRequestType req = new ReplaceRequestType(); req.Select = "//note[@Id='a9df1410-69a0-4be3-ab91-c017f6a44b58']/@priority"; req.Any = new XmlElement[] { ToXmlElement(@"<illegal-content />") }; req.UseClientIdsSpecified = true; req.UseClientIds = true; RedAttributeType at = new RedAttributeType(); at.Name = "priority"; at.Value = "42"; req.Attributes = new RedAttributeType[] { at }; IXmlStore xmlstore = GetXmlStore(); ReplaceResponseType res = xmlstore.Replace(GetSubject(), req); Assert.IsTrue(res.SelectedNodeCount == 1); Assert.IsTrue(res.Status == ResponseStatus.Failure); Assert.IsTrue(xmlstore.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""3""><note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""1""><title>Test</title><description>asdf</description></note><note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""><title>Test4</title><description>asdf</description></note></notes>" ) ); } [Test] public void Replace_Attribute() { ReplaceRequestType req = new ReplaceRequestType(); req.Select = "//note[@Id='a9df1410-69a0-4be3-ab91-c017f6a44b58']/@priority"; req.Any = new XmlElement[0]; req.UseClientIdsSpecified = true; req.UseClientIds = true; RedAttributeType at = new RedAttributeType(); at.Name = "priority"; at.Value = "42"; req.Attributes = new RedAttributeType[] { at }; IXmlStore xmlstore = GetXmlStore(); ReplaceResponseType res = xmlstore.Replace(GetSubject(), req); Assert.IsTrue(res.SelectedNodeCount == 1); Assert.IsTrue("4".Equals(res.NewChangeNumber)); Assert.IsTrue(res.NewBlueId.Length == 0); Assert.IsTrue(res.Status == ResponseStatus.Success); Assert.IsTrue(xmlstore.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""4""><note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""1""><title>Test</title><description>asdf</description></note><note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""4"" priority=""42""><title>Test3</title><description>asdf</description></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""><title>Test4</title><description>asdf</description></note></notes>" ) ); } #endregion #region Test cases for "Update" method [Test] public void Update_SimpleInsert() { UpdateRequestType req = new UpdateRequestType(); UpdateBlockType u = new UpdateBlockType(); InsertRequestType ir = new InsertRequestType(); ir.Select = "/notes"; ir.Any = new XmlElement[] { ToXmlElement("<note />") }; ir.UseClientIdsSpecified = true; ir.UseClientIds = true; u.InsertRequest = new InsertRequestType[] { ir }; req.UpdateBlock = new UpdateBlockType[] { u }; IXmlStore xmlstore = GetXmlStore(); UpdateResponseType res = xmlstore.Update(GetSubject(), req); Assert.IsTrue(res.UpdateBlockStatus[0].InsertResponse[0].SelectedNodeCount == 1); Assert.IsTrue("4".Equals(res.UpdateBlockStatus[0].InsertResponse[0].NewChangeNumber)); Assert.IsTrue(res.UpdateBlockStatus[0].Status == ResponseStatus.Success); Assert.IsTrue(xmlstore.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""4""><note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""1""><title>Test</title><description>asdf</description></note><note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""><title>Test4</title><description>asdf</description></note><note /></notes>" ) ); } [Test] public void Update_InsertDelete() { UpdateRequestType req = new UpdateRequestType(); UpdateBlockType u = new UpdateBlockType(); InsertRequestType ir = new InsertRequestType(); ir.Select = "/notes"; ir.Any = new XmlElement[] { ToXmlElement(@"<note Id=""new-id"" />") }; ir.UseClientIdsSpecified = true; ir.UseClientIds = true; u.InsertRequest = new InsertRequestType[] { ir }; DeleteRequestType dr = new DeleteRequestType(); dr.Select = "//note[@Id='f3492deb-b41d-4c98-8324-e550a6c42757']"; u.DeleteRequest = new DeleteRequestType[] { dr }; req.UpdateBlock = new UpdateBlockType[] { u }; IXmlStore xmlstore = GetXmlStore(); UpdateResponseType res = xmlstore.Update(GetSubject(), req); Assert.IsTrue(res.UpdateBlockStatus[0].InsertResponse[0].SelectedNodeCount == 1); Assert.IsTrue(res.UpdateBlockStatus[0].DeleteResponse[0].SelectedNodeCount == 1); Assert.IsTrue(res.UpdateBlockStatus[0].Status == ResponseStatus.Success); Assert.IsTrue(xmlstore.ContentDocument.XmlDocument.OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""4""><note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""><title>Test4</title><description>asdf</description></note><note Id=""new-id"" /></notes>" ) ); } #endregion #region Test cases for "Query.XpQuery" method [Test] public void Query_Simple() { QueryRequestType req = new QueryRequestType(); XpQueryType q = new XpQueryType(); q.Select = "//note[@Id='724334d8-dbc6-45db-b808-d6dbdc09a789']"; req.XpQuery = new XpQueryType[] { q }; QueryResponseType res = GetXmlStore().Query(GetSubject(), req); Assert.IsTrue(res.XpQueryResponse[0].SelectedNodeCount == 1); Assert.IsTrue(res.XpQueryResponse[0].Status == ResponseStatus.Success); Assert.IsTrue(res.XpQueryResponse[0].Any.Length == 1); Assert.IsTrue(res.XpQueryResponse[0].Any[0].OuterXml.Equals( @"<note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note>" ) ); } [Test] public void Query_SimpleRole() { QueryRequestType req = new QueryRequestType(); XpQueryType q = new XpQueryType(); q.Select = "/notes//note"; req.XpQuery = new XpQueryType[] { q }; QueryResponseType res = GetXmlStore().Query(GetSubject2(), req); Assert.IsTrue(res.XpQueryResponse[0].SelectedNodeCount == 1); Assert.IsTrue(res.XpQueryResponse[0].Status == ResponseStatus.Success); Assert.IsTrue(res.XpQueryResponse[0].Any.Length == 1); Assert.IsTrue(res.XpQueryResponse[0].Any[0].OuterXml.Equals( @"<note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note>" ) ); } [Test] public void Query_RoleExcludeSpecific() { QueryRequestType req = new QueryRequestType(); XpQueryType q = new XpQueryType(); q.Select = "/*/note[@Id='18ed9bfa-1c2c-4974-be82-9a36bf480484']"; req.XpQuery = new XpQueryType[] { q }; QueryResponseType res = GetXmlStore().Query(GetSubject2(), req); Assert.IsTrue(res.XpQueryResponse[0].SelectedNodeCount == 0); Assert.IsTrue(res.XpQueryResponse[0].Status == ResponseStatus.Success); Assert.IsTrue(res.XpQueryResponse[0].Any.Length == 0); } [Test] public void Query_RoleIncludeSpecific() { QueryRequestType req = new QueryRequestType(); XpQueryType q = new XpQueryType(); q.Select = "/*/note[@Id='724334d8-dbc6-45db-b808-d6dbdc09a789']"; req.XpQuery = new XpQueryType[] { q }; QueryResponseType res = GetXmlStore().Query(GetSubject2(), req); Assert.IsTrue(res.XpQueryResponse[0].SelectedNodeCount == 1); Assert.IsTrue(res.XpQueryResponse[0].Status == ResponseStatus.Success); Assert.IsTrue(res.XpQueryResponse[0].Any.Length == 1); Assert.IsTrue(res.XpQueryResponse[0].Any[0].OuterXml.Equals( @"<note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note>" ) ); } [Test] public void Query_MultipleNodes() { QueryRequestType req = new QueryRequestType(); XpQueryType q = new XpQueryType(); q.Select = "//note[@Id='f3492deb-b41d-4c98-8324-e550a6c42757' or @Id='724334d8-dbc6-45db-b808-d6dbdc09a789']"; req.XpQuery = new XpQueryType[] { q }; QueryResponseType res = GetXmlStore().Query(GetSubject(), req); Assert.IsTrue(res.XpQueryResponse[0].SelectedNodeCount == 2); Assert.IsTrue(res.XpQueryResponse[0].Status == ResponseStatus.Success); Assert.IsTrue(res.XpQueryResponse[0].Any.Length == 2); Assert.IsTrue(res.XpQueryResponse[0].Any[0].OuterXml.Equals( @"<note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""1""><title>Test</title><description>asdf</description></note>" )); Assert.IsTrue(res.XpQueryResponse[0].Any[1].OuterXml.Equals( @"<note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note>" )); } [Test] public void Query_Multiple() { QueryRequestType req = new QueryRequestType(); XpQueryType q = new XpQueryType(); q.Select = "//note[@Id='f3492deb-b41d-4c98-8324-e550a6c42757']"; XpQueryType q2 = new XpQueryType(); q2.Select = "//note[@Id='724334d8-dbc6-45db-b808-d6dbdc09a789']"; req.XpQuery = new XpQueryType[] { q, q2 }; QueryResponseType res = GetXmlStore().Query(GetSubject(), req); Assert.IsTrue(res.XpQueryResponse[0].SelectedNodeCount == 1); Assert.IsTrue(res.XpQueryResponse[0].Status == ResponseStatus.Success); Assert.IsTrue(res.XpQueryResponse[0].Any[0].OuterXml.Equals( @"<note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""1""><title>Test</title><description>asdf</description></note>" )); Assert.IsTrue(res.XpQueryResponse[1].SelectedNodeCount == 1); Assert.IsTrue(res.XpQueryResponse[1].Status == ResponseStatus.Success); Assert.IsTrue(res.XpQueryResponse[1].Any[0].OuterXml.Equals( @"<note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note>" )); } [Test] public void Query_NoNodes() { QueryRequestType req = new QueryRequestType(); XpQueryType q = new XpQueryType(); q.Select = "//d"; req.XpQuery = new XpQueryType[] { q }; QueryResponseType res = GetXmlStore().Query(GetSubject(), req); Assert.IsTrue(res.XpQueryResponse[0].SelectedNodeCount == 0); Assert.IsTrue(res.XpQueryResponse[0].Status == ResponseStatus.Success); } [Test] public void Query_TooManyNodes() { QueryRequestType req = new QueryRequestType(); XpQueryType q = new XpQueryType(); q.Select = "//note"; q.MaxOccursSpecified = true; q.MaxOccurs = 3; req.XpQuery = new XpQueryType[] { q }; QueryResponseType res = GetXmlStore().Query(GetSubject(), req); Assert.IsTrue(res.XpQueryResponse[0].SelectedNodeCount == 4); Assert.IsTrue(res.XpQueryResponse[0].Status == ResponseStatus.Failure); } [Test] public void Query_RootNode() { QueryRequestType req = new QueryRequestType(); XpQueryType q = new XpQueryType(); q.Select = "/notes"; req.XpQuery = new XpQueryType[] { q }; QueryResponseType res = GetXmlStore().Query(GetSubject(), req); Assert.IsTrue(res.XpQueryResponse[0].SelectedNodeCount == 1); Assert.IsTrue(res.XpQueryResponse[0].Status == ResponseStatus.Success); Assert.IsTrue(res.XpQueryResponse[0].Any[0].OuterXml.Equals( @"<notes InstanceId=""18ed9bfa-1c2c-4974-be82-9a36bf480484"" ChangeNumber=""3""><note Id=""f3492deb-b41d-4c98-8324-e550a6c42757"" ChangeNumber=""1""><title>Test</title><description>asdf</description></note><note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note><note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note><note Id=""80831c54-90e6-4e55-9150-6e57c8e8f2b5"" ChangeNumber=""1""><title>Test4</title><description>asdf</description></note></notes>" )); } #endregion #region Test cases for "Query.ChangeQuery" method [Test] public void Query_ChangeQueryNoChange() { QueryRequestType req = new QueryRequestType(); ChangeQueryType q = new ChangeQueryType(); q.BaseChangeNumber = "3"; q.Select = "/notes"; req.ChangeQuery = new ChangeQueryType[] { q }; QueryResponseType res = GetXmlStore().Query(GetSubject(), req); Assert.IsTrue("3".Equals(res.ChangeQueryResponse[0].BaseChangeNumber)); Assert.IsTrue(res.ChangeQueryResponse[0].Status == ResponseStatus.Success); Assert.IsTrue(res.ChangeQueryResponse[0].ChangedBlue.Length == 0); } [Test] public void Query_ChangeQuerySingleChanges() { QueryRequestType req = new QueryRequestType(); ChangeQueryType q = new ChangeQueryType(); q.BaseChangeNumber = "2"; q.Select = "/notes"; req.ChangeQuery = new ChangeQueryType[] { q }; QueryResponseType res = GetXmlStore().Query(GetSubject(), req); Assert.IsTrue("3".Equals(res.ChangeQueryResponse[0].BaseChangeNumber)); Assert.IsTrue(res.ChangeQueryResponse[0].Status == ResponseStatus.Success); Assert.IsTrue(res.ChangeQueryResponse[0].ChangedBlue.Length == 1); Assert.IsTrue(res.ChangeQueryResponse[0].ChangedBlue[0].Any[0].OuterXml.Equals( @"<note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note>")); } [Test] public void Query_ChangeQueryMultipleChanges() { QueryRequestType req = new QueryRequestType(); ChangeQueryType q = new ChangeQueryType(); q.BaseChangeNumber = "1"; q.Select = "/notes"; req.ChangeQuery = new ChangeQueryType[] { q }; QueryResponseType res = GetXmlStore().Query(GetSubject(), req); Assert.IsTrue("3".Equals(res.ChangeQueryResponse[0].BaseChangeNumber)); Assert.IsTrue(res.ChangeQueryResponse[0].Status == ResponseStatus.Success); Assert.IsTrue(res.ChangeQueryResponse[0].ChangedBlue.Length == 2); Assert.IsTrue(res.ChangeQueryResponse[0].ChangedBlue[0].Any[0].OuterXml.Equals( @"<note Id=""724334d8-dbc6-45db-b808-d6dbdc09a789"" ChangeNumber=""2""><title>Test2</title><description>asdf</description></note>")); Assert.IsTrue(res.ChangeQueryResponse[0].ChangedBlue[1].Any[0].OuterXml.Equals( @"<note Id=""a9df1410-69a0-4be3-ab91-c017f6a44b58"" ChangeNumber=""3"" priority=""1""><title>Test3</title><description>asdf</description></note>")); } [Test] public void Query_ChangeQueryFailedTooManyNodes() { QueryRequestType req = new QueryRequestType(); ChangeQueryType q = new ChangeQueryType(); q.BaseChangeNumber = "2"; q.Select = "/notes/note"; req.ChangeQuery = new ChangeQueryType[] { q }; QueryResponseType res = GetXmlStore().Query(GetSubject(), req); Assert.IsTrue("2".Equals(res.ChangeQueryResponse[0].BaseChangeNumber)); Assert.IsTrue(res.ChangeQueryResponse[0].Status == ResponseStatus.Failure); Assert.IsTrue(res.ChangeQueryResponse[0].ChangedBlue.Length == 0); Assert.IsTrue(res.ChangeQueryResponse[0].DeletedBlue.Length == 0); } #endregion [Test] public void SerializeTest() { RoleListType rl = new RoleListType(); RoleType r1 = new RoleType(); r1.Subject = new SubjectType(); r1.Subject.UserId = "unittest-testiqid"; r1.RoleTemplateRef = "rt0"; r1.ScopeRef = "1"; RoleType r2 = new RoleType(); r2.Subject = new SubjectType(); r2.Subject.UserId = "unittest-testiqid2"; r2.RoleTemplateRef = "rt1"; r2.ScopeRef = "1"; rl.Role = new RoleType[] { r1, r2 }; /* RoleListScopeType rls = new RoleListScopeType(); rls.Id = "1"; rls.Shape = new Services.ShapeType(); rls.Shape.Base = ShapeTypeBase.T; rls.Shape.BaseSpecified = true; rl.Scope = new RoleListScopeType[] { rls }; */ StringWriter buffer = new StringWriter(); XmlSerializer serializer = new XmlSerializer(typeof(RoleListType)); serializer.Serialize(buffer, rl); Console.Out.Write(buffer.ToString()); } } }
#region Copyright notice and license // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Diagnostics; using System.Runtime.InteropServices; using Grpc.Core; using Grpc.Core.Utils; using Grpc.Core.Profiling; namespace Grpc.Core.Internal { /// <summary> /// grpc_call from <c>grpc/grpc.h</c> /// </summary> internal class CallSafeHandle : SafeHandleZeroIsInvalid, INativeCall { public static readonly CallSafeHandle NullInstance = new CallSafeHandle(); const uint GRPC_WRITE_BUFFER_HINT = 1; CompletionRegistry completionRegistry; [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_cancel(CallSafeHandle call); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_cancel_with_status(CallSafeHandle call, StatusCode status, string description); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_start_unary(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_start_client_streaming(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_start_server_streaming(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_start_duplex_streaming(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_send_message(CallSafeHandle call, BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len, WriteFlags writeFlags, bool sendEmptyInitialMetadata); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_send_close_from_client(CallSafeHandle call, BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_send_status_from_server(CallSafeHandle call, BatchContextSafeHandle ctx, StatusCode statusCode, string statusMessage, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_recv_message(CallSafeHandle call, BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_recv_initial_metadata(CallSafeHandle call, BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_start_serverside(CallSafeHandle call, BatchContextSafeHandle ctx); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_send_initial_metadata(CallSafeHandle call, BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray); [DllImport("grpc_csharp_ext.dll")] static extern GRPCCallError grpcsharp_call_set_credentials(CallSafeHandle call, CallCredentialsSafeHandle credentials); [DllImport("grpc_csharp_ext.dll")] static extern CStringSafeHandle grpcsharp_call_get_peer(CallSafeHandle call); [DllImport("grpc_csharp_ext.dll")] static extern void grpcsharp_call_destroy(IntPtr call); private CallSafeHandle() { } public void SetCompletionRegistry(CompletionRegistry completionRegistry) { this.completionRegistry = completionRegistry; } public void SetCredentials(CallCredentialsSafeHandle credentials) { grpcsharp_call_set_credentials(this, credentials).CheckOk(); } public void StartUnary(UnaryResponseClientHandler callback, byte[] payload, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient(), context.GetReceivedMessage(), context.GetReceivedInitialMetadata())); grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray, writeFlags) .CheckOk(); } public void StartUnary(BatchContextSafeHandle ctx, byte[] payload, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags) { using (Profilers.ForCurrentThread().NewScope("CallSafeHandle.StartUnary")) { grpcsharp_call_start_unary(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray, writeFlags) .CheckOk(); } } public void StartClientStreaming(UnaryResponseClientHandler callback, MetadataArraySafeHandle metadataArray) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient(), context.GetReceivedMessage(), context.GetReceivedInitialMetadata())); grpcsharp_call_start_client_streaming(this, ctx, metadataArray).CheckOk(); } public void StartServerStreaming(ReceivedStatusOnClientHandler callback, byte[] payload, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient())); grpcsharp_call_start_server_streaming(this, ctx, payload, new UIntPtr((ulong)payload.Length), metadataArray, writeFlags).CheckOk(); } public void StartDuplexStreaming(ReceivedStatusOnClientHandler callback, MetadataArraySafeHandle metadataArray) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedStatusOnClient())); grpcsharp_call_start_duplex_streaming(this, ctx, metadataArray).CheckOk(); } public void StartSendMessage(SendCompletionHandler callback, byte[] payload, WriteFlags writeFlags, bool sendEmptyInitialMetadata) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success)); grpcsharp_call_send_message(this, ctx, payload, new UIntPtr((ulong)payload.Length), writeFlags, sendEmptyInitialMetadata).CheckOk(); } public void StartSendCloseFromClient(SendCompletionHandler callback) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success)); grpcsharp_call_send_close_from_client(this, ctx).CheckOk(); } public void StartSendStatusFromServer(SendCompletionHandler callback, Status status, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success)); grpcsharp_call_send_status_from_server(this, ctx, status.StatusCode, status.Detail, metadataArray, sendEmptyInitialMetadata).CheckOk(); } public void StartReceiveMessage(ReceivedMessageHandler callback) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedMessage())); grpcsharp_call_recv_message(this, ctx).CheckOk(); } public void StartReceiveInitialMetadata(ReceivedResponseHeadersHandler callback) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedInitialMetadata())); grpcsharp_call_recv_initial_metadata(this, ctx).CheckOk(); } public void StartServerSide(ReceivedCloseOnServerHandler callback) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success, context.GetReceivedCloseOnServerCancelled())); grpcsharp_call_start_serverside(this, ctx).CheckOk(); } public void StartSendInitialMetadata(SendCompletionHandler callback, MetadataArraySafeHandle metadataArray) { var ctx = BatchContextSafeHandle.Create(); completionRegistry.RegisterBatchCompletion(ctx, (success, context) => callback(success)); grpcsharp_call_send_initial_metadata(this, ctx, metadataArray).CheckOk(); } public void Cancel() { grpcsharp_call_cancel(this).CheckOk(); } public void CancelWithStatus(Status status) { grpcsharp_call_cancel_with_status(this, status.StatusCode, status.Detail).CheckOk(); } public string GetPeer() { using (var cstring = grpcsharp_call_get_peer(this)) { return cstring.GetValue(); } } protected override bool ReleaseHandle() { grpcsharp_call_destroy(handle); return true; } private static uint GetFlags(bool buffered) { return buffered ? 0 : GRPC_WRITE_BUFFER_HINT; } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using EncDef = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition; using EncDef_VFP = Microsoft.Zelig.TargetModel.ArmProcessor.EncodingDefinition_VFP; using InstructionSet = Microsoft.Zelig.TargetModel.ArmProcessor.InstructionSet; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Cfg = Microsoft.Zelig.Configuration.Environment; public class Profiler { public class AllocationEntry { // // State // public readonly CallEntry Context; public readonly ulong AbsoluteClockTicks; public readonly TS.TypeRepresentation Type; public readonly int ArraySize; // // Constructor Methods // internal AllocationEntry( CallEntry context , ulong absoluteClockTicks , TS.TypeRepresentation type , int arraySize ) { this.Context = context; this.Type = type; this.AbsoluteClockTicks = absoluteClockTicks; this.ArraySize = arraySize; } // // Helper Methods // //--// public int TotalByteSize { get { var vtbl = this.Type.VirtualTable; return (int)(vtbl.BaseSize + vtbl.ElementSize * this.ArraySize); } } } public class CallEntry { // // State // public readonly ThreadContext Owner; public readonly TS.MethodRepresentation Method; public readonly CallEntry Parent; public CallList Children; public AllocationList MemoryAllocations; public ulong AbsoluteClockCycles; public long InclusiveClockCycles; public long InclusiveWaitStates; internal ulong m_startCycles; internal ulong m_startWaitStates; internal bool m_visited; // // Constructor Methods // public CallEntry( ThreadContext tc , CallEntry parent , TS.MethodRepresentation method ) { this.Owner = tc; this.Method = method; this.Parent = parent; if(parent != null) { tc.Push( this ); } } // // Helper Methods // internal void AddSubCall( CallEntry en ) { var lst = this.Children; if(lst == null) { lst = new CallList(); this.Children = lst; } lst.Add( en ); } internal IEnumerable< CallEntry > EnumerateChildren() { var lst = this.Children; if(lst != null) { foreach(var en in lst) { yield return en; foreach(var enSub in en.EnumerateChildren()) { yield return enSub; } } } } internal void ResetVisitedFlag() { m_visited = false; var lst = this.Children; if(lst != null) { foreach(var en in lst) { en.ResetVisitedFlag(); } } } internal long ComputeExactInclusiveClockCycles() { if(m_visited) { return 0; } m_visited = true; long res = this.ExclusiveClockCycles; if(this.Children != null) { foreach(var sub in this.Children) { res += sub.ComputeExactInclusiveClockCycles(); } } return res; } internal long ComputeExactAllocatedBytes() { if(m_visited) { return 0; } m_visited = true; long res = this.ExclusiveAllocatedBytes; if(this.Children != null) { foreach(var sub in this.Children) { res += sub.ComputeExactAllocatedBytes(); } } return res; } // // Access Methods // public int Depth { get { int res = 0; var en = this; while((en = en.Parent) != null) { res++; } return res; } } public long ExclusiveClockCycles { get { long res = this.InclusiveClockCycles; if(this.Children != null) { foreach(var sub in this.Children) { res -= sub.InclusiveClockCycles; } } return res; } } public long ExclusiveWaitStates { get { long res = this.InclusiveWaitStates; if(this.Children != null) { foreach(var sub in this.Children) { res -= sub.InclusiveWaitStates; } } return res; } } public long InclusiveAllocatedBytes { get { long total = this.ExclusiveAllocatedBytes; if(this.Children != null) { foreach(var sub in this.Children) { total += sub.InclusiveAllocatedBytes; } } return total; } } public long ExclusiveAllocatedBytes { get { long total = 0; int headerSize = this.Owner.m_owner.m_objectHeaderSize; if(this.MemoryAllocations != null) { foreach(var memAlloc in this.MemoryAllocations) { total += memAlloc.TotalByteSize + headerSize; } } return total; } } // // Debug Methods // public override string ToString() { return string.Format( "[Thread:{0}] {1}{2}: {3} clock cycles [{4} exclusive] - {5} bytes allocated", this.Owner.ManagedThreadId, new string( ' ', this.Depth + 1 ), this.Method.ToShortString(), this.InclusiveClockCycles, this.ExclusiveClockCycles, this.InclusiveAllocatedBytes ); } } public class ThreadContext { // // State // internal readonly Profiler m_owner; private CallEntry m_activeEntry; public readonly int ManagedThreadId; public readonly ThreadStatus.Kind ThreadKind; public readonly CallEntry TopLevel; // // Constructor Methods // internal ThreadContext( Profiler owner , int id , ThreadStatus.Kind kind ) { m_owner = owner; this.ManagedThreadId = id; this.ThreadKind = kind; this.TopLevel = new CallEntry( this, null, null ); m_activeEntry = this.TopLevel; } // // Helper Methods // internal void Activate() { var perf = m_owner.m_svcPerf; if(perf != null) { ulong cycles = perf.ClockCycles; ulong waitStates = perf.WaitStates; for(var en = this.ActiveEntry; en != null; en = en.Parent) { en.m_startCycles = cycles; en.m_startWaitStates = waitStates; } } } internal void Deactivate() { var perf = m_owner.m_svcPerf; if(perf != null) { ulong cycles = perf.ClockCycles; ulong waitStates = perf.WaitStates; for(var en = this.ActiveEntry; en != null; en = en.Parent) { en.InclusiveClockCycles += (long)(cycles - en.m_startCycles ); en.InclusiveWaitStates += (long)(waitStates - en.m_startWaitStates); } } } internal void Push( CallEntry en ) { m_activeEntry.AddSubCall( en ); m_activeEntry = en; var perf = m_owner.m_svcPerf; if(perf != null) { ulong cycles = perf.ClockCycles; ulong waitStates = perf.WaitStates; en.AbsoluteClockCycles = cycles; en.m_startCycles = cycles; en.m_startWaitStates = waitStates; } } internal void Pop() { if(this.IsActive) { var en = m_activeEntry; m_activeEntry = en.Parent; var perf = m_owner.m_svcPerf; if(perf != null) { ulong cycles = perf.ClockCycles; ulong waitStates = perf.WaitStates; en.InclusiveClockCycles += (long)(cycles - en.m_startCycles ); en.InclusiveWaitStates += (long)(waitStates - en.m_startWaitStates); } } } internal void AddAllocation( TS.TypeRepresentation td , int arraySize ) { var perf = m_owner.m_svcPerf; ulong cycles = (perf != null) ? perf.ClockCycles : 0; //--// var en = this.ActiveEntry; var mat = en.MemoryAllocations; if(mat == null) { mat = new AllocationList(); en.MemoryAllocations = mat; } mat.Add( new AllocationEntry( en, cycles, td, arraySize ) ); } // // Access Methods // public CallEntry ActiveEntry { get { return m_activeEntry; } } public bool IsActive { get { return this.ActiveEntry != this.TopLevel; } } } //--// public class CallList : GrowOnlyList< CallEntry > { // // Helper Methods // public long ComputeExactInclusiveClockCycles() { foreach(var en in this) { en.ResetVisitedFlag(); } long res = 0; foreach(var en in this) { res += en.ComputeExactInclusiveClockCycles(); } return res; } public long ComputeExactAllocatedBytes() { foreach(var en in this) { en.ResetVisitedFlag(); } long res = 0; foreach(var en in this) { res += en.ComputeExactAllocatedBytes(); } return res; } // // Access Methods // public long ExclusiveClockCycles { get { long res = 0; foreach(var en in this) { res += en.ExclusiveClockCycles; } return res; } } public long InclusiveClockCycles { get { long res = 0; foreach(var en in this) { res += en.InclusiveClockCycles; } return res; } } public long AllocatedBytes { get { long res = 0; foreach(var en in this) { res += en.ExclusiveAllocatedBytes; } return res; } } } public class CallsByType : GrowOnlyHashTable< TS.TypeRepresentation, CallList > { // // Helper Method // internal void AddCall( CallEntry en ) { var td = en.Method.OwnerType; CallList coll; if(this.TryGetValue( td, out coll ) == false) { coll = new CallList(); this[td] = coll; } coll.Add( en ); } // // Access Methods // public long ExclusiveClockCycles { get { long res = 0; foreach(var md in this.Keys) { res += this[md].ExclusiveClockCycles; } return res; } } public long InclusiveClockCycles { get { long res = 0; foreach(var md in this.Keys) { res += this[md].InclusiveClockCycles; } return res; } } public long AllocatedBytes { get { long res = 0; foreach(var md in this.Keys) { res += this[md].AllocatedBytes; } return res; } } } public class CallsByMethod : GrowOnlyHashTable< TS.MethodRepresentation, CallList > { // // Helper Method // internal void AddCall( CallEntry en ) { var md = en.Method; CallList coll; if(this.TryGetValue( md, out coll ) == false) { coll = new CallList(); this[md] = coll; } coll.Add( en ); } // // Access Methods // public long TotalCalls { get { long res = 0; foreach(var key in this.Keys) { res += this[key].Count; } return res; } } public long ExclusiveClockCycles { get { long res = 0; foreach(var key in this.Keys) { res += this[key].ExclusiveClockCycles; } return res; } } public long InclusiveClockCycles { get { long res = 0; foreach(var key in this.Keys) { res += this[key].InclusiveClockCycles; } return res; } } public long AllocatedBytes { get { long res = 0; foreach(var td in this.Keys) { res += this[td].AllocatedBytes; } return res; } } } public class CallsByTypeAndMethod : GrowOnlyHashTable< TS.TypeRepresentation, CallsByMethod > { // // Helper Method // internal void AddCall( CallEntry en ) { var td = en.Method.OwnerType; CallsByMethod coll; if(this.TryGetValue( td, out coll ) == false) { coll = new CallsByMethod(); this[td] = coll; } coll.AddCall( en ); } } public class Callers : GrowOnlyHashTable< TS.MethodRepresentation, CallsByMethod > { // // Helper Method // internal void AddCall( CallEntry en ) { var md = en.Method; if(md != null) { var enParent = en.Parent; if(enParent != null && enParent.Method != null) { CallsByMethod coll; if(this.TryGetValue( md, out coll ) == false) { coll = new CallsByMethod(); this[md] = coll; } coll.AddCall( enParent ); } } } } public class Callees : GrowOnlyHashTable< TS.MethodRepresentation, CallsByMethod > { // // Helper Method // internal void AddCall( CallEntry en ) { if(en.Children != null) { var md = en.Method; if(md != null) { CallsByMethod coll; if(this.TryGetValue( md, out coll ) == false) { coll = new CallsByMethod(); this[md] = coll; } foreach(var child in en.Children) { coll.AddCall( child ); } } } } } public class CallsByMethodAndType : GrowOnlyHashTable< TS.MethodRepresentation, CallsByType > { // // Helper Method // internal void AddCall( CallEntry en ) { var md = en.Method; CallsByType coll; if(this.TryGetValue( md, out coll ) == false) { coll = new CallsByType(); this[md] = coll; } coll.AddCall( en ); } } //--// public class AllocationList : GrowOnlyList< AllocationEntry > { // // Access Methods // public long AllocatedBytes { get { long res = 0; foreach(var mem in this) { res += mem.TotalByteSize; } return res; } } public long AllocatedInstances { get { return this.Count; } } } public class AllocationsByType : GrowOnlyHashTable< TS.TypeRepresentation, AllocationList > { // // Helper Method // internal void AddAllocation( AllocationEntry en ) { var td = en.Type; AllocationList coll; if(this.TryGetValue( td, out coll ) == false) { coll = new AllocationList(); this[td] = coll; } coll.Add( en ); } // // Access Methods // public long AllocatedBytes { get { long res = 0; foreach(var td in this.Keys) { res += this[td].AllocatedBytes; } return res; } } } public class AllocationsByMethod : GrowOnlyHashTable< TS.MethodRepresentation, AllocationList > { // // Helper Method // internal void AddAllocation( AllocationEntry en ) { var md = en.Context.Method; AllocationList coll; if(this.TryGetValue( md, out coll ) == false) { coll = new AllocationList(); this[md] = coll; } coll.Add( en ); } // // Access Methods // public long AllocatedBytes { get { long res = 0; foreach(var md in this.Keys) { res += this[md].AllocatedBytes; } return res; } } public long AllocatedInstances { get { long res = 0; foreach(var md in this.Keys) { res += this[md].AllocatedInstances; } return res; } } } public class AllocationsByTypeAndMethod : GrowOnlyHashTable< TS.TypeRepresentation, AllocationsByMethod > { // // Helper Method // internal void AddAllocation( AllocationEntry en ) { var td = en.Type; AllocationsByMethod coll; if(this.TryGetValue( td, out coll ) == false) { coll = new AllocationsByMethod(); this[td] = coll; } coll.AddAllocation( en ); } // // Access Methods // public long AllocatedBytes { get { long res = 0; foreach(var td in this.Keys) { res += this[td].AllocatedBytes; } return res; } } public long AllocatedInstances { get { long res = 0; foreach(var td in this.Keys) { res += this[td].AllocatedInstances; } return res; } } } //--// // // State // private MemoryDelta m_memDelta; private Emulation.Hosting.Interop m_svcInterop; private Emulation.Hosting.ProcessorPerformance m_svcPerf; private Emulation.Hosting.ProcessorStatus m_svcStatus; private Dictionary< int, ThreadContext > m_threads; private ThreadContext m_activeContext; private List< Emulation.Hosting.Interop.Registration > m_interopsForCalls; private List< Emulation.Hosting.Interop.Registration > m_interopsForAllocations; private bool m_fCollectAllocationData; private bool m_fAttachedForCalls; private bool m_fAttachedForAllocations; private int m_objectHeaderSize; // // Constructor Methods // public Profiler( MemoryDelta memDelta ) { m_memDelta = memDelta; m_threads = new Dictionary< int, ThreadContext >(); m_interopsForCalls = new List< Emulation.Hosting.Interop.Registration >(); m_interopsForAllocations = new List< Emulation.Hosting.Interop.Registration >(); m_objectHeaderSize = (int)memDelta.ImageInformation.TypeSystem.WellKnownTypes.Microsoft_Zelig_Runtime_ObjectHeader.Size; } // // Helper Methods // internal IEnumerable< CallEntry > EnumerateCalls() { foreach(var tc in m_threads.Values) { foreach(var en in tc.TopLevel.EnumerateChildren()) { yield return en; } } } public CallsByTypeAndMethod GetCallsByType() { var res = new CallsByTypeAndMethod(); foreach(var en in this.EnumerateCalls()) { res.AddCall( en ); } return res; } public CallsByMethodAndType GetCallsByMethod() { var res = new CallsByMethodAndType(); foreach(var en in this.EnumerateCalls()) { res.AddCall( en ); } return res; } public void GetCallersAndCallees( out Callers callers , out Callees callees ) { callers = new Callers(); callees = new Callees(); foreach(var en in this.EnumerateCalls()) { callers.AddCall( en ); callees.AddCall( en ); } } public AllocationsByType GetAllocationsByType() { var res = new AllocationsByType(); foreach(var en in this.EnumerateCalls()) { if(en.MemoryAllocations != null) { foreach(var mem in en.MemoryAllocations) { res.AddAllocation( mem ); } } } return res; } public AllocationsByMethod GetAllocationsByMethod() { var res = new AllocationsByMethod(); foreach(var en in this.EnumerateCalls()) { if(en.MemoryAllocations != null) { foreach(var mem in en.MemoryAllocations) { res.AddAllocation( mem ); } } } return res; } public AllocationsByTypeAndMethod GetAllocationsByTypeAndMethod() { var res = new AllocationsByTypeAndMethod(); foreach(var en in this.EnumerateCalls()) { if(en.MemoryAllocations != null) { foreach(var mem in en.MemoryAllocations) { res.AddAllocation( mem ); } } } return res; } //--// public void Attach() { if(m_fAttachedForCalls == false) { var host = m_memDelta.Host; if(host.GetHostingService( out m_svcInterop ) && host.GetHostingService( out m_svcStatus ) ) { host.GetHostingService( out m_svcPerf ); Attach_Calls(); if(m_fCollectAllocationData) { Attach_Allocations(); } SwitchToNewThread(); } m_fAttachedForCalls = true; } } private void Attach_Calls() { m_svcStatus.NotifyOnExternalProgramFlowChange += Unwind; m_memDelta.ImageInformation.ImageBuilder.EnumerateImageAnnotations( an => { if(an.Target is Runtime.ActivationRecordEvents) { switch((Runtime.ActivationRecordEvents)an.Target) { case Runtime.ActivationRecordEvents.Constructing: AttachProfiler_Enter( an ); break; case Runtime.ActivationRecordEvents.ReturnToCaller: AttachProfiler_Exit( an ); break; case Runtime.ActivationRecordEvents.ReturnFromException: AttachProfiler_ExitFromException( an ); break; case Runtime.ActivationRecordEvents.LongJump: AttachProfiler_LongJump( an ); break; } } return true; } ); } private void Attach_Allocations() { if(m_fAttachedForAllocations == false) { var ts = m_memDelta.ImageInformation.TypeSystem; if(ts != null) { var wkm = ts.WellKnownMethods; SetInteropForVirtualMethod( ts, wkm.TypeSystemManager_AllocateObject, delegate() { RecordAllocation_Object( EncDef.c_register_r1 ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); SetInteropForVirtualMethod( ts, wkm.TypeSystemManager_AllocateArray, delegate() { RecordAllocation_Array( EncDef.c_register_r1, EncDef.c_register_r2 ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); SetInteropForVirtualMethod( ts, wkm.TypeSystemManager_AllocateArrayNoClear, delegate() { RecordAllocation_Array( EncDef.c_register_r1, EncDef.c_register_r2 ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); SetInteropForVirtualMethod( ts, wkm.TypeSystemManager_AllocateString, delegate() { RecordAllocation_Array( EncDef.c_register_r1, EncDef.c_register_r2 ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); } m_fAttachedForAllocations = true; } } private void RecordAllocation_Object( uint encodingVTable ) { var td = ExtractType( encodingVTable ); if(td != null) { m_activeContext.AddAllocation( td, 0 ); } } private void RecordAllocation_Array( uint encodingVTable , uint encodingLength ) { var td = ExtractType( encodingVTable ); if(td != null) { var bb = ReadRegister( encodingLength ); if(bb != null) { m_activeContext.AddAllocation( td, (int)bb.ReadUInt32( 0 ) ); } } } //--// public void Detach() { Detach_Allocations(); Detach_Calls(); if(m_activeContext != null) { m_activeContext.Deactivate(); m_activeContext = null; } } private void Detach_Calls() { if(m_fAttachedForCalls) { m_svcStatus.NotifyOnExternalProgramFlowChange -= Unwind; foreach(var reg in m_interopsForCalls) { m_svcInterop.RemoveInterop( reg ); } m_interopsForCalls.Clear(); m_fAttachedForCalls = false; } } private void Detach_Allocations() { if(m_fAttachedForAllocations) { foreach(var reg in m_interopsForAllocations) { m_svcInterop.RemoveInterop( reg ); } m_interopsForAllocations.Clear(); m_fAttachedForAllocations = false; } } //--// private TS.TypeRepresentation ExtractType( uint encoding ) { var bb = ReadRegister( EncDef.c_register_r1 ); if(bb != null) { uint vTablePtr = bb.ReadUInt32( 0 ); return m_memDelta.ImageInformation.GetTypeFromVirtualTable( vTablePtr ); } return null; } private Emulation.Hosting.BinaryBlob ReadRegister( uint encoding ) { return m_svcStatus.GetRegister( m_memDelta.ImageInformation.TypeSystem.PlatformAbstraction.GetRegisterForEncoding( encoding ) ); } private void SetInteropForCall( uint pc , bool fPostProcessing , Emulation.Hosting.Interop.Callback ftn ) { m_interopsForCalls.Add( m_svcInterop.SetInterop( pc, true, fPostProcessing, ftn ) ); } private void SetInteropForVirtualMethod( IR.TypeSystemForCodeTransformation ts , TS.MethodRepresentation md , Emulation.Hosting.Interop.Callback ftn ) { if(md is TS.VirtualMethodRepresentation) { for(TS.TypeRepresentation td = ts.FindSingleConcreteImplementation( md.OwnerType ); td != null; td = td.Extends) { TS.MethodRepresentation md2 = td.FindMatch( md, null ); if(md2 != null) { md = md2; break; } } } if(md != null) { IR.ImageBuilders.SequentialRegion reg = m_memDelta.ImageInformation.ResolveMethodToRegion( md ); if(reg != null) { m_interopsForAllocations.Add( m_svcInterop.SetInterop( reg.ExternalAddress, true, false, ftn ) ); } } } private CallEntry CreateNewEntry( TS.MethodRepresentation md ) { var en = new CallEntry( m_activeContext, m_activeContext.ActiveEntry, md ); return en; } private TS.MethodRepresentation GetMethod( IR.ImageBuilders.ImageAnnotation an ) { var bb = (IR.BasicBlock)an.Region.Context; return bb.Owner.Method; } private ThreadStatus AnalyzeStackFrame( out List< ThreadStatus > lst ) { StopTiming(); lst = new List< ThreadStatus >(); m_memDelta.FlushCache(); var ts = ThreadStatus.Analyze( lst, m_memDelta, null ); RestartTiming(); return ts; } private void SwitchToNewThread() { List< ThreadStatus > lst; var ts = AnalyzeStackFrame( out lst ); //--// if(m_activeContext != null) { m_activeContext.Deactivate(); } var tc = FindThread( ts ); if(tc == null) { int id = ts.ManagedThreadId; tc = new ThreadContext( this, id, ts.ThreadKind ); m_threads[id] = tc; } m_activeContext = tc; tc.Activate(); if(tc.IsActive == false) { var md = ts.TopMethod; // // If we switch to the beginning of a method, we don't need to create an entry, it will be created as part of the normal interop sequence. // if(ts.ProgramCounter != m_memDelta.ImageInformation.ResolveMethodToRegion( md ).ExternalAddress) { CreateNewEntry( ts.TopMethod ); } } } private void Unwind() { List< ThreadStatus > lst; var ts = AnalyzeStackFrame( out lst ); var md = ts.TopMethod; while(true) { var en = m_activeContext.ActiveEntry; if(en == m_activeContext.TopLevel) { break; } if(en.Method == md) { break; } m_activeContext.Pop(); } if(m_activeContext.IsActive == false) { CreateNewEntry( md ); } } private ThreadContext FindThread( ThreadStatus ts ) { ThreadContext res; m_threads.TryGetValue( ts.ManagedThreadId, out res ); return res; } private void StopTiming() { if(m_svcPerf != null) { m_svcPerf.SuspendTimingUpdates(); } } private void RestartTiming() { if(m_svcPerf != null) { m_svcPerf.ResumeTimingUpdates(); } } //--// private void AttachProfiler_Enter( IR.ImageBuilders.ImageAnnotation an ) { var md = GetMethod( an ); switch(m_memDelta.ImageInformation.TypeSystem.ExtractHardwareExceptionSettingsForMethod( md )) { case Runtime.HardwareException.UndefinedInstruction: case Runtime.HardwareException.PrefetchAbort : case Runtime.HardwareException.DataAbort : case Runtime.HardwareException.Interrupt : case Runtime.HardwareException.FastInterrupt : case Runtime.HardwareException.SoftwareInterrupt : SetInteropForCall( an.InsertionAddress, false, delegate() { SwitchToNewThread(); CreateNewEntry( md ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); break; default: SetInteropForCall( an.InsertionAddress, false, delegate() { CreateNewEntry( md ); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); break; } } private void AttachProfiler_Exit( IR.ImageBuilders.ImageAnnotation an ) { SetInteropForCall( an.InsertionAddress, true, delegate() { m_activeContext.Pop(); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); } private void AttachProfiler_ExitFromException( IR.ImageBuilders.ImageAnnotation an ) { SetInteropForCall( an.InsertionAddress, true, delegate() { m_activeContext.Pop(); SwitchToNewThread(); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); } private void AttachProfiler_LongJump( IR.ImageBuilders.ImageAnnotation an ) { SetInteropForCall( an.InsertionAddress, true, delegate() { m_activeContext.Pop(); Unwind(); return Emulation.Hosting.Interop.CallbackResponse.DoNothing; } ); } // // Access Methods // public bool IsActive { get { return m_fAttachedForCalls; } } public bool CollectAllocationData { get { return m_fCollectAllocationData; } set { if(m_fCollectAllocationData != value) { m_fCollectAllocationData = value; if(m_fAttachedForCalls) { if(value) { Attach_Allocations(); } else { Detach_Allocations(); } } } } } public ThreadContext[] Threads { get { var values = m_threads.Values; var res = new ThreadContext[values.Count]; m_threads.Values.CopyTo( res, 0 ); return res; } } } }
/* * 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.Reflection; using System.Text; using System.Xml; using System.Collections.Generic; using System.IO; using Nini.Config; using OpenSim.Framework; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Handlers.Base; using log4net; using OpenMetaverse; namespace OpenSim.Groups { public class HGGroupsServiceRobustConnector : ServiceConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private HGGroupsService m_GroupsService; private string m_ConfigName = "Groups"; // Called by Robust shell public HGGroupsServiceRobustConnector(IConfigSource config, IHttpServer server, string configName) : this(config, server, configName, null, null) { } // Called by the sim-bound module public HGGroupsServiceRobustConnector(IConfigSource config, IHttpServer server, string configName, IOfflineIMService im, IUserAccountService users) : base(config, server, configName) { if (configName != String.Empty) m_ConfigName = configName; m_log.DebugFormat("[Groups.RobustHGConnector]: Starting with config name {0}", m_ConfigName); string homeURI = Util.GetConfigVarFromSections<string>(config, "HomeURI", new string[] { "Startup", "Hypergrid", m_ConfigName}, string.Empty); if (homeURI == string.Empty) throw new Exception(String.Format("[Groups.RobustHGConnector]: please provide the HomeURI [Startup] or in section {0}", m_ConfigName)); IConfig cnf = config.Configs[m_ConfigName]; if (cnf == null) throw new Exception(String.Format("[Groups.RobustHGConnector]: {0} section does not exist", m_ConfigName)); if (im == null) { string imDll = cnf.GetString("OfflineIMService", string.Empty); if (imDll == string.Empty) throw new Exception(String.Format("[Groups.RobustHGConnector]: please provide OfflineIMService in section {0}", m_ConfigName)); Object[] args = new Object[] { config }; im = ServerUtils.LoadPlugin<IOfflineIMService>(imDll, args); } if (users == null) { string usersDll = cnf.GetString("UserAccountService", string.Empty); if (usersDll == string.Empty) throw new Exception(String.Format("[Groups.RobustHGConnector]: please provide UserAccountService in section {0}", m_ConfigName)); Object[] args = new Object[] { config }; users = ServerUtils.LoadPlugin<IUserAccountService>(usersDll, args); } m_GroupsService = new HGGroupsService(config, im, users, homeURI); server.AddStreamHandler(new HGGroupsServicePostHandler(m_GroupsService)); } } public class HGGroupsServicePostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private HGGroupsService m_GroupsService; public HGGroupsServicePostHandler(HGGroupsService service) : base("POST", "/hg-groups") { m_GroupsService = service; } protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); string method = request["METHOD"].ToString(); request.Remove("METHOD"); m_log.DebugFormat("[Groups.RobustHGConnector]: {0}", method); switch (method) { case "POSTGROUP": return HandleAddGroupProxy(request); case "REMOVEAGENTFROMGROUP": return HandleRemoveAgentFromGroup(request); case "GETGROUP": return HandleGetGroup(request); case "ADDNOTICE": return HandleAddNotice(request); case "VERIFYNOTICE": return HandleVerifyNotice(request); case "GETGROUPMEMBERS": return HandleGetGroupMembers(request); case "GETGROUPROLES": return HandleGetGroupRoles(request); case "GETROLEMEMBERS": return HandleGetRoleMembers(request); } m_log.DebugFormat("[Groups.RobustHGConnector]: unknown method request: {0}", method); } catch (Exception e) { m_log.Error(string.Format("[Groups.RobustHGConnector]: Exception {0} ", e.Message), e); } return FailureResult(); } byte[] HandleAddGroupProxy(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("GroupID") || !request.ContainsKey("AgentID") || !request.ContainsKey("AccessToken") || !request.ContainsKey("Location")) NullResult(result, "Bad network data"); else { string RequestingAgentID = request["RequestingAgentID"].ToString(); string agentID = request["AgentID"].ToString(); UUID groupID = new UUID(request["GroupID"].ToString()); string accessToken = request["AccessToken"].ToString(); string location = request["Location"].ToString(); string name = string.Empty; if (request.ContainsKey("Name")) name = request["Name"].ToString(); string reason = string.Empty; bool success = m_GroupsService.CreateGroupProxy(RequestingAgentID, agentID, accessToken, groupID, location, name, out reason); result["REASON"] = reason; result["RESULT"] = success.ToString(); } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleRemoveAgentFromGroup(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("AccessToken") || !request.ContainsKey("AgentID") || !request.ContainsKey("GroupID")) NullResult(result, "Bad network data"); else { UUID groupID = new UUID(request["GroupID"].ToString()); string agentID = request["AgentID"].ToString(); string token = request["AccessToken"].ToString(); if (!m_GroupsService.RemoveAgentFromGroup(agentID, agentID, groupID, token)) NullResult(result, "Internal error"); else result["RESULT"] = "true"; } //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(ServerUtils.BuildXmlResponse(result)); } byte[] HandleGetGroup(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("AccessToken")) NullResult(result, "Bad network data"); else { string RequestingAgentID = request["RequestingAgentID"].ToString(); string token = request["AccessToken"].ToString(); UUID groupID = UUID.Zero; string groupName = string.Empty; if (request.ContainsKey("GroupID")) groupID = new UUID(request["GroupID"].ToString()); if (request.ContainsKey("Name")) groupName = request["Name"].ToString(); ExtendedGroupRecord grec = m_GroupsService.GetGroupRecord(RequestingAgentID, groupID, groupName, token); if (grec == null) NullResult(result, "Group not found"); else result["RESULT"] = GroupsDataUtils.GroupRecord(grec); } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetGroupMembers(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("GroupID") || !request.ContainsKey("AccessToken")) NullResult(result, "Bad network data"); else { UUID groupID = new UUID(request["GroupID"].ToString()); string requestingAgentID = request["RequestingAgentID"].ToString(); string token = request["AccessToken"].ToString(); List<ExtendedGroupMembersData> members = m_GroupsService.GetGroupMembers(requestingAgentID, groupID, token); if (members == null || (members != null && members.Count == 0)) { NullResult(result, "No members"); } else { Dictionary<string, object> dict = new Dictionary<string, object>(); int i = 0; foreach (ExtendedGroupMembersData m in members) { dict["m-" + i++] = GroupsDataUtils.GroupMembersData(m); } result["RESULT"] = dict; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetGroupRoles(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("GroupID") || !request.ContainsKey("AccessToken")) NullResult(result, "Bad network data"); else { UUID groupID = new UUID(request["GroupID"].ToString()); string requestingAgentID = request["RequestingAgentID"].ToString(); string token = request["AccessToken"].ToString(); List<GroupRolesData> roles = m_GroupsService.GetGroupRoles(requestingAgentID, groupID, token); if (roles == null || (roles != null && roles.Count == 0)) { NullResult(result, "No members"); } else { Dictionary<string, object> dict = new Dictionary<string, object>(); int i = 0; foreach (GroupRolesData r in roles) dict["r-" + i++] = GroupsDataUtils.GroupRolesData(r); result["RESULT"] = dict; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetRoleMembers(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("GroupID") || !request.ContainsKey("AccessToken")) NullResult(result, "Bad network data"); else { UUID groupID = new UUID(request["GroupID"].ToString()); string requestingAgentID = request["RequestingAgentID"].ToString(); string token = request["AccessToken"].ToString(); List<ExtendedGroupRoleMembersData> rmembers = m_GroupsService.GetGroupRoleMembers(requestingAgentID, groupID, token); if (rmembers == null || (rmembers != null && rmembers.Count == 0)) { NullResult(result, "No members"); } else { Dictionary<string, object> dict = new Dictionary<string, object>(); int i = 0; foreach (ExtendedGroupRoleMembersData rm in rmembers) dict["rm-" + i++] = GroupsDataUtils.GroupRoleMembersData(rm); result["RESULT"] = dict; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleAddNotice(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("GroupID") || !request.ContainsKey("NoticeID") || !request.ContainsKey("FromName") || !request.ContainsKey("Subject") || !request.ContainsKey("Message") || !request.ContainsKey("HasAttachment")) NullResult(result, "Bad network data"); else { bool hasAtt = bool.Parse(request["HasAttachment"].ToString()); byte attType = 0; string attName = string.Empty; string attOwner = string.Empty; UUID attItem = UUID.Zero; if (request.ContainsKey("AttachmentType")) attType = byte.Parse(request["AttachmentType"].ToString()); if (request.ContainsKey("AttachmentName")) attName = request["AttachmentType"].ToString(); if (request.ContainsKey("AttachmentItemID")) attItem = new UUID(request["AttachmentItemID"].ToString()); if (request.ContainsKey("AttachmentOwnerID")) attOwner = request["AttachmentOwnerID"].ToString(); bool success = m_GroupsService.AddNotice(request["RequestingAgentID"].ToString(), new UUID(request["GroupID"].ToString()), new UUID(request["NoticeID"].ToString()), request["FromName"].ToString(), request["Subject"].ToString(), request["Message"].ToString(), hasAtt, attType, attName, attItem, attOwner); result["RESULT"] = success.ToString(); } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleVerifyNotice(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); if (!request.ContainsKey("NoticeID") || !request.ContainsKey("GroupID")) NullResult(result, "Bad network data"); else { UUID noticeID = new UUID(request["NoticeID"].ToString()); UUID groupID = new UUID(request["GroupID"].ToString()); bool success = m_GroupsService.VerifyNotice(noticeID, groupID); //m_log.DebugFormat("[XXX]: VerifyNotice returned {0}", success); result["RESULT"] = success.ToString(); } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } // // // // // #region Helpers private void NullResult(Dictionary<string, object> result, string reason) { result["RESULT"] = "NULL"; result["REASON"] = reason; } private byte[] FailureResult() { Dictionary<string, object> result = new Dictionary<string, object>(); NullResult(result, "Unknown method"); string xmlString = ServerUtils.BuildXmlResponse(result); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } #endregion } }
#region Usings using System; using System.IO; using System.Text; using System.Text.RegularExpressions; #endregion namespace AT.MIN { public static class Tools { #region Public Methods #region IsNumericType /// <summary> /// Determines whether the specified value is of numeric type. /// </summary> /// <param name="o">The object to check.</param> /// <returns> /// <c>true</c> if o is a numeric type; otherwise, <c>false</c>. /// </returns> public static bool IsNumericType( object o ) { return ( o is byte || o is sbyte || o is short || o is ushort || o is int || o is uint || o is long || o is ulong || o is float || o is double || o is decimal ); } #endregion #region IsPositive /// <summary> /// Determines whether the specified value is positive. /// </summary> /// <param name="Value">The value.</param> /// <param name="ZeroIsPositive">if set to <c>true</c> treats 0 as positive.</param> /// <returns> /// <c>true</c> if the specified value is positive; otherwise, <c>false</c>. /// </returns> public static bool IsPositive( object Value, bool ZeroIsPositive ) { switch ( Type.GetTypeCode( Value.GetType() ) ) { case TypeCode.SByte: return ( ZeroIsPositive ? (sbyte)Value >= 0 : (sbyte)Value > 0 ); case TypeCode.Int16: return ( ZeroIsPositive ? (short)Value >= 0 : (short)Value > 0 ); case TypeCode.Int32: return ( ZeroIsPositive ? (int)Value >= 0 : (int)Value > 0 ); case TypeCode.Int64: return ( ZeroIsPositive ? (long)Value >= 0 : (long)Value > 0 ); case TypeCode.Single: return ( ZeroIsPositive ? (float)Value >= 0 : (float)Value > 0 ); case TypeCode.Double: return ( ZeroIsPositive ? (double)Value >= 0 : (double)Value > 0 ); case TypeCode.Decimal: return ( ZeroIsPositive ? (decimal)Value >= 0 : (decimal)Value > 0 ); case TypeCode.Byte: return ( ZeroIsPositive ? true : (byte)Value > 0 ); case TypeCode.UInt16: return ( ZeroIsPositive ? true : (ushort)Value > 0 ); case TypeCode.UInt32: return ( ZeroIsPositive ? true : (uint)Value > 0 ); case TypeCode.UInt64: return ( ZeroIsPositive ? true : (ulong)Value > 0 ); case TypeCode.Char: return ( ZeroIsPositive ? true : (char)Value != '\0' ); default: return false; } } #endregion #region ToUnsigned /// <summary> /// Converts the specified values boxed type to its correpsonding unsigned /// type. /// </summary> /// <param name="Value">The value.</param> /// <returns>A boxed numeric object whos type is unsigned.</returns> public static object ToUnsigned( object Value ) { switch ( Type.GetTypeCode( Value.GetType() ) ) { case TypeCode.SByte: return (byte)( (sbyte)Value ); case TypeCode.Int16: return (ushort)( (short)Value ); case TypeCode.Int32: return (uint)( (int)Value ); case TypeCode.Int64: return (ulong)( (long)Value ); case TypeCode.Byte: return Value; case TypeCode.UInt16: return Value; case TypeCode.UInt32: return Value; case TypeCode.UInt64: return Value; case TypeCode.Single: return (UInt32)( (float)Value ); case TypeCode.Double: return (ulong)( (double)Value ); case TypeCode.Decimal: return (ulong)( (decimal)Value ); default: return null; } } #endregion #region ToInteger /// <summary> /// Converts the specified values boxed type to its correpsonding integer /// type. /// </summary> /// <param name="Value">The value.</param> /// <returns>A boxed numeric object whos type is an integer type.</returns> public static object ToInteger( object Value, bool Round ) { switch ( Type.GetTypeCode( Value.GetType() ) ) { case TypeCode.SByte: return Value; case TypeCode.Int16: return Value; case TypeCode.Int32: return Value; case TypeCode.Int64: return Value; case TypeCode.Byte: return Value; case TypeCode.UInt16: return Value; case TypeCode.UInt32: return Value; case TypeCode.UInt64: return Value; case TypeCode.Single: return ( Round ? (int)Math.Round( (float)Value ) : (int)( (float)Value ) ); case TypeCode.Double: return ( Round ? (long)Math.Round( (double)Value ) : (long)( (double)Value ) ); case TypeCode.Decimal: return ( Round ? Math.Round( (decimal)Value ) : (decimal)Value ); default: return null; } } #endregion #region UnboxToLong public static long UnboxToLong( object Value, bool Round ) { switch ( Type.GetTypeCode( Value.GetType() ) ) { case TypeCode.SByte: return (long)( (sbyte)Value ); case TypeCode.Int16: return (long)( (short)Value ); case TypeCode.Int32: return (long)( (int)Value ); case TypeCode.Int64: return (long)Value; case TypeCode.Byte: return (long)( (byte)Value ); case TypeCode.UInt16: return (long)( (ushort)Value ); case TypeCode.UInt32: return (long)( (uint)Value ); case TypeCode.UInt64: return (long)( (ulong)Value ); case TypeCode.Single: return ( Round ? (long)Math.Round( (float)Value ) : (long)( (float)Value ) ); case TypeCode.Double: return ( Round ? (long)Math.Round( (double)Value ) : (long)( (double)Value ) ); case TypeCode.Decimal: return ( Round ? (long)Math.Round( (decimal)Value ) : (long)( (decimal)Value ) ); default: return 0; } } #endregion #region ReplaceMetaChars /// <summary> /// Replaces the string representations of meta chars with their corresponding /// character values. /// </summary> /// <param name="input">The input.</param> /// <returns>A string with all string meta chars are replaced</returns> public static string ReplaceMetaChars( string input ) { return Regex.Replace( input, @"(\\)(\d{3}|[^\d])?", new MatchEvaluator( ReplaceMetaCharsMatch ) ); } private static string ReplaceMetaCharsMatch( Match m ) { // convert octal quotes (like \040) if ( m.Groups[2].Length == 3 ) return Convert.ToChar( Convert.ToByte( m.Groups[2].Value, 8 ) ).ToString(); else { // convert all other special meta characters //TODO: \xhhh hex and possible dec !! switch ( m.Groups[2].Value ) { case "0": // null return "\0"; case "a": // alert (beep) return "\a"; case "b": // BS return "\b"; case "f": // FF return "\f"; case "v": // vertical tab return "\v"; case "r": // CR return "\r"; case "n": // LF return "\n"; case "t": // Tab return "\t"; default: // if neither an octal quote nor a special meta character // so just remove the backslash return m.Groups[2].Value; } } } #endregion #region printf public static void printf( string Format, params object[] Parameters ) { Console.Write( Tools.sprintf( Format, Parameters ) ); } #endregion #region fprintf public static void fprintf( TextWriter Destination, string Format, params object[] Parameters ) { Destination.Write( Tools.sprintf( Format, Parameters ) ); } internal static Regex r = new Regex(@"\%(\d*\$)?([\'\#\-\+ ]*)(\d*)(?:\.(\d+))?([hl])?([dioxXucsfeEgGpn%])"); #endregion #region sprintf public static string sprintf( string Format, params object[] Parameters ) { #region Variables StringBuilder f = new StringBuilder(); //Regex r = new Regex( @"\%(\d*\$)?([\'\#\-\+ ]*)(\d*)(?:\.(\d+))?([hl])?([dioxXucsfeEgGpn%])" ); //"%[parameter][flags][width][.precision][length]type" Match m = null; string w = String.Empty; int defaultParamIx = 0; int paramIx; object o = null; bool flagLeft2Right = false; bool flagAlternate = false; bool flagPositiveSign = false; bool flagPositiveSpace = false; bool flagZeroPadding = false; bool flagGroupThousands = false; int fieldLength = 0; int fieldPrecision = 0; char shortLongIndicator = '\0'; char formatSpecifier = '\0'; char paddingCharacter = ' '; #endregion // find all format parameters in format string f.Append( Format ); m = r.Match( f.ToString() ); while ( m.Success ) { #region parameter index paramIx = defaultParamIx; if ( m.Groups[1] != null && m.Groups[1].Value.Length > 0 ) { string val = m.Groups[1].Value.Substring( 0, m.Groups[1].Value.Length - 1 ); paramIx = Convert.ToInt32( val ) - 1; }; #endregion #region format flags // extract format flags flagAlternate = false; flagLeft2Right = false; flagPositiveSign = false; flagPositiveSpace = false; flagZeroPadding = false; flagGroupThousands = false; if ( m.Groups[2] != null && m.Groups[2].Value.Length > 0 ) { string flags = m.Groups[2].Value; flagAlternate = ( flags.IndexOf( '#' ) >= 0 ); flagLeft2Right = ( flags.IndexOf( '-' ) >= 0 ); flagPositiveSign = ( flags.IndexOf( '+' ) >= 0 ); flagPositiveSpace = ( flags.IndexOf( ' ' ) >= 0 ); flagGroupThousands = ( flags.IndexOf( '\'' ) >= 0 ); // positive + indicator overrides a // positive space character if ( flagPositiveSign && flagPositiveSpace ) flagPositiveSpace = false; } #endregion #region field length // extract field length and // pading character paddingCharacter = ' '; fieldLength = int.MinValue; if ( m.Groups[3] != null && m.Groups[3].Value.Length > 0 ) { fieldLength = Convert.ToInt32( m.Groups[3].Value ); flagZeroPadding = ( m.Groups[3].Value[0] == '0' ); } #endregion if ( flagZeroPadding ) paddingCharacter = '0'; // left2right allignment overrides zero padding if ( flagLeft2Right && flagZeroPadding ) { flagZeroPadding = false; paddingCharacter = ' '; } #region field precision // extract field precision fieldPrecision = int.MinValue; if ( m.Groups[4] != null && m.Groups[4].Value.Length > 0 ) fieldPrecision = Convert.ToInt32( m.Groups[4].Value ); #endregion #region short / long indicator // extract short / long indicator shortLongIndicator = Char.MinValue; if ( m.Groups[5] != null && m.Groups[5].Value.Length > 0 ) shortLongIndicator = m.Groups[5].Value[0]; #endregion #region format specifier // extract format formatSpecifier = Char.MinValue; if ( m.Groups[6] != null && m.Groups[6].Value.Length > 0 ) formatSpecifier = m.Groups[6].Value[0]; #endregion // default precision is 6 digits if none is specified except if ( fieldPrecision == int.MinValue && formatSpecifier != 's' && formatSpecifier != 'c' && Char.ToUpper( formatSpecifier ) != 'X' && formatSpecifier != 'o' ) fieldPrecision = 6; #region get next value parameter // get next value parameter and convert value parameter depending on short / long indicator if ( Parameters == null || paramIx >= Parameters.Length ) o = null; else { o = Parameters[paramIx]; if ( shortLongIndicator == 'h' ) { if ( o is int ) o = (short)( (int)o ); else if ( o is long ) o = (short)( (long)o ); else if ( o is uint ) o = (ushort)( (uint)o ); else if ( o is ulong ) o = (ushort)( (ulong)o ); } else if ( shortLongIndicator == 'l' ) { if ( o is short ) o = (long)( (short)o ); else if ( o is int ) o = (long)( (int)o ); else if ( o is ushort ) o = (ulong)( (ushort)o ); else if ( o is uint ) o = (ulong)( (uint)o ); } } #endregion // convert value parameters to a string depending on the formatSpecifier w = String.Empty; switch ( formatSpecifier ) { #region % - character case '%': // % character w = "%"; break; #endregion #region d - integer case 'd': // integer w = FormatNumber( ( flagGroupThousands ? "n" : "d" ), flagAlternate, fieldLength, int.MinValue, flagLeft2Right, flagPositiveSign, flagPositiveSpace, paddingCharacter, o ); defaultParamIx++; break; #endregion #region i - integer case 'i': // integer goto case 'd'; #endregion #region o - octal integer case 'o': // octal integer - no leading zero w = FormatOct( "o", flagAlternate, fieldLength, int.MinValue, flagLeft2Right, paddingCharacter, o ); defaultParamIx++; break; #endregion #region x - hex integer case 'x': // hex integer - no leading zero w = FormatHex( "x", flagAlternate, fieldLength, fieldPrecision, flagLeft2Right, paddingCharacter, o ); defaultParamIx++; break; #endregion #region X - hex integer case 'X': // same as x but with capital hex characters w = FormatHex( "X", flagAlternate, fieldLength, fieldPrecision, flagLeft2Right, paddingCharacter, o ); defaultParamIx++; break; #endregion #region u - unsigned integer case 'u': // unsigned integer w = FormatNumber( ( flagGroupThousands ? "n" : "d" ), flagAlternate, fieldLength, int.MinValue, flagLeft2Right, false, false, paddingCharacter, ToUnsigned( o ) ); defaultParamIx++; break; #endregion #region c - character case 'c': // character if ( IsNumericType( o ) ) w = Convert.ToChar( o ).ToString(); else if ( o is char ) w = ( (char)o ).ToString(); else if ( o is string && ( (string)o ).Length > 0 ) w = ( (string)o )[0].ToString(); defaultParamIx++; break; #endregion #region s - string case 's': // string string t = "{0" + ( fieldLength != int.MinValue ? "," + ( flagLeft2Right ? "-" : String.Empty ) + fieldLength.ToString() : String.Empty ) + ":s}"; w = o.ToString(); if ( fieldPrecision >= 0 ) w = w.Substring( 0, fieldPrecision ); if ( fieldLength != int.MinValue ) if ( flagLeft2Right ) w = w.PadRight( fieldLength, paddingCharacter ); else w = w.PadLeft( fieldLength, paddingCharacter ); defaultParamIx++; break; #endregion #region f - double number case 'f': // double w = FormatNumber( ( flagGroupThousands ? "n" : "f" ), flagAlternate, fieldLength, fieldPrecision, flagLeft2Right, flagPositiveSign, flagPositiveSpace, paddingCharacter, o ); defaultParamIx++; break; #endregion #region e - exponent number case 'e': // double / exponent w = FormatNumber( "e", flagAlternate, fieldLength, fieldPrecision, flagLeft2Right, flagPositiveSign, flagPositiveSpace, paddingCharacter, o ); defaultParamIx++; break; #endregion #region E - exponent number case 'E': // double / exponent w = FormatNumber( "E", flagAlternate, fieldLength, fieldPrecision, flagLeft2Right, flagPositiveSign, flagPositiveSpace, paddingCharacter, o ); defaultParamIx++; break; #endregion #region g - general number case 'g': // double / exponent w = FormatNumber( "g", flagAlternate, fieldLength, fieldPrecision, flagLeft2Right, flagPositiveSign, flagPositiveSpace, paddingCharacter, o ); defaultParamIx++; break; #endregion #region G - general number case 'G': // double / exponent w = FormatNumber( "G", flagAlternate, fieldLength, fieldPrecision, flagLeft2Right, flagPositiveSign, flagPositiveSpace, paddingCharacter, o ); defaultParamIx++; break; #endregion #region p - pointer case 'p': // pointer if ( o is IntPtr ) #if XBOX || SILVERLIGHT w = ( (IntPtr)o ).ToString(); #else w = "0x" + ( (IntPtr)o ).ToString( "x" ); #endif defaultParamIx++; break; #endregion #region n - number of processed chars so far case 'n': // number of characters so far w = FormatNumber( "d", flagAlternate, fieldLength, int.MinValue, flagLeft2Right, flagPositiveSign, flagPositiveSpace, paddingCharacter, m.Index ); break; #endregion default: w = String.Empty; defaultParamIx++; break; } // replace format parameter with parameter value // and start searching for the next format parameter // AFTER the position of the current inserted value // to prohibit recursive matches if the value also // includes a format specifier f.Remove( m.Index, m.Length ); f.Insert( m.Index, w ); m = r.Match( f.ToString(), m.Index + w.Length ); } return f.ToString(); } #endregion #endregion #region Private Methods #region FormatOCT private static string FormatOct( string NativeFormat, bool Alternate, int FieldLength, int FieldPrecision, bool Left2Right, char Padding, object Value ) { string w = String.Empty; string lengthFormat = "{0" + ( FieldLength != int.MinValue ? "," + ( Left2Right ? "-" : String.Empty ) + FieldLength.ToString() : String.Empty ) + "}"; if ( IsNumericType( Value ) ) { w = Convert.ToString( UnboxToLong( Value, true ), 8 ); if ( Left2Right || Padding == ' ' ) { if ( Alternate && w != "0" ) w = "0" + w; w = String.Format( lengthFormat, w ); } else { if ( FieldLength != int.MinValue ) w = w.PadLeft( FieldLength - ( Alternate && w != "0" ? 1 : 0 ), Padding ); if ( Alternate && w != "0" ) w = "0" + w; } } return w; } #endregion #region FormatHEX private static string FormatHex( string NativeFormat, bool Alternate, int FieldLength, int FieldPrecision, bool Left2Right, char Padding, object Value ) { string w = String.Empty; string lengthFormat = "{0" + ( FieldLength != int.MinValue ? "," + ( Left2Right ? "-" : String.Empty ) + FieldLength.ToString() : String.Empty ) + "}"; string numberFormat = "{0:" + NativeFormat + ( FieldPrecision != int.MinValue ? FieldPrecision.ToString() : String.Empty ) + "}"; if ( IsNumericType( Value ) ) { w = String.Format( numberFormat, Value ); if ( Left2Right || Padding == ' ' ) { if ( Alternate ) w = ( NativeFormat == "x" ? "0x" : "0X" ) + w; w = String.Format( lengthFormat, w ); } else { if ( FieldLength != int.MinValue ) w = w.PadLeft( FieldLength - ( Alternate ? 2 : 0 ), Padding ); if ( Alternate ) w = ( NativeFormat == "x" ? "0x" : "0X" ) + w; } } return w; } #endregion #region FormatNumber private static string FormatNumber( string NativeFormat, bool Alternate, int FieldLength, int FieldPrecision, bool Left2Right, bool PositiveSign, bool PositiveSpace, char Padding, object Value ) { string w = String.Empty; string lengthFormat = "{0" + ( FieldLength != int.MinValue ? "," + ( Left2Right ? "-" : String.Empty ) + FieldLength.ToString() : String.Empty ) + "}"; string numberFormat = "{0:" + NativeFormat + ( FieldPrecision != int.MinValue ? FieldPrecision.ToString() : "0" ) + "}"; if ( IsNumericType( Value ) ) { w = String.Format( numberFormat, Value ); if ( Left2Right || Padding == ' ' ) { if ( IsPositive( Value, true ) ) w = ( PositiveSign ? "+" : ( PositiveSpace ? " " : String.Empty ) ) + w; w = String.Format( lengthFormat, w ); } else { if ( w.StartsWith( "-" ) ) w = w.Substring( 1 ); if ( FieldLength != int.MinValue ) w = w.PadLeft( FieldLength - 1, Padding ); if ( IsPositive( Value, true ) ) w = ( PositiveSign ? "+" : ( PositiveSpace ? " " : String.Empty ) ) + w; else w = "-" + w; } } return w; } #endregion #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Security; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Runtime.InteropServices.WindowsRuntime { // This is a set of stub methods implementing the support for the IVector`1 interface on managed // objects that implement IList`1. Used by the interop mashaling infrastructure. // // The methods on this class must be written VERY carefully to avoid introducing security holes. // That's because they are invoked with special "this"! The "this" object // for all of these methods are not ListToVectorAdapter objects. Rather, they are of type // IList<T>. No actual ListToVectorAdapter object is ever instantiated. Thus, you will // see a lot of expressions that cast "this" to "IList<T>". internal sealed class ListToVectorAdapter { private ListToVectorAdapter() { Contract.Assert(false, "This class is never instantiated"); } // T GetAt(uint index) [SecurityCritical] internal T GetAt<T>(uint index) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); EnsureIndexInt32(index, _this.Count); try { return _this[(Int32)index]; } catch (ArgumentOutOfRangeException ex) { throw WindowsRuntimeMarshal.GetExceptionForHR(__HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange"); } } // uint Size { get } [SecurityCritical] internal uint Size<T>() { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); return (uint)_this.Count; } // IVectorView<T> GetView() [SecurityCritical] internal IReadOnlyList<T> GetView<T>() { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); Contract.Assert(_this != null); // Note: This list is not really read-only - you could QI for a modifiable // list. We gain some perf by doing this. We believe this is acceptable. IReadOnlyList<T> roList = _this as IReadOnlyList<T>; if (roList == null) { roList = new ReadOnlyCollection<T>(_this); } return roList; } // bool IndexOf(T value, out uint index) [SecurityCritical] internal bool IndexOf<T>(T value, out uint index) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); int ind = _this.IndexOf(value); if (-1 == ind) { index = 0; return false; } index = (uint)ind; return true; } // void SetAt(uint index, T value) [SecurityCritical] internal void SetAt<T>(uint index, T value) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); EnsureIndexInt32(index, _this.Count); try { _this[(int)index] = value; } catch (ArgumentOutOfRangeException ex) { throw WindowsRuntimeMarshal.GetExceptionForHR(__HResults.E_BOUNDS, ex, "ArgumentOutOfRange_IndexOutOfRange"); } } // void InsertAt(uint index, T value) [SecurityCritical] internal void InsertAt<T>(uint index, T value) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); // Inserting at an index one past the end of the list is equivalent to appending // so we need to ensure that we're within (0, count + 1). EnsureIndexInt32(index, _this.Count + 1); try { _this.Insert((int)index, value); } catch (ArgumentOutOfRangeException ex) { // Change error code to match what WinRT expects ex.SetErrorCode(__HResults.E_BOUNDS); throw; } } // void RemoveAt(uint index) [SecurityCritical] internal void RemoveAt<T>(uint index) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); EnsureIndexInt32(index, _this.Count); try { _this.RemoveAt((Int32)index); } catch (ArgumentOutOfRangeException ex) { // Change error code to match what WinRT expects ex.SetErrorCode(__HResults.E_BOUNDS); throw; } } // void Append(T value) [SecurityCritical] internal void Append<T>(T value) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); _this.Add(value); } // void RemoveAtEnd() [SecurityCritical] internal void RemoveAtEnd<T>() { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); if (_this.Count == 0) { Exception e = new InvalidOperationException(Environment.GetResourceString("InvalidOperation_CannotRemoveLastFromEmptyCollection")); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } uint size = (uint)_this.Count; RemoveAt<T>(size - 1); } // void Clear() [SecurityCritical] internal void Clear<T>() { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); _this.Clear(); } // uint GetMany(uint startIndex, T[] items) [SecurityCritical] internal uint GetMany<T>(uint startIndex, T[] items) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); return GetManyHelper<T>(_this, startIndex, items); } // void ReplaceAll(T[] items) [SecurityCritical] internal void ReplaceAll<T>(T[] items) { IList<T> _this = JitHelpers.UnsafeCast<IList<T>>(this); _this.Clear(); if (items != null) { foreach (T item in items) { _this.Add(item); } } } // Helpers: private static void EnsureIndexInt32(uint index, int listCapacity) { // We use '<=' and not '<' becasue Int32.MaxValue == index would imply // that Size > Int32.MaxValue: if (((uint)Int32.MaxValue) <= index || index >= (uint)listCapacity) { Exception e = new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_IndexLargerThanMaxValue")); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } } private static uint GetManyHelper<T>(IList<T> sourceList, uint startIndex, T[] items) { // Calling GetMany with a start index equal to the size of the list should always // return 0 elements, regardless of the input item size if (startIndex == sourceList.Count) { return 0; } EnsureIndexInt32(startIndex, sourceList.Count); if (items == null) { return 0; } uint itemCount = Math.Min((uint)items.Length, (uint)sourceList.Count - startIndex); for (uint i = 0; i < itemCount; ++i) { items[i] = sourceList[(int)(i + startIndex)]; } if (typeof(T) == typeof(string)) { string[] stringItems = items as string[]; // Fill in rest of the array with String.Empty to avoid marshaling failure for (uint i = itemCount; i < items.Length; ++i) stringItems[i] = String.Empty; } return itemCount; } } }
using System; using System.Diagnostics; using System.IO; using System.Linq; using Mono.Cecil; using NUnit.Framework; namespace Mono.Cecil.Tests { [TestFixture] public class ModuleTests : BaseTestFixture { [Test] public void CreateModuleEscapesAssemblyName () { var module = ModuleDefinition.CreateModule ("Test.dll", ModuleKind.Dll); Assert.AreEqual ("Test", module.Assembly.Name.Name); module = ModuleDefinition.CreateModule ("Test.exe", ModuleKind.Console); Assert.AreEqual ("Test", module.Assembly.Name.Name); } [Test] public void SingleModule () { TestModule ("hello.exe", module => { var assembly = module.Assembly; Assert.AreEqual (1, assembly.Modules.Count); Assert.IsNotNull (assembly.MainModule); }); } [Test] public void EntryPoint () { TestModule ("hello.exe", module => { var entry_point = module.EntryPoint; Assert.IsNotNull (entry_point); Assert.AreEqual ("System.Void Program::Main()", entry_point.ToString ()); }); } [Test] public void MultiModules () { IgnoreOnCoreClr (); TestModule("mma.exe", module => { var assembly = module.Assembly; Assert.AreEqual (3, assembly.Modules.Count); Assert.AreEqual ("mma.exe", assembly.Modules [0].Name); Assert.AreEqual (ModuleKind.Console, assembly.Modules [0].Kind); Assert.AreEqual ("moda.netmodule", assembly.Modules [1].Name); Assert.AreEqual ("eedb4721-6c3e-4d9a-be30-49021121dd92", assembly.Modules [1].Mvid.ToString ()); Assert.AreEqual (ModuleKind.NetModule, assembly.Modules [1].Kind); Assert.AreEqual ("modb.netmodule", assembly.Modules [2].Name); Assert.AreEqual ("46c5c577-11b2-4ea0-bb3c-3c71f1331dd0", assembly.Modules [2].Mvid.ToString ()); Assert.AreEqual (ModuleKind.NetModule, assembly.Modules [2].Kind); }); } [Test] public void ModuleInformation () { TestModule ("hello.exe", module => { Assert.IsNotNull (module); Assert.AreEqual ("hello.exe", module.Name); Assert.AreEqual (new Guid ("C3BC2BD3-2576-4D00-A80E-465B5632415F"), module.Mvid); }); } [Test] public void AssemblyReferences () { TestModule ("hello.exe", module => { Assert.AreEqual (1, module.AssemblyReferences.Count); var reference = module.AssemblyReferences [0]; Assert.AreEqual ("mscorlib", reference.Name); Assert.AreEqual (new Version (2, 0, 0, 0), reference.Version); Assert.AreEqual (new byte [] { 0xB7, 0x7A, 0x5C, 0x56, 0x19, 0x34, 0xE0, 0x89 }, reference.PublicKeyToken); }); } [Test] public void ModuleReferences () { TestModule ("pinvoke.exe", module => { Assert.AreEqual (2, module.ModuleReferences.Count); Assert.AreEqual ("kernel32.dll", module.ModuleReferences [0].Name); Assert.AreEqual ("shell32.dll", module.ModuleReferences [1].Name); }); } [Test] public void Types () { TestModule ("hello.exe", module => { Assert.AreEqual (2, module.Types.Count); Assert.AreEqual ("<Module>", module.Types [0].FullName); Assert.AreEqual ("<Module>", module.GetType ("<Module>").FullName); Assert.AreEqual ("Program", module.Types [1].FullName); Assert.AreEqual ("Program", module.GetType ("Program").FullName); }); } [Test] public void LinkedResource () { TestModule ("libres.dll", module => { var resource = module.Resources.Where (res => res.Name == "linked.txt").First () as LinkedResource; Assert.IsNotNull (resource); Assert.AreEqual ("linked.txt", resource.Name); Assert.AreEqual ("linked.txt", resource.File); Assert.AreEqual (ResourceType.Linked, resource.ResourceType); Assert.IsTrue (resource.IsPublic); }); } [Test] public void EmbeddedResource () { TestModule ("libres.dll", module => { var resource = module.Resources.Where (res => res.Name == "embedded1.txt").First () as EmbeddedResource; Assert.IsNotNull (resource); Assert.AreEqual ("embedded1.txt", resource.Name); Assert.AreEqual (ResourceType.Embedded, resource.ResourceType); Assert.IsTrue (resource.IsPublic); using (var reader = new StreamReader (resource.GetResourceStream ())) Assert.AreEqual ("Hello", reader.ReadToEnd ()); resource = module.Resources.Where (res => res.Name == "embedded2.txt").First () as EmbeddedResource; Assert.IsNotNull (resource); Assert.AreEqual ("embedded2.txt", resource.Name); Assert.AreEqual (ResourceType.Embedded, resource.ResourceType); Assert.IsTrue (resource.IsPublic); using (var reader = new StreamReader (resource.GetResourceStream ())) Assert.AreEqual ("World", reader.ReadToEnd ()); }); } [Test] public void ExportedTypeFromNetModule () { IgnoreOnCoreClr (); TestModule ("mma.exe", module => { Assert.IsTrue (module.HasExportedTypes); Assert.AreEqual (2, module.ExportedTypes.Count); var exported_type = module.ExportedTypes [0]; Assert.AreEqual ("Module.A.Foo", exported_type.FullName); Assert.AreEqual ("moda.netmodule", exported_type.Scope.Name); exported_type = module.ExportedTypes [1]; Assert.AreEqual ("Module.B.Baz", exported_type.FullName); Assert.AreEqual ("modb.netmodule", exported_type.Scope.Name); }); } [Test] public void NestedTypeForwarder () { TestCSharp ("CustomAttributes.cs", module => { Assert.IsTrue (module.HasExportedTypes); Assert.AreEqual (2, module.ExportedTypes.Count); var exported_type = module.ExportedTypes [0]; Assert.AreEqual ("System.Diagnostics.DebuggableAttribute", exported_type.FullName); Assert.AreEqual (Platform.OnCoreClr ? "System.Private.CoreLib" : "mscorlib", exported_type.Scope.Name); Assert.IsTrue (exported_type.IsForwarder); var nested_exported_type = module.ExportedTypes [1]; Assert.AreEqual ("System.Diagnostics.DebuggableAttribute/DebuggingModes", nested_exported_type.FullName); Assert.AreEqual (exported_type, nested_exported_type.DeclaringType); Assert.AreEqual (Platform.OnCoreClr ? "System.Private.CoreLib" : "mscorlib", nested_exported_type.Scope.Name); }); } [Test] public void HasTypeReference () { TestCSharp ("CustomAttributes.cs", module => { Assert.IsTrue (module.HasTypeReference ("System.Attribute")); Assert.IsTrue (module.HasTypeReference (Platform.OnCoreClr ? "System.Private.CoreLib" : "mscorlib", "System.Attribute")); Assert.IsFalse (module.HasTypeReference ("System.Core", "System.Attribute")); Assert.IsFalse (module.HasTypeReference ("System.Linq.Enumerable")); }); } [Test] public void Win32FileVersion () { IgnoreOnCoreClr (); TestModule ("libhello.dll", module => { var version = FileVersionInfo.GetVersionInfo (module.FileName); Assert.AreEqual ("0.0.0.0", version.FileVersion); }); } [Test] public void ModuleWithoutBlob () { TestModule ("noblob.dll", module => { Assert.IsNull (module.Image.BlobHeap); }); } [Test] public void MixedModeModule () { using (var module = GetResourceModule ("cppcli.dll")) { Assert.AreEqual (1, module.ModuleReferences.Count); Assert.AreEqual (string.Empty, module.ModuleReferences [0].Name); } } [Test] public void OpenIrrelevantFile () { Assert.Throws<BadImageFormatException> (() => GetResourceModule ("text_file.txt")); } [Test] public void GetTypeNamespacePlusName () { using (var module = GetResourceModule ("moda.netmodule")) { var type = module.GetType ("Module.A", "Foo"); Assert.IsNotNull (type); } } [Test] public void GetNonExistentTypeRuntimeName () { using (var module = GetResourceModule ("libhello.dll")) { var type = module.GetType ("DoesNotExist", runtimeName: true); Assert.IsNull (type); } } [Test] public void OpenModuleImmediate () { using (var module = GetResourceModule ("hello.exe", ReadingMode.Immediate)) { Assert.AreEqual (ReadingMode.Immediate, module.ReadingMode); } } [Test] public void OpenModuleDeferred () { using (var module = GetResourceModule ("hello.exe", ReadingMode.Deferred)) { Assert.AreEqual (ReadingMode.Deferred, module.ReadingMode); } } [Test] public void OwnedStreamModuleFileName () { var path = GetAssemblyResourcePath ("hello.exe"); using (var file = File.Open (path, FileMode.Open)) { using (var module = ModuleDefinition.ReadModule (file)) { Assert.IsNotNull (module.FileName); Assert.IsNotEmpty (module.FileName); Assert.AreEqual (path, module.FileName); } } } [Test] public void ReadAndWriteFile () { var path = Path.GetTempFileName (); var original = ModuleDefinition.CreateModule ("FooFoo", ModuleKind.Dll); var type = new TypeDefinition ("Foo", "Foo", TypeAttributes.Abstract | TypeAttributes.Sealed); original.Types.Add (type); original.Write (path); using (var module = ModuleDefinition.ReadModule (path, new ReaderParameters { ReadWrite = true })) { module.Write (); } using (var module = ModuleDefinition.ReadModule (path)) Assert.AreEqual ("Foo.Foo", module.Types [1].FullName); } [Test] public void ExceptionInWriteDoesNotKeepLockOnFile () { var path = Path.GetTempFileName (); var module = ModuleDefinition.CreateModule ("FooFoo", ModuleKind.Dll); // Mixed mode module that Cecil can not write module.Attributes = (ModuleAttributes) 0; Assert.Throws<NotSupportedException>(() => module.Write (path)); // Ensure you can still delete the file File.Delete (path); } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. See license.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Scriban; using Scriban.Parsing; namespace Scriban.Tests { [TestFixture] public class TestLexer { // TOOD: Add parse invalid character // TODO: Add parse invalid number // TODO: Add parse invalid escape in string // TODO: Add parse unexpected eof in string // TODO: Add tests for FrontMatterMarker [Test] public void ParseRaw() { var text = "text"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token> { new Token(TokenType.Raw, new TextPosition(0,0, 0), new TextPosition(3,0, 3)), Token.Eof }, tokens); Assert.AreEqual(text, tokens[0].GetText(text)); } [Test] public void ParseComment() { var text = "# This is a comment {{ and some interpolated}} and another text"; var lexer = new Lexer(text, options: new LexerOptions() { Lang = ScriptLang.Default, Mode = ScriptMode.ScriptOnly }); var tokens = lexer.ToList<Token>(); Assert.AreEqual(new List<Token> { new Token(TokenType.Comment, new TextPosition(0,0, 0), new TextPosition(62,0, 62)), Token.Eof }, tokens); Assert.AreEqual(text, tokens[0].GetText(text)); } [Test] public void ParseLiquidComment() { string text; // 0 1 2 3 4 // 0123456789012345678901234567890123456789012345 text = "{% comment %}This is a comment{% endcomment %}"; var tokens = ParseTokens(text, isLiquid: true); Assert.AreEqual(new List<Token> { new Token(TokenType.CodeEnter, new TextPosition(0, 0, 0), new TextPosition(12, 0, 12)), new Token(TokenType.CommentMulti, new TextPosition(13, 0, 13), new TextPosition(29, 0, 29)), new Token(TokenType.CodeExit, new TextPosition(30, 0, 30), new TextPosition(45, 0, 45)), Token.Eof }, tokens); // 0 1 2 3 4 // 0123456789012345678901234567890123456789012345 text = "{%comment%}This is a comment{%endcomment%}"; tokens = ParseTokens(text, isLiquid: true); Assert.AreEqual(new List<Token> { new Token(TokenType.CodeEnter, new TextPosition(0, 0, 0), new TextPosition(10, 0, 10)), new Token(TokenType.CommentMulti, new TextPosition(11, 0, 11), new TextPosition(27, 0, 27)), new Token(TokenType.CodeExit, new TextPosition(28, 0, 28), new TextPosition(41, 0, 41)), Token.Eof }, tokens); // 0 1 2 3 4 // 0123456789012345678901234567890123456789012345678 text = "{% comment%}This is a comment{% endcomment%}"; tokens = ParseTokens(text, isLiquid: true); Assert.AreEqual(new List<Token> { new Token(TokenType.CodeEnter, new TextPosition(0, 0, 0), new TextPosition(14, 0, 14)), new Token(TokenType.CommentMulti, new TextPosition(15, 0, 15), new TextPosition(31, 0, 31)), new Token(TokenType.CodeExit, new TextPosition(32, 0, 32), new TextPosition(48, 0, 48)), Token.Eof }, tokens); // 0 1 2 3 4 // 0123456789012345678901234567890123456789012345678 text = "{%comment %}This is a comment{%endcomment %}"; tokens = ParseTokens(text, isLiquid: true); Assert.AreEqual(new List<Token> { new Token(TokenType.CodeEnter, new TextPosition(0, 0, 0), new TextPosition(13, 0, 13)), new Token(TokenType.CommentMulti, new TextPosition(14, 0, 14), new TextPosition(30, 0, 30)), new Token(TokenType.CodeExit, new TextPosition(31, 0, 31), new TextPosition(47, 0, 47)), Token.Eof }, tokens); } [Test] public void ParseLiquidRaw() { string text; // 0 1 2 3 4 // 0123456789012345678901234567890123456789012345 text = "{% raw %}This is a raw{% endraw %}"; var tokens = ParseTokens(text, isLiquid: true); Assert.AreEqual(new List<Token> { new Token(TokenType.EscapeEnter, new TextPosition(0, 0, 0), new TextPosition(8, 0, 8)), new Token(TokenType.Escape, new TextPosition(9, 0, 9), new TextPosition(21, 0, 21)), new Token(TokenType.EscapeExit, new TextPosition(22, 0, 22), new TextPosition(33, 0, 33)), Token.Eof }, tokens); // 0 1 2 3 4 // 0123456789012345678901234567890123456789012345 text = "{%raw%}This is a raw{%endraw%}"; tokens = ParseTokens(text, isLiquid: true); Assert.AreEqual(new List<Token> { new Token(TokenType.EscapeEnter, new TextPosition(0, 0, 0), new TextPosition(6, 0, 6)), new Token(TokenType.Escape, new TextPosition(7, 0, 7), new TextPosition(19, 0, 19)), new Token(TokenType.EscapeExit, new TextPosition(20, 0, 20), new TextPosition(29, 0, 29)), Token.Eof }, tokens); // 0 1 2 3 4 // 0123456789012345678901234567890123456789012345678 text = "{% raw%}This is a raw{% endraw%}"; tokens = ParseTokens(text, isLiquid: true); Assert.AreEqual(new List<Token> { new Token(TokenType.EscapeEnter, new TextPosition(0, 0, 0), new TextPosition(10, 0, 10)), new Token(TokenType.Escape, new TextPosition(11, 0, 11), new TextPosition(23, 0, 23)), new Token(TokenType.EscapeExit, new TextPosition(24, 0, 24), new TextPosition(36, 0, 36)), Token.Eof }, tokens); // 0 1 2 3 4 // 0123456789012345678901234567890123456789012345678 text = "{%raw %}This is a raw{%endraw %}"; tokens = ParseTokens(text, isLiquid: true); Assert.AreEqual(new List<Token> { new Token(TokenType.EscapeEnter, new TextPosition(0, 0, 0), new TextPosition(9, 0, 9)), new Token(TokenType.Escape, new TextPosition(10, 0, 10), new TextPosition(22, 0, 22)), new Token(TokenType.EscapeExit, new TextPosition(23, 0, 23), new TextPosition(35, 0, 35)), Token.Eof }, tokens); } private void CheckLiquidRawOrComment(bool isComment, string text, string inner, bool withLeft = false, bool withRight = false) { if (withLeft) { text = "abc " + text; } if (withRight) { text = text + " abc"; } var startInner = text.IndexOf(inner, StringComparison.Ordinal); var endInner = startInner + inner.Length - 1; var tokens = ParseTokens(text, true); var expectedTokens = new List<Token>(); int innerIndex = 0; if (isComment) { var startCodeEnter = text.IndexOf("{%"); expectedTokens.Add(new Token(TokenType.CodeEnter, new TextPosition(startCodeEnter, 0, startCodeEnter), new TextPosition(startCodeEnter+1, 0, startCodeEnter+1))); innerIndex = 1; } expectedTokens.Add(new Token(isComment ? TokenType.CommentMulti : TokenType.Escape, new TextPosition(startInner, 0, startInner), new TextPosition(endInner, 0, endInner))); if (isComment) { var startCodeExit = text.LastIndexOf("%}"); expectedTokens.Add(new Token(TokenType.CodeExit, new TextPosition(startCodeExit, 0, startCodeExit), new TextPosition(startCodeExit + 1, 0, startCodeExit + 1))); } else { expectedTokens.Add(new Token(TokenType.EscapeExit, new TextPosition(startInner, 0, startInner), new TextPosition(endInner, 0, endInner))); } expectedTokens.Add(Token.Eof); var tokensIt = tokens.GetEnumerator(); foreach (var expectedToken in expectedTokens) { if (tokensIt.MoveNext()) { var token = tokensIt.Current; if (expectedToken.Type == TokenType.EscapeExit) { Assert.AreEqual(expectedToken.Type, token.Type); } else { Assert.AreEqual(expectedToken, token); } } } Assert.AreEqual(expectedTokens.Count, tokens.Count); Assert.AreEqual(inner, tokens[innerIndex].GetText(text)); } [Test] public void ParseJekyllLiquidInclude() { // 0 1 2 // 012345678901234567890123456 var text = "{% include toto/tata.htm %}"; var tokens = ParseTokens(text, true, true, true); Assert.AreEqual(new List<Token> { new Token(TokenType.LiquidTagEnter, new TextPosition(0, 0, 0), new TextPosition(1, 0, 1)), new Token(TokenType.Whitespace, new TextPosition(2, 0, 2), new TextPosition(2, 0, 2)), new Token(TokenType.Identifier, new TextPosition(3, 0, 3), new TextPosition(9, 0, 9)), new Token(TokenType.Whitespace, new TextPosition(10, 0, 10), new TextPosition(10, 0, 10)), new Token(TokenType.ImplicitString, new TextPosition(11, 0, 11), new TextPosition(23, 0, 23)), new Token(TokenType.Whitespace, new TextPosition(24, 0, 24), new TextPosition(24, 0, 24)), new Token(TokenType.LiquidTagExit, new TextPosition(25, 0, 25), new TextPosition(26, 0, 26)), Token.Eof }, tokens); } [Test] public void ParseRawWithNewLines() { var text = "te\r\n\r\n\r\n"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token> { new Token(TokenType.Raw, new TextPosition(0,0, 0), new TextPosition(7,2, 1)), Token.Eof }, tokens); Assert.AreEqual(text, tokens[0].GetText(text)); } [Test] public void ParseRawWithCodeExit() { var text = "te}}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token> { new Token(TokenType.Raw, new TextPosition(0,0, 0), new TextPosition(3,0, 3)), Token.Eof }, tokens); Assert.AreEqual(text, tokens[0].GetText(text)); } [Test] public void ParseCodeEnterAndCodeExit() { var text = "{{}}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token> { new Token(TokenType.CodeEnter, new TextPosition(0,0, 0), new TextPosition(1,0, 1)), new Token(TokenType.CodeExit, new TextPosition(2,0, 2), new TextPosition(3,0, 3)), Token.Eof }, tokens); VerifyTokenGetText(tokens, text); } [Test] public void ParseCodeEnterAndCodeExitWithNewLineAndTextInRaw() { // In this case a raw token is generated // 01234 5 6 var text = "{{}}\r\na"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token> { new Token(TokenType.CodeEnter, new TextPosition(0,0, 0), new TextPosition(1,0, 1)), new Token(TokenType.CodeExit, new TextPosition(2,0, 2), new TextPosition(3,0, 3)), new Token(TokenType.Raw, new TextPosition(4,0, 4), new TextPosition(6,1, 0)), // skip \r\n Token.Eof }, tokens); VerifyTokenGetText(tokens, text); } [Test] public void ParseCodeEnterAndCodeExitWithSpaces() { // whitespace don't generate tokens inside a code block var text = @"{{ }}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token> { new Token(TokenType.CodeEnter, new TextPosition(0,0, 0), new TextPosition(1,0, 1)), new Token(TokenType.CodeExit, new TextPosition(6,0, 6), new TextPosition(7,0, 7)), Token.Eof }, tokens); VerifyTokenGetText(tokens, text); } [Test] public void ParseCodeEnterAndCodeExitWithNewLines() { // A New line is always generated only for a first statement (even empty), but subsequent empty white-space/new-lines are skipped var text = "{{ \r\n\r\n\r\n}}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token> { new Token(TokenType.CodeEnter, new TextPosition(0,0, 0), new TextPosition(1,0, 1)), new Token(TokenType.NewLine, new TextPosition(4,0, 4), new TextPosition(8,2, 1)), // Whe whole whitespaces with newlines new Token(TokenType.CodeExit, new TextPosition(9,3, 0), new TextPosition(10,3, 1)), Token.Eof }, tokens); VerifyTokenGetText(tokens, text); } [Test] public void ParseLogicalOperators() { VerifyCodeBlock("{{ ! && || }}", new Token(TokenType.Exclamation, new TextPosition(3, 0, 3), new TextPosition(3, 0, 3)), new Token(TokenType.DoubleAmp, new TextPosition(5, 0, 5), new TextPosition(6, 0, 6)), new Token(TokenType.DoubleVerticalBar, new TextPosition(8, 0, 8), new TextPosition(9, 0, 9)) ); } [Test] public void ParseEscapeRaw() { { var text = "{%{}%}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { // Empty escape new Token(TokenType.EscapeEnter, new TextPosition(0, 0, 0), new TextPosition(2, 0, 2)), new Token(TokenType.EscapeExit, new TextPosition(3, 0, 3), new TextPosition(5, 0, 5)), Token.Eof, }, tokens); } { var text = "{%{ }%}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.EscapeEnter, new TextPosition(0, 0, 0), new TextPosition(2, 0, 2)), new Token(TokenType.Escape, new TextPosition(3, 0, 3), new TextPosition(3, 0, 3)), new Token(TokenType.EscapeExit, new TextPosition(4, 0, 4), new TextPosition(6, 0, 6)), Token.Eof, }, tokens); } { var text = "{%{{{}}}%}"; // The raw should be {{}} var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.EscapeEnter, new TextPosition(0, 0, 0), new TextPosition(2, 0, 2)), new Token(TokenType.Escape, new TextPosition(3, 0, 3), new TextPosition(6, 0, 6)), new Token(TokenType.EscapeExit, new TextPosition(7, 0, 7), new TextPosition(9, 0, 9)), Token.Eof, }, tokens); } { var text = "{%%{}%}}%%}"; // The raw should be }%} var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.EscapeEnter, new TextPosition(0, 0, 0), new TextPosition(3, 0, 3)), new Token(TokenType.Escape, new TextPosition(4, 0, 4), new TextPosition(6, 0, 6)), new Token(TokenType.EscapeExit, new TextPosition(7, 0, 7), new TextPosition(10, 0, 10)), Token.Eof, }, tokens); } } [Test] public void ParseEscapeAndSpaces() { { // 1 // 01234567 8901234567 var text = "{%{ }%}\n {{~ }}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.EscapeEnter, new TextPosition(0, 0, 0), new TextPosition(2, 0, 2)), new Token(TokenType.Escape, new TextPosition(3, 0, 3), new TextPosition(3, 0, 3)), new Token(TokenType.EscapeExit, new TextPosition(4, 0, 4), new TextPosition(6, 0, 6)), new Token(TokenType.Raw, new TextPosition(7, 0, 7), new TextPosition(7, 0, 7)), new Token(TokenType.Whitespace, new TextPosition(8, 1, 0), new TextPosition(11, 1, 3)), new Token(TokenType.CodeEnter, new TextPosition(12, 1, 4), new TextPosition(14, 1, 6)), new Token(TokenType.CodeExit, new TextPosition(16, 1, 8), new TextPosition(17, 1, 9)), Token.Eof, }, tokens); } } [Test] public void ParseWithoutSpaces() { { // 1 // 0 12 3 4567890 var text = "\n \r\n {{~ }}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.Raw, new TextPosition(0, 0, 0), new TextPosition(3, 1, 2)), new Token(TokenType.Whitespace, new TextPosition(4, 2, 0), new TextPosition(4, 2, 0)), new Token(TokenType.CodeEnter, new TextPosition(5, 2, 1), new TextPosition(7, 2, 3)), new Token(TokenType.CodeExit, new TextPosition(9, 2, 5), new TextPosition(10, 2, 6)), Token.Eof, }, tokens); } { // 1 // 0 12 3 4567890 var text = "\n \r\n {{- }}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.WhitespaceFull, new TextPosition(0, 0, 0), new TextPosition(4, 2, 0)), new Token(TokenType.CodeEnter, new TextPosition(5, 2, 1), new TextPosition(7, 2, 3)), new Token(TokenType.CodeExit, new TextPosition(9, 2, 5), new TextPosition(10, 2, 6)), Token.Eof, }, tokens); } { // 01234567 var text = "a {{~ }}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.Raw, new TextPosition(0, 0, 0), new TextPosition(0, 0, 0)), new Token(TokenType.Whitespace, new TextPosition(1, 0, 1), new TextPosition(1, 0, 1)), new Token(TokenType.CodeEnter, new TextPosition(2, 0, 2), new TextPosition(4, 0, 4)), new Token(TokenType.CodeExit, new TextPosition(6, 0, 6), new TextPosition(7, 0, 7)), Token.Eof, }, tokens); } { // 0 1 2 // 01234567 89012345 6789012 var text = "{{ ~}} \n \r\n \n"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.CodeEnter, new TextPosition(0, 0, 0), new TextPosition(1, 0, 1)), new Token(TokenType.CodeExit, new TextPosition(3, 0, 3), new TextPosition(5, 0, 5)), new Token(TokenType.Whitespace, new TextPosition(6, 0, 6), new TextPosition(7, 0, 7)), new Token(TokenType.Raw, new TextPosition(8, 1, 0), new TextPosition(22, 2, 6)), Token.Eof, }, tokens); } { // 0 1 2 // 01234567 89012345 6789012 var text = "{{ -}} \n \r\n \n"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.CodeEnter, new TextPosition(0, 0, 0), new TextPosition(1, 0, 1)), new Token(TokenType.CodeExit, new TextPosition(3, 0, 3), new TextPosition(5, 0, 5)), new Token(TokenType.WhitespaceFull, new TextPosition(6, 0, 6), new TextPosition(22, 2, 6)), Token.Eof, }, tokens); } { // 012345678 var text = " {%{~ }%}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.Whitespace, new TextPosition(0, 0, 0), new TextPosition(0, 0, 0)), new Token(TokenType.EscapeEnter, new TextPosition(1, 0, 1), new TextPosition(4, 0, 4)), new Token(TokenType.Escape, new TextPosition(5, 0, 5), new TextPosition(5, 0, 5)), new Token(TokenType.EscapeExit, new TextPosition(6, 0, 6), new TextPosition(8, 0, 8)), Token.Eof, }, tokens); } { // 0123456789 01234567 8901234 var text = "{%{ ~}%} \n \n \n"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.EscapeEnter, new TextPosition(0, 0, 0), new TextPosition(2, 0, 2)), new Token(TokenType.Escape, new TextPosition(3, 0, 3), new TextPosition(3, 0, 3)), new Token(TokenType.EscapeExit, new TextPosition(4, 0, 4), new TextPosition(7, 0, 7)), new Token(TokenType.Whitespace, new TextPosition(8, 0, 8), new TextPosition(9, 0, 9)), new Token(TokenType.Raw, new TextPosition(10, 1, 0), new TextPosition(24, 2, 6)), Token.Eof, }, tokens); } { // 0123456789 01234567 8901234 var text = "{%{ -}%} \n \n \n"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.EscapeEnter, new TextPosition(0, 0, 0), new TextPosition(2, 0, 2)), new Token(TokenType.Escape, new TextPosition(3, 0, 3), new TextPosition(3, 0, 3)), new Token(TokenType.EscapeExit, new TextPosition(4, 0, 4), new TextPosition(7, 0, 7)), new Token(TokenType.WhitespaceFull, new TextPosition(8, 0, 8), new TextPosition(24, 2, 6)), Token.Eof, }, tokens); } } [Test] public void ParseSimpleTokens() { VerifySimpleTokens(new Dictionary<string, TokenType>() { {"\x01", TokenType.Invalid}, {"@", TokenType.Arroba}, {"^", TokenType.Caret}, {"^^", TokenType.DoubleCaret}, {"*", TokenType.Asterisk}, {"+", TokenType.Plus}, {"-", TokenType.Minus}, {"/", TokenType.Divide}, {"//", TokenType.DoubleDivide}, {"%", TokenType.Percent}, {"=", TokenType.Equal}, {"!", TokenType.Exclamation}, {"|", TokenType.VerticalBar}, {"|>", TokenType.PipeGreater}, {",", TokenType.Comma}, {".", TokenType.Dot}, {"(", TokenType.OpenParen}, {")", TokenType.CloseParen}, {"[", TokenType.OpenBracket}, {"]", TokenType.CloseBracket}, {"<", TokenType.Less}, {">", TokenType.Greater}, {"==", TokenType.DoubleEqual}, {">=", TokenType.GreaterEqual}, {"<=", TokenType.LessEqual}, {"&", TokenType.Amp}, {"&&", TokenType.DoubleAmp}, {"??", TokenType.DoubleQuestion}, {"||", TokenType.DoubleVerticalBar}, {"..", TokenType.DoubleDot}, {"..<", TokenType.DoubleDotLess}, }); //{ "{", TokenType.OpenBrace}, // We cannot test them individualy here as they are used in the lexer to match braces and better handle closing code }} //{ "}", TokenType.CloseBrace}, } [Test] public void ParseLiquidTokens() { VerifySimpleTokens(new Dictionary<string, TokenType>() { {"\x01", TokenType.Invalid}, {"@", TokenType.Invalid}, {"^", TokenType.Invalid}, {"*", TokenType.Invalid}, {"+", TokenType.Invalid}, {"-", TokenType.Minus}, {"/", TokenType.Invalid}, {"%", TokenType.Invalid}, {"=", TokenType.Equal}, {"!", TokenType.Invalid}, {"|", TokenType.VerticalBar}, {",", TokenType.Comma}, {".", TokenType.Dot}, {"(", TokenType.OpenParen}, {")", TokenType.CloseParen}, {"[", TokenType.OpenBracket}, {"]", TokenType.CloseBracket}, {"<", TokenType.Less}, {">", TokenType.Greater}, {"==", TokenType.DoubleEqual}, {"!=", TokenType.ExclamationEqual}, {">=", TokenType.GreaterEqual}, {"<=", TokenType.LessEqual}, {"?", TokenType.Question}, {"&", TokenType.Invalid}, {"..", TokenType.DoubleDot} }, true); //{ "{", TokenType.OpenBrace}, // We cannot test them individualy here as they are used in the lexer to match braces and better handle closing code }} //{ "}", TokenType.CloseBrace}, } [Test] public void ParseIdentifier() { VerifySimpleTokens(new Dictionary<string, TokenType>() { {"_", TokenType.Identifier}, {"t_st", TokenType.Identifier}, {"test", TokenType.Identifier}, {"t999", TokenType.Identifier}, {"_est", TokenType.Identifier}, {"_999", TokenType.Identifier}, {"$", TokenType.IdentifierSpecial}, {"$$", TokenType.IdentifierSpecial}, {"$0", TokenType.IdentifierSpecial}, {"$test", TokenType.IdentifierSpecial}, {"$t999", TokenType.IdentifierSpecial}, {"$_est", TokenType.IdentifierSpecial}, {"$_999", TokenType.IdentifierSpecial}, }); } [Test] public void ParseNumbers() { VerifySimpleTokens(new Dictionary<string, TokenType>() { {"1", TokenType.Integer}, {"10", TokenType.Integer}, {"100000", TokenType.Integer}, {"1e1", TokenType.Integer}, {"1.", TokenType.Float}, {"1.e1", TokenType.Float}, {"1.0", TokenType.Float}, {"10.0", TokenType.Float}, {"10.01235", TokenType.Float}, {"10.01235e1", TokenType.Float}, {"10.01235e-1", TokenType.Float}, {"10.01235e+1", TokenType.Float}, }); } [Test] public void ParseNumberInvalid() { var lexer = new Lexer("{{ 1e }}"); var tokens = lexer.ToList(); Assert.True(lexer.HasErrors); StringAssert.Contains("Expecting at least one digit after the exponent", lexer.Errors.First().Message); } [Test] public void ParseCommentSingleLine() { var comment = "{{# This is a comment}}"; VerifyCodeBlock(comment, new Token(TokenType.Comment, new TextPosition(2, 0, 2), new TextPosition(comment.Length-3, 0, comment.Length-3)) ); } [Test] public void ParseCommentSingleLineEof() { var text = "{{# This is a comment"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.CodeEnter, new TextPosition(0, 0, 0), new TextPosition(1, 0, 1)), new Token(TokenType.Comment, new TextPosition(2, 0, 2), new TextPosition(20, 0, 20)), Token.Eof, }, tokens); } [Test] public void ParseCommentMultiLineEof() { var text = "{{## This is a comment"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.CodeEnter, new TextPosition(0, 0, 0), new TextPosition(1, 0, 1)), new Token(TokenType.CommentMulti, new TextPosition(2, 0, 2), new TextPosition(21, 0, 21)), Token.Eof, }, tokens); } [Test] public void ParseCommentMultiLineOnSingleLine() { { var comment = @"{{## This a multiline comment on a single line ##}}"; VerifyCodeBlock(comment, new Token(TokenType.CommentMulti, new TextPosition(2, 0, 2), new TextPosition(comment.Length - 3, 0, comment.Length - 3))); } { var comment = @"{{## This a multiline comment on a single line without a ending}}"; VerifyCodeBlock(comment, new Token(TokenType.CommentMulti, new TextPosition(2, 0, 2), new TextPosition(comment.Length - 3, 0, comment.Length - 3))); } } [Test] public void ParseCommentMultiLine() { var text = @"{{## This a multiline comment on a single line ##}}"; VerifyCodeBlock(text, new Token(TokenType.CommentMulti, new TextPosition(2, 0, 2), new TextPosition(text.Length - 3, 3, 1)), // Handle eplicit code exit matching when we have multiline new Token(TokenType.CodeExit, new TextPosition(text.Length-2, 3, 2), new TextPosition(text.Length-1, 3, 3)) ); } [Test] public void ParseStringSingleLine() { VerifySimpleTokens(new Dictionary<string, TokenType>() { {@"""This a string on a single line""", TokenType.String}, {@"""This a string with an escape \"" and escape \\ """, TokenType.String}, {@"'This a string with an escape \' and inlined "" '", TokenType.String}, {@"'This a string with \0 \b \n \u0000 \uFFFF \x00 \xff'", TokenType.String}, // {@"'This a single string spanning over multilines with \\ //This is the continuation'", TokenType.String}, }); } [Test] public void ParseUnbalancedCloseBrace() { { var lexer = new Lexer("{{ } }}"); var tokens = lexer.ToList(); Assert.True(lexer.HasErrors); StringAssert.Contains("Unexpected } while no matching", lexer.Errors.First().Message); } } [Test] public void ParseStringInvalid() { { var lexer = new Lexer("{{ '\\u' }}"); var tokens = lexer.ToList(); Assert.True(lexer.HasErrors); StringAssert.Contains("Unexpected hex number", lexer.Errors.First().Message); } { var lexer = new Lexer("{{ '\\u1' }}"); var tokens = lexer.ToList(); Assert.True(lexer.HasErrors); StringAssert.Contains("Unexpected hex number", lexer.Errors.First().Message); } { var lexer = new Lexer("{{ '\\u12' }}"); var tokens = lexer.ToList(); Assert.True(lexer.HasErrors); StringAssert.Contains("Unexpected hex number", lexer.Errors.First().Message); } { var lexer = new Lexer("{{ '\\u123' }}"); var tokens = lexer.ToList(); Assert.True(lexer.HasErrors); StringAssert.Contains("Unexpected hex number", lexer.Errors.First().Message); } { var lexer = new Lexer("{{ '\\x' }}"); var tokens = lexer.ToList(); Assert.True(lexer.HasErrors); StringAssert.Contains("Unexpected hex number", lexer.Errors.First().Message); } { var lexer = new Lexer("{{ '\\x1' }}"); var tokens = lexer.ToList(); Assert.True(lexer.HasErrors); StringAssert.Contains("Unexpected hex number", lexer.Errors.First().Message); } { var lexer = new Lexer("{{ '"); var tokens = lexer.ToList(); Assert.True(lexer.HasErrors); StringAssert.Contains("Unexpected end of file while parsing a string not terminated", lexer.Errors.First().Message); } { var lexer = new Lexer("{{ `"); var tokens = lexer.ToList(); Assert.True(lexer.HasErrors); StringAssert.Contains("Unexpected end of file while parsing a verbatim string not terminated by", lexer.Errors.First().Message); } } [Test] public void ParseTestNewLine() { { // 0 // 01234 567 var text = "{{ a\r }}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.CodeEnter, new TextPosition(0, 0, 0), new TextPosition(1, 0, 1)), new Token(TokenType.Identifier, new TextPosition(3, 0, 3), new TextPosition(3, 0, 3)), new Token(TokenType.NewLine, new TextPosition(4, 0, 4), new TextPosition(5, 1, 0)), new Token(TokenType.CodeExit, new TextPosition(6, 1, 1), new TextPosition(7, 1, 2)), Token.Eof, }, tokens); } { // 0 // 01234 567 var text = "{{ a\n }}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.CodeEnter, new TextPosition(0, 0, 0), new TextPosition(1, 0, 1)), new Token(TokenType.Identifier, new TextPosition(3, 0, 3), new TextPosition(3, 0, 3)), new Token(TokenType.NewLine, new TextPosition(4, 0, 4), new TextPosition(5, 1, 0)), new Token(TokenType.CodeExit, new TextPosition(6, 1, 1), new TextPosition(7, 1, 2)), Token.Eof, }, tokens); } { // 0 // 01234 5 678 var text = "{{ a\r\n }}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.CodeEnter, new TextPosition(0, 0, 0), new TextPosition(1, 0, 1)), new Token(TokenType.Identifier, new TextPosition(3, 0, 3), new TextPosition(3, 0, 3)), new Token(TokenType.NewLine, new TextPosition(4, 0, 4), new TextPosition(6, 1, 0)), new Token(TokenType.CodeExit, new TextPosition(7, 1, 1), new TextPosition(8, 1, 2)), Token.Eof, }, tokens); } } [Test] public void ParseStringEscapeEol() { // 0 1 // 012345678 9 0123 var text = "{{ 'text\\\n' }}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.CodeEnter, new TextPosition(0, 0, 0), new TextPosition(1, 0, 1)), new Token(TokenType.String, new TextPosition(3, 0, 3), new TextPosition(10, 1, 0)), new Token(TokenType.CodeExit, new TextPosition(12, 1, 2), new TextPosition(13, 1, 3)), Token.Eof, }, tokens); } [Test] public void ParseStringEscapeEol2() { // 0 1 // 012345678 9 0 1234 var text = "{{ 'text\\\r\n' }}"; var tokens = ParseTokens(text); Assert.AreEqual(new List<Token>() { new Token(TokenType.CodeEnter, new TextPosition(0, 0, 0), new TextPosition(1, 0, 1)), new Token(TokenType.String, new TextPosition(3, 0, 3), new TextPosition(11, 1, 0)), new Token(TokenType.CodeExit, new TextPosition(13, 1, 2), new TextPosition(14, 1, 3)), Token.Eof, }, tokens); } [Test] public void ParseStringMultiLine() { var text = @"{{""This a string on a single line ""}}"; VerifyCodeBlock(text, new Token(TokenType.String, new TextPosition(2, 0, 2), new TextPosition(text.Length - 3, 2, 0)), // Handle eplicit code exit matching when we have multiline new Token(TokenType.CodeExit, new TextPosition(text.Length - 2, 2, 1), new TextPosition(text.Length - 1, 2, 2)) ); } [Test] public void ParseIdentifiers() { var text = @"{{ with this xxx = 5 end}}This is a test"; var lexer = new Lexer(text); Assert.False((bool)lexer.HasErrors); var tokens = Enumerable.ToList<Token>(lexer); // TODO Add testd } private void VerifySimpleTokens(Dictionary<string, TokenType> simpleTokens, bool isLiquid = false) { foreach (var token in simpleTokens) { var text = "{{ " + token.Key + " }}"; VerifyCodeBlock(text, isLiquid, new Token(token.Value, new TextPosition(3, 0, 3), new TextPosition(3 + token.Key.Length - 1, 0, 3 + token.Key.Length - 1)) ); } } private List<Token> ParseTokens(string text, bool isLiquid = false, bool keepTrivia = false, bool isJekyll = false) { var lexer = new Lexer(text, options: new LexerOptions() { Lang = isLiquid ? ScriptLang.Liquid : ScriptLang.Default, KeepTrivia = keepTrivia, EnableIncludeImplicitString = isJekyll}); foreach (var error in lexer.Errors) { Console.WriteLine(error); } Assert.False((bool)lexer.HasErrors); var tokens = Enumerable.ToList<Token>(lexer); return tokens; } private void VerifyCodeBlock(string text, params Token[] expectedTokens) { VerifyCodeBlock(text, false, expectedTokens); } private void VerifyCodeBlock(string text, bool isLiquid, params Token[] expectedTokens) { var expectedTokenList = new List<Token>(); expectedTokenList.Add(new Token(TokenType.CodeEnter, new TextPosition(0, 0, 0), new TextPosition(1, 0, 1))); expectedTokenList.AddRange(expectedTokens); if (expectedTokenList[expectedTokenList.Count - 1].Type != TokenType.CodeExit) { // Add last token automatically if not already here expectedTokenList.Add(new Token(TokenType.CodeExit, new TextPosition(text.Length - 2, 0, text.Length - 2), new TextPosition(text.Length - 1, 0, text.Length - 1))); } expectedTokenList.Add(Token.Eof); var tokens = ParseTokens(text, isLiquid); Assert.AreEqual(expectedTokenList, tokens, $"Unexpected error while parsing: {text}"); VerifyTokenGetText(tokens, text); } private static void VerifyTokenGetText(List<Token> tokens, string text) { foreach (var token in tokens) { var tokenText = token.GetText(text); if (token.Type.HasText()) { Assert.AreEqual(token.Type.ToText(), tokenText, $"Invalid captured text found for standard token `{token.Type}` while parsing: {text}"); } } } } }
#region Copyright /*Copyright (C) 2015 Konstantin Udilovich Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Kodestruct.Concrete.ACI; using Kodestruct.Common.Entities; using Kodestruct.Common.Reports; using Kodestruct.Common.CalculationLogger.Interfaces; using Kodestruct.Common.CalculationLogger; namespace Kodestruct.Concrete.ACI318_14 { public partial class DevelopmentTension : Development { //internal double GetTensionDevelopmentLength(double fy, double sqrt_fc, double fc, double lambda, //double ksi_t, double ksi_e, double ksi_s, double cb, double Ktr) //{ private void GetDevelopmentLengthParameters(ref double lambda, ref double fc, ref double sqrt_fc, ref double fy, ref double db, ref double ksi_t, ref double ksi_e, ref double ksi_s, ref double ksi_tAndKsi_eProduct) { fy = Rebar.Material.YieldStress; fc = Concrete.SpecifiedCompressiveStrength; sqrt_fc = GetSqrt_fc(); lambda = Concrete.lambda; lambda = CheckLambda(lambda); db = Rebar.Diameter; //Get ksi Factors and lambda factor ksi_t = GetKsi_t(); ksi_e = GetKsi_e(); ksi_s = GetKsi_s(); if (ksi_t == 0.0 || ksi_e == 0.0 || ksi_s == 0.0) { throw new Exception("Failed to calculate at least one ksi-factor. Please check input"); } ksi_tAndKsi_eProduct = Getksi_tAndKsi_eProduct(ksi_t, ksi_e); } public double GetTensionDevelopmentLength(double A_tr, double s_tr, double n) { double ld; double lambda =0; double fc=0; double sqrt_fc=0; double fy=0; double db=0; double ksi_t=0; double ksi_e=0; double ksi_s=0; double ksi_tAndKsi_eProduct=0; GetDevelopmentLengthParameters(ref lambda, ref fc, ref sqrt_fc, ref fy, ref db, ref ksi_t,ref ksi_e,ref ksi_s, ref ksi_tAndKsi_eProduct); double cb = GetCb(); double Ktr = GetKtr(A_tr,s_tr,n); double ConfinementTerm = GetConfinementTerm(cb, Ktr); ld = 3.0 / 40.0 * (fy / (lambda * sqrt_fc)) * (ksi_tAndKsi_eProduct * ksi_s / (ConfinementTerm)) * db; ld = CheckExcessReinforcement(ld, true,false); if (this.CheckMinimumLength == true) { ld = GetMinimumLength(ld); } Length = ld; return ld; } public double GetTensionDevelopmentLength(bool minimumShearReinforcementProvided) { double ld; double lambda = 0; double fc = 0; double sqrt_fc = 0; double fy = 0; double db = 0; double ksi_t = 0; double ksi_e = 0; double ksi_s = 0; double ksi_tAndKsi_eProduct = 0; GetDevelopmentLengthParameters(ref lambda, ref fc, ref sqrt_fc, ref fy, ref db, ref ksi_t, ref ksi_e, ref ksi_s, ref ksi_tAndKsi_eProduct); bool clearSpacingLimitsAreMet; if (clearSpacing!= 0.0 && clearCover!=0) { if (clearSpacing >= db || clearCover >= db) { clearSpacingLimitsAreMet = true; } else { clearSpacingLimitsAreMet = false; } } else { clearSpacingLimitsAreMet = MeetsSpacingCritera; } if (clearSpacingLimitsAreMet && minimumShearReinforcementProvided == true) { if (db < 7.0 / 8.0) { //Formula A ld = (fy * ksi_tAndKsi_eProduct / (25.0 * lambda * sqrt_fc)) * db; } else { //Formula B ld = (fy * ksi_tAndKsi_eProduct / (20.0 * lambda * sqrt_fc)) * db; } } else { if (db < 7.0 / 8.0) { //Formula C ld = (3.0 * fy * ksi_tAndKsi_eProduct / (50.0 * lambda * sqrt_fc)) * db; } else { //Formula D ld = (3.0 * fy * ksi_tAndKsi_eProduct / (40.0 * lambda * sqrt_fc)) * db; } } ld = CheckExcessReinforcement(ld, true, false); if (this.CheckMinimumLength == true) { ld = GetMinimumLength(ld); } return ld; } internal double GetMinimumLength(double ld) { if (ld < 12.0) { ld = 12.0; } return ld; } } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. 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. */ /* The conversion functions are derived from OpenEXR's implementation and are governed by the following license: Copyright (c) 2002, Industrial Light & Magic, a division of Lucas Digital Ltd. LLC All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Industrial Light & Magic nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion --- License --- using System; using System.IO; using System.Runtime.InteropServices; using System.Runtime.Serialization; namespace Picodex.Render.Unity { /// <summary> /// The name Half is derived from half-precision floating-point number. /// It occupies only 16 bits, which are split into 1 Sign bit, 5 Exponent bits and 10 Mantissa bits. /// </summary> /// <remarks> /// Quote from ARB_half_float_pixel specification: /// Any representable 16-bit floating-point value is legal as input to a GL command that accepts 16-bit floating-point data. The /// result of providing a value that is not a floating-point number (such as infinity or NaN) to such a command is unspecified, /// but must not lead to GL interruption or termination. Providing a denormalized number or negative zero to GL must yield /// predictable results. /// </remarks> [Serializable, StructLayout(LayoutKind.Sequential)] public struct Half : ISerializable, IComparable<Half>, IFormattable, IEquatable<Half> { #region Internal Field UInt16 bits; #endregion Internal Field #region Properties /// <summary>Returns true if the Half is zero.</summary> public bool IsZero { get { return (bits == 0) || (bits == 0x8000); } } /// <summary>Returns true if the Half represents Not A Number (NaN)</summary> public bool IsNaN { get { return (((bits & 0x7C00) == 0x7C00) && (bits & 0x03FF) != 0x0000); } } /// <summary>Returns true if the Half represents positive infinity.</summary> public bool IsPositiveInfinity { get { return (bits == 31744); } } /// <summary>Returns true if the Half represents negative infinity.</summary> public bool IsNegativeInfinity { get { return (bits == 64512); } } #endregion Properties #region Constructors /// <summary> /// The new Half instance will convert the parameter into 16-bit half-precision floating-point. /// </summary> /// <param name="f">32-bit single-precision floating-point number.</param> public Half(Single f) : this() { unsafe { bits = SingleToHalf(*(int*)&f); } } /// <summary> /// The new Half instance will convert the parameter into 16-bit half-precision floating-point. /// </summary> /// <param name="f">32-bit single-precision floating-point number.</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> public Half(Single f, bool throwOnError) : this(f) { if (throwOnError) { // handle cases that cause overflow rather than silently ignoring it if (f > Half.MaxValue) throw new ArithmeticException("Half: Positive maximum value exceeded."); if (f < -Half.MaxValue) throw new ArithmeticException("Half: Negative minimum value exceeded."); // handle cases that make no sense if (Single.IsNaN(f)) throw new ArithmeticException("Half: Input is not a number (NaN)."); if (Single.IsPositiveInfinity(f)) throw new ArithmeticException("Half: Input is positive infinity."); if (Single.IsNegativeInfinity(f)) throw new ArithmeticException("Half: Input is negative infinity."); } } /// <summary> /// The new Half instance will convert the parameter into 16-bit half-precision floating-point. /// </summary> /// <param name="d">64-bit double-precision floating-point number.</param> public Half(Double d) : this((Single)d) { } /// <summary> /// The new Half instance will convert the parameter into 16-bit half-precision floating-point. /// </summary> /// <param name="d">64-bit double-precision floating-point number.</param> /// <param name="throwOnError">Enable checks that will throw if the conversion result is not meaningful.</param> public Half(Double d, bool throwOnError) : this((Single)d, throwOnError) { } #endregion Constructors #region Single -> Half /// <summary>Ported from OpenEXR's IlmBase 1.0.1</summary> private UInt16 SingleToHalf(Int32 si32) { // Our floating point number, F, is represented by the bit pattern in integer i. // Disassemble that bit pattern into the sign, S, the exponent, E, and the significand, M. // Shift S into the position where it will go in in the resulting half number. // Adjust E, accounting for the different exponent bias of float and half (127 versus 15). Int32 sign = (si32 >> 16) & 0x00008000; Int32 exponent = ((si32 >> 23) & 0x000000ff) - (127 - 15); Int32 mantissa = si32 & 0x007fffff; // Now reassemble S, E and M into a half: if (exponent <= 0) { if (exponent < -10) { // E is less than -10. The absolute value of F is less than Half.MinValue // (F may be a small normalized float, a denormalized float or a zero). // // We convert F to a half zero with the same sign as F. return (UInt16)sign; } // E is between -10 and 0. F is a normalized float whose magnitude is less than Half.MinNormalizedValue. // // We convert F to a denormalized half. // Add an explicit leading 1 to the significand. mantissa = mantissa | 0x00800000; // Round to M to the nearest (10+E)-bit value (with E between -10 and 0); in case of a tie, round to the nearest even value. // // Rounding may cause the significand to overflow and make our number normalized. Because of the way a half's bits // are laid out, we don't have to treat this case separately; the code below will handle it correctly. Int32 t = 14 - exponent; Int32 a = (1 << (t - 1)) - 1; Int32 b = (mantissa >> t) & 1; mantissa = (mantissa + a + b) >> t; // Assemble the half from S, E (==zero) and M. return (UInt16)(sign | mantissa); } else if (exponent == 0xff - (127 - 15)) { if (mantissa == 0) { // F is an infinity; convert F to a half infinity with the same sign as F. return (UInt16)(sign | 0x7c00); } else { // F is a NAN; we produce a half NAN that preserves the sign bit and the 10 leftmost bits of the // significand of F, with one exception: If the 10 leftmost bits are all zero, the NAN would turn // into an infinity, so we have to set at least one bit in the significand. mantissa >>= 13; return (UInt16)(sign | 0x7c00 | mantissa | ((mantissa == 0) ? 1 : 0)); } } else { // E is greater than zero. F is a normalized float. We try to convert F to a normalized half. // Round to M to the nearest 10-bit value. In case of a tie, round to the nearest even value. mantissa = mantissa + 0x00000fff + ((mantissa >> 13) & 1); if ((mantissa & 0x00800000) != 0) { mantissa = 0; // overflow in significand, exponent += 1; // adjust exponent } // exponent overflow if (exponent > 30) throw new ArithmeticException("Half: Hardware floating-point overflow."); // Assemble the half from S, E and M. return (UInt16)(sign | (exponent << 10) | (mantissa >> 13)); } } #endregion Single -> Half #region Half -> Single /// <summary>Converts the 16-bit half to 32-bit floating-point.</summary> /// <returns>A single-precision floating-point number.</returns> public Single ToSingle() { int i = HalfToFloat(bits); unsafe { return *(float*)&i; } } /// <summary>Ported from OpenEXR's IlmBase 1.0.1</summary> private Int32 HalfToFloat(UInt16 ui16) { Int32 sign = (ui16 >> 15) & 0x00000001; Int32 exponent = (ui16 >> 10) & 0x0000001f; Int32 mantissa = ui16 & 0x000003ff; if (exponent == 0) { if (mantissa == 0) { // Plus or minus zero return sign << 31; } else { // Denormalized number -- renormalize it while ((mantissa & 0x00000400) == 0) { mantissa <<= 1; exponent -= 1; } exponent += 1; mantissa &= ~0x00000400; } } else if (exponent == 31) { if (mantissa == 0) { // Positive or negative infinity return (sign << 31) | 0x7f800000; } else { // Nan -- preserve sign and significand bits return (sign << 31) | 0x7f800000 | (mantissa << 13); } } // Normalized number exponent = exponent + (127 - 15); mantissa = mantissa << 13; // Assemble S, E and M. return (sign << 31) | (exponent << 23) | mantissa; } #endregion Half -> Single #region Conversions /// <summary> /// Converts a System.Single to a OpenTK.Half. /// </summary> /// <param name="f">The value to convert. /// A <see cref="System.Single"/> /// </param> /// <returns>The result of the conversion. /// A <see cref="Half"/> /// </returns> public static explicit operator Half(float f) { return new Half(f); } /// <summary> /// Converts a System.Double to a OpenTK.Half. /// </summary> /// <param name="d">The value to convert. /// A <see cref="System.Double"/> /// </param> /// <returns>The result of the conversion. /// A <see cref="Half"/> /// </returns> public static explicit operator Half(double d) { return new Half(d); } /// <summary> /// Converts a OpenTK.Half to a System.Single. /// </summary> /// <param name="h">The value to convert. /// A <see cref="Half"/> /// </param> /// <returns>The result of the conversion. /// A <see cref="System.Single"/> /// </returns> public static implicit operator float(Half h) { return h.ToSingle(); } /// <summary> /// Converts a OpenTK.Half to a System.Double. /// </summary> /// <param name="h">The value to convert. /// A <see cref="Half"/> /// </param> /// <returns>The result of the conversion. /// A <see cref="System.Double"/> /// </returns> public static implicit operator double(Half h) { return (double)h.ToSingle(); } #endregion Conversions #region Constants /// <summary>The size in bytes for an instance of the Half struct.</summary> public static readonly Int32 SizeInBytes = 2; /// <summary>Smallest positive half</summary> public static readonly Single MinValue = 5.96046448e-08f; /// <summary>Smallest positive normalized half</summary> public static readonly Single MinNormalizedValue = 6.10351562e-05f; /// <summary>Largest positive half</summary> public static readonly Single MaxValue = 65504.0f; /// <summary>Smallest positive e for which half (1.0 + e) != half (1.0)</summary> public static readonly Single Epsilon = 0.00097656f; #endregion Constants #region ISerializable /// <summary>Constructor used by ISerializable to deserialize the object.</summary> /// <param name="info"></param> /// <param name="context"></param> public Half(SerializationInfo info, StreamingContext context) { this.bits = (ushort)info.GetValue("bits", typeof(ushort)); } /// <summary>Used by ISerialize to serialize the object.</summary> /// <param name="info"></param> /// <param name="context"></param> public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("bits", this.bits); } #endregion ISerializable #region Binary dump /// <summary>Updates the Half by reading from a Stream.</summary> /// <param name="bin">A BinaryReader instance associated with an open Stream.</param> public void FromBinaryStream(BinaryReader bin) { this.bits = bin.ReadUInt16(); } /// <summary>Writes the Half into a Stream.</summary> /// <param name="bin">A BinaryWriter instance associated with an open Stream.</param> public void ToBinaryStream(BinaryWriter bin) { bin.Write(this.bits); } #endregion Binary dump #region IEquatable<Half> Members const int maxUlps = 1; /// <summary> /// Returns a value indicating whether this instance is equal to a specified OpenTK.Half value. /// </summary> /// <param name="other">OpenTK.Half object to compare to this instance..</param> /// <returns>True, if other is equal to this instance; false otherwise.</returns> public bool Equals(Half other) { short aInt, bInt; unchecked { aInt = (short)other.bits; } unchecked { bInt = (short)this.bits; } // Make aInt lexicographically ordered as a twos-complement int if (aInt < 0) aInt = (short)(0x8000 - aInt); // Make bInt lexicographically ordered as a twos-complement int if (bInt < 0) bInt = (short)(0x8000 - bInt); short intDiff = System.Math.Abs((short)(aInt - bInt)); if (intDiff <= maxUlps) return true; return false; } #endregion #region IComparable<Half> Members /// <summary> /// Compares this instance to a specified half-precision floating-point number /// and returns an integer that indicates whether the value of this instance /// is less than, equal to, or greater than the value of the specified half-precision /// floating-point number. /// </summary> /// <param name="other">A half-precision floating-point number to compare.</param> /// <returns> /// A signed number indicating the relative values of this instance and value. If the number is: /// <para>Less than zero, then this instance is less than other, or this instance is not a number /// (OpenTK.Half.NaN) and other is a number.</para> /// <para>Zero: this instance is equal to value, or both this instance and other /// are not a number (OpenTK.Half.NaN), OpenTK.Half.PositiveInfinity, or /// OpenTK.Half.NegativeInfinity.</para> /// <para>Greater than zero: this instance is greater than othrs, or this instance is a number /// and other is not a number (OpenTK.Half.NaN).</para> /// </returns> public int CompareTo(Half other) { return ((float)this).CompareTo((float)other); } #endregion IComparable<Half> Members #region IFormattable Members /// <summary>Converts this Half into a human-legible string representation.</summary> /// <returns>The string representation of this instance.</returns> public override string ToString() { return this.ToSingle().ToString(); } /// <summary>Converts this Half into a human-legible string representation.</summary> /// <param name="format">Formatting for the output string.</param> /// <param name="formatProvider">Culture-specific formatting information.</param> /// <returns>The string representation of this instance.</returns> public string ToString(string format, IFormatProvider formatProvider) { return this.ToSingle().ToString(format, formatProvider); } #endregion IFormattable Members #region String -> Half /// <summary>Converts the string representation of a number to a half-precision floating-point equivalent.</summary> /// <param name="s">String representation of the number to convert.</param> /// <returns>A new Half instance.</returns> public static Half Parse(string s) { return (Half)Single.Parse(s); } /// <summary>Converts the string representation of a number to a half-precision floating-point equivalent.</summary> /// <param name="s">String representation of the number to convert.</param> /// <param name="style">Specifies the format of s.</param> /// <param name="provider">Culture-specific formatting information.</param> /// <returns>A new Half instance.</returns> public static Half Parse(string s, System.Globalization.NumberStyles style, IFormatProvider provider) { return (Half)Single.Parse(s, style, provider); } /// <summary>Converts the string representation of a number to a half-precision floating-point equivalent. Returns success.</summary> /// <param name="s">String representation of the number to convert.</param> /// <param name="result">The Half instance to write to.</param> /// <returns>Success.</returns> public static bool TryParse(string s, out Half result) { float f; bool b = Single.TryParse(s, out f); result = (Half)f; return b; } /// <summary>Converts the string representation of a number to a half-precision floating-point equivalent. Returns success.</summary> /// <param name="s">String representation of the number to convert.</param> /// <param name="style">Specifies the format of s.</param> /// <param name="provider">Culture-specific formatting information.</param> /// <param name="result">The Half instance to write to.</param> /// <returns>Success.</returns> public static bool TryParse(string s, System.Globalization.NumberStyles style, IFormatProvider provider, out Half result) { float f; bool b = Single.TryParse(s, style, provider, out f); result = (Half)f; return b; } #endregion String -> Half #region BitConverter /// <summary>Returns the Half as an array of bytes.</summary> /// <param name="h">The Half to convert.</param> /// <returns>The input as byte array.</returns> public static byte[] GetBytes(Half h) { return BitConverter.GetBytes(h.bits); } /// <summary>Converts an array of bytes into Half.</summary> /// <param name="value">A Half in it's byte[] representation.</param> /// <param name="startIndex">The starting position within value.</param> /// <returns>A new Half instance.</returns> public static Half FromBytes(byte[] value, int startIndex) { Half h; h.bits = BitConverter.ToUInt16(value, startIndex); return h; } #endregion BitConverter } }
//////////////////////////////////////////////////////////////////////////////// // // // MIT X11 license, Copyright (c) 2005-2006 by: // // // // Authors: // // Michael Dominic K. <michaldominik@gmail.com> // // // // Permission is hereby granted, free of charge, to any person obtaining a // // copy of this software and associated documentation files (the "Software"), // // to deal in the Software without restriction, including without limitation // // the rights to use, copy, modify, merge, publish, distribute, sublicense, // // and/or sell copies of the Software, and to permit persons to whom the // // Software is furnished to do so, subject to the following conditions: // // // // The above copyright notice and this permission notice shall be included // // in all copies or substantial portions of the Software. // // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // // USE OR OTHER DEALINGS IN THE SOFTWARE. // // // //////////////////////////////////////////////////////////////////////////////// namespace Diva.Util { using Gdk; using Gtk; using System; public static class GtkFu { // Public methods ////////////////////////////////////////////// /* Now, I have no *fcking clue why Gtk.Window.ParseGeometry doesn't * work like expected. Franky, I don't care */ public static void ParseGeometry (Gtk.Window win, string str) { int x = -1; int y = -1; int width = -1; int height = -1; try { string[] matches = str.Split ('x', '+'); if (matches.Length == 0) throw new Exception (); if (matches.Length == 1) throw new Exception (); width = Convert.ToInt32 (matches[0]); height = Convert.ToInt32 (matches[1]); if (matches.Length > 2) x = Convert.ToInt32 (matches [2]); if (matches.Length > 3) y = Convert.ToInt32 (matches [3]); } catch { } finally { if (width != -1 && height != -1) win.Resize (width, height); if (x != -1 && y != -1) win.Move (x, y); } } /* Convert x, y, widdth, height into a X-geometry like string */ public static string GetGeometry (Gtk.Window win) { int width, height, x, y; win.GetSize (out width, out height); win.GetPosition (out x, out y); return String.Format ("{0}x{1}+{2}+{3}", width, height, x, y); } /* Find the iter that represents the given object in a model */ public static TreeIter TreeModelIterByObject (TreeModel model, object searched, int clmn) { TreeIter iter; model.GetIterFirst (out iter); do { object currentObject = model.GetValue (iter, clmn); if (currentObject == searched) // Success return iter; } while (model.IterNext (ref iter)); // Failure return TreeIter.Zero; } /* Find the iter that represents the given int in a model */ public static TreeIter TreeModelIterByInt (TreeModel model, int searched, int clmn) { TreeIter iter; model.GetIterFirst (out iter); do { int current = (int) model.GetValue (iter, clmn); if (current == searched) // Success return iter; } while (model.IterNext (ref iter)); // Failure return TreeIter.Zero; } /* If a given span intersects with another one */ public static bool LinearIntersectsWith (int s1, int e1, int s2, int e2) { if (s1 == e1 || s2 == e2) return false; // equals if (s1 == s2 && e1 == e2) return true; // contained in if (s1 < s2 && e1 > e2) return true; if (s2 < s1 && e2 > e1) return true; // start or end in if (s2 >= s1 && s2 < e1) return true; if (e2 > s1 && e2 < e1) return true; if (s1 >= s2 && s1 < e2) return true; if (e1 > s2 && e1 < e2) return true; return false; } /* Get a linear intersection of two regions */ public static void LinearGetIntersection (int s1, int e1, int s2, int e2, out int s3, out int e3) { // equals if (s1 == s2 && e1 == e2) { s3 = s1; e3 = e1; return; } // contained in if (s1 < s2 && e1 > e2) { s3 = s2; e3 = e2; return; } if (s2 < s1 && e2 > e1) { s3 = s1; e3 = e1; return; } // start or end in if (s2 >= s1 && s2 < e1) { s3 = s2; e3 = e1; return; } if (e2 > s1 && e2 < e1) { s3 = s1; e3 = e2; return; } if (s1 >= s2 && s1 < e2) { s3 = s1; e3 = e2; return; } if (e1 > s2 && e1 < e2) { s3 = s2; e3 = e1; return; } s3 = 0; e3 = 0; } /* Check if two Rectangles intersect */ public static bool RectanglesIntersect (Rectangle r1, Rectangle r2) { if (LinearIntersectsWith (r1.Left, r1.Right, r2.Left, r2.Right) && LinearIntersectsWith (r1.Top, r1.Bottom, r2.Top, r2.Bottom)) return true; else return false; } /* Get an intersection between two rectangles */ public static Rectangle GetIntersection (Rectangle r1, Rectangle r2) { if (! RectanglesIntersect (r1, r2)) return Rectangle.Zero; int hs, he; LinearGetIntersection (r1.Left, r1.Right, r2.Left, r2.Right, out hs, out he); int vs, ve; LinearGetIntersection (r1.Top, r1.Bottom, r2.Top, r2.Bottom, out vs, out ve); return new Rectangle (hs, vs, he - hs, ve - vs); } public static Gtk.Window GetParentForWidget (Widget widget) { Gtk.Window parent = null; try { if (widget is Gtk.Window) return widget as Gtk.Window; if (widget != null && widget.Toplevel != null) parent = (widget.Toplevel as Gtk.Window); // FIXME: Check for toplevel widget flags } catch (Exception excp) { parent = null; } return parent; } } }
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using NLog.Config; using NLog.LayoutRenderers; using NLog.Layouts; /// <summary> /// Sends log messages to the remote instance of NLog Viewer. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/NLogViewer-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/NLogViewer/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/NLogViewer/Simple/Example.cs" /> /// <p> /// NOTE: If your receiver application is ever likely to be off-line, don't use TCP protocol /// or you'll get TCP timeouts and your application will crawl. /// Either switch to UDP transport or use <a href="target.AsyncWrapper.html">AsyncWrapper</a> target /// so that your application threads will not be blocked by the timing-out connection attempts. /// </p> /// </example> [Target("NLogViewer")] public class NLogViewerTarget : NetworkTarget, IIncludeContext { private readonly Log4JXmlEventLayout _log4JLayout = new Log4JXmlEventLayout(); /// <summary> /// Initializes a new instance of the <see cref="NLogViewerTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> public NLogViewerTarget() { Parameters = new List<NLogViewerParameterInfo>(); Renderer.Parameters = Parameters; OnConnectionOverflow = NetworkTargetConnectionsOverflowAction.Block; MaxConnections = 16; NewLine = false; OptimizeBufferReuse = GetType() == typeof(NLogViewerTarget); // Class not sealed, reduce breaking changes } /// <summary> /// Initializes a new instance of the <see cref="NLogViewerTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> /// <param name="name">Name of the target.</param> public NLogViewerTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets a value indicating whether to include NLog-specific extensions to log4j schema. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeNLogData { get => Renderer.IncludeNLogData; set => Renderer.IncludeNLogData = value; } /// <summary> /// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain. /// </summary> /// <docgen category='Payload Options' order='10' /> public string AppInfo { get => Renderer.AppInfo; set => Renderer.AppInfo = value; } /// <summary> /// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeCallSite { get => Renderer.IncludeCallSite; set => Renderer.IncludeCallSite = value; } #if !SILVERLIGHT /// <summary> /// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeSourceInfo { get => Renderer.IncludeSourceInfo; set => Renderer.IncludeSourceInfo = value; } #endif /// <summary> /// Gets or sets a value indicating whether to include <see cref="MappedDiagnosticsContext"/> dictionary contents. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeMdc { get => Renderer.IncludeMdc; set => Renderer.IncludeMdc = value; } /// <summary> /// Gets or sets a value indicating whether to include <see cref="NestedDiagnosticsContext"/> stack contents. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeNdc { get => Renderer.IncludeNdc; set => Renderer.IncludeNdc = value; } #if !SILVERLIGHT /// <summary> /// Gets or sets a value indicating whether to include <see cref="MappedDiagnosticsLogicalContext"/> dictionary contents. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeMdlc { get => Renderer.IncludeMdlc; set => Renderer.IncludeMdlc = value; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsLogicalContext"/> stack. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeNdlc { get => Renderer.IncludeNdlc; set => Renderer.IncludeNdlc = value; } /// <summary> /// Gets or sets the NDLC item separator. /// </summary> /// <docgen category='Payload Options' order='10' /> public string NdlcItemSeparator { get => Renderer.NdlcItemSeparator; set => Renderer.NdlcItemSeparator = value; } #endif /// <summary> /// Gets or sets the option to include all properties from the log events /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeAllProperties { get => Renderer.IncludeAllProperties; set => Renderer.IncludeAllProperties = value; } /// <summary> /// Gets or sets the NDC item separator. /// </summary> /// <docgen category='Payload Options' order='10' /> public string NdcItemSeparator { get => Renderer.NdcItemSeparator; set => Renderer.NdcItemSeparator = value; } /// <summary> /// Gets or sets the renderer for log4j:event logger-xml-attribute (Default ${logger}) /// </summary> /// <docgen category='Payload Options' order='10' /> public Layout LoggerName { get => Renderer.LoggerName; set => Renderer.LoggerName = value; } /// <summary> /// Gets the collection of parameters. Each parameter contains a mapping /// between NLog layout and a named parameter. /// </summary> /// <docgen category='Payload Options' order='10' /> [ArrayParameter(typeof(NLogViewerParameterInfo), "parameter")] public IList<NLogViewerParameterInfo> Parameters { get; private set; } /// <summary> /// Gets the layout renderer which produces Log4j-compatible XML events. /// </summary> [NLogConfigurationIgnoreProperty] public Log4JXmlEventLayoutRenderer Renderer => _log4JLayout.Renderer; /// <summary> /// Gets or sets the instance of <see cref="Log4JXmlEventLayout"/> that is used to format log messages. /// </summary> /// <docgen category='Layout Options' order='10' /> public override Layout Layout { get { return _log4JLayout; } set { // Fixed Log4JXmlEventLayout } } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Xml; using Orleans.GrainDirectory; using Orleans.Providers; using Orleans.Storage; using Orleans.Streams; using Orleans.LogConsistency; using Orleans.Versions.Compatibility; using Orleans.Versions.Selector; namespace Orleans.Runtime.Configuration { // helper utility class to handle default vs. explicitly set config value. [Serializable] internal class ConfigValue<T> { public T Value; public bool IsDefaultValue; public ConfigValue(T val, bool isDefaultValue) { Value = val; IsDefaultValue = isDefaultValue; } } /// <summary> /// Data object holding Silo global configuration parameters. /// </summary> [Serializable] public class GlobalConfiguration : MessagingConfiguration { private const string DefaultClusterId = "DefaultClusterID"; // if no id is configured, we pick a nonempty default. /// <summary> /// Liveness configuration that controls the type of the liveness protocol that silo use for membership. /// </summary> public enum LivenessProviderType { /// <summary>Default value to allow discrimination of override values.</summary> NotSpecified, /// <summary>Grain is used to store membership information. /// This option is not reliable and thus should only be used in local development setting.</summary> MembershipTableGrain, /// <summary>AzureTable is used to store membership information. /// This option can be used in production.</summary> AzureTable, /// <summary>SQL Server is used to store membership information. /// This option can be used in production.</summary> SqlServer, /// <summary>Apache ZooKeeper is used to store membership information. /// This option can be used in production.</summary> ZooKeeper, /// <summary>Use custom provider from third-party assembly</summary> Custom } /// <summary> /// Reminders configuration that controls the type of the protocol that silo use to implement Reminders. /// </summary> public enum ReminderServiceProviderType { /// <summary>Default value to allow discrimination of override values.</summary> NotSpecified, /// <summary>Grain is used to store reminders information. /// This option is not reliable and thus should only be used in local development setting.</summary> ReminderTableGrain, /// <summary>AzureTable is used to store reminders information. /// This option can be used in production.</summary> AzureTable, /// <summary>SQL Server is used to store reminders information. /// This option can be used in production.</summary> SqlServer, /// <summary>Used for benchmarking; it simply delays for a specified delay during each operation.</summary> MockTable, /// <summary>Reminder Service is disabled.</summary> Disabled, /// <summary>Use custom Reminder Service from third-party assembly</summary> Custom } /// <summary> /// Configuration for Gossip Channels /// </summary> public enum GossipChannelType { /// <summary>Default value to allow discrimination of override values.</summary> NotSpecified, /// <summary>An Azure Table serving as a channel. </summary> AzureTable, } /// <summary> /// Gossip channel configuration. /// </summary> [Serializable] public class GossipChannelConfiguration { /// <summary>Gets or sets the gossip channel type.</summary> public GossipChannelType ChannelType { get; set; } /// <summary>Gets or sets the credential information used by the channel implementation.</summary> public string ConnectionString { get; set; } } /// <summary> /// Configuration type that controls the type of the grain directory caching algorithm that silo use. /// </summary> public enum DirectoryCachingStrategyType { /// <summary>Don't cache.</summary> None, /// <summary>Standard fixed-size LRU.</summary> LRU, /// <summary>Adaptive caching with fixed maximum size and refresh. This option should be used in production.</summary> Adaptive } public ApplicationConfiguration Application { get; private set; } /// <summary> /// SeedNodes are only used in local development setting with LivenessProviderType.MembershipTableGrain /// SeedNodes are never used in production. /// </summary> public IList<IPEndPoint> SeedNodes { get; private set; } /// <summary> /// The subnet on which the silos run. /// This option should only be used when running on multi-homed cluster. It should not be used when running in Azure. /// </summary> public byte[] Subnet { get; set; } /// <summary> /// Determines if primary node is required to be configured as a seed node. /// True if LivenessType is set to MembershipTableGrain, false otherwise. /// </summary> public bool PrimaryNodeIsRequired { get { return LivenessType == LivenessProviderType.MembershipTableGrain; } } /// <summary> /// Global switch to disable silo liveness protocol (should be used only for testing). /// The LivenessEnabled attribute, if provided and set to "false", suppresses liveness enforcement. /// If a silo is suspected to be dead, but this attribute is set to "false", the suspicions will not propagated to the system and enforced, /// This parameter is intended for use only for testing and troubleshooting. /// In production, liveness should always be enabled. /// Default is true (eanabled) /// </summary> public bool LivenessEnabled { get; set; } /// <summary> /// The number of seconds to periodically probe other silos for their liveness or for the silo to send "I am alive" heartbeat messages about itself. /// </summary> public TimeSpan ProbeTimeout { get; set; } /// <summary> /// The number of seconds to periodically fetch updates from the membership table. /// </summary> public TimeSpan TableRefreshTimeout { get; set; } /// <summary> /// Expiration time in seconds for death vote in the membership table. /// </summary> public TimeSpan DeathVoteExpirationTimeout { get; set; } /// <summary> /// The number of seconds to periodically write in the membership table that this silo is alive. Used ony for diagnostics. /// </summary> public TimeSpan IAmAliveTablePublishTimeout { get; set; } /// <summary> /// The number of seconds to attempt to join a cluster of silos before giving up. /// </summary> public TimeSpan MaxJoinAttemptTime { get; set; } /// <summary> /// The number of seconds to refresh the cluster grain interface map /// </summary> public TimeSpan TypeMapRefreshInterval { get; set; } internal ConfigValue<int> ExpectedClusterSizeConfigValue { get; set; } /// <summary> /// The expected size of a cluster. Need not be very accurate, can be an overestimate. /// </summary> public int ExpectedClusterSize { get { return ExpectedClusterSizeConfigValue.Value; } set { ExpectedClusterSizeConfigValue = new ConfigValue<int>(value, false); } } /// <summary> /// The number of missed "I am alive" heartbeat messages from a silo or number of un-replied probes that lead to suspecting this silo as dead. /// </summary> public int NumMissedProbesLimit { get; set; } /// <summary> /// The number of silos each silo probes for liveness. /// </summary> public int NumProbedSilos { get; set; } /// <summary> /// The number of non-expired votes that are needed to declare some silo as dead (should be at most NumMissedProbesLimit) /// </summary> public int NumVotesForDeathDeclaration { get; set; } /// <summary> /// The number of missed "I am alive" updates in the table from a silo that causes warning to be logged. Does not impact the liveness protocol. /// </summary> public int NumMissedTableIAmAliveLimit { get; set; } /// <summary> /// Whether to use the gossip optimization to speed up spreading liveness information. /// </summary> public bool UseLivenessGossip { get; set; } /// <summary> /// Whether new silo that joins the cluster has to validate the initial connectivity with all other Active silos. /// </summary> public bool ValidateInitialConnectivity { get; set; } /// <summary> /// Service Id. /// </summary> public Guid ServiceId { get; set; } /// <summary> /// Deployment Id. /// </summary> public string DeploymentId { get; set; } #region MultiClusterNetwork private string clusterId; /// <summary> /// Whether this cluster is configured to be part of a multicluster network /// </summary> public bool HasMultiClusterNetwork { get { return !(string.IsNullOrEmpty(this.clusterId)); } } /// <summary> /// Cluster id (one per deployment, unique across all the deployments/clusters) /// </summary> public string ClusterId { get { var configuredId = this.HasMultiClusterNetwork ? this.clusterId : this.DeploymentId; return string.IsNullOrEmpty(configuredId) ? DefaultClusterId : configuredId; } set { this.clusterId = value; } } /// <summary> ///A list of cluster ids, to be used if no multicluster configuration is found in gossip channels. /// </summary> public IReadOnlyList<string> DefaultMultiCluster { get; set; } /// <summary> /// The maximum number of silos per cluster should be designated to serve as gateways. /// </summary> public int MaxMultiClusterGateways { get; set; } /// <summary> /// The time between background gossips. /// </summary> public TimeSpan BackgroundGossipInterval { get; set; } /// <summary> /// Whether to use the global single instance protocol as the default /// multicluster registration strategy. /// </summary> public bool UseGlobalSingleInstanceByDefault { get; set; } /// <summary> /// The number of quick retries before going into DOUBTFUL state. /// </summary> public int GlobalSingleInstanceNumberRetries { get; set; } /// <summary> /// The time between the slow retries for DOUBTFUL activations. /// </summary> public TimeSpan GlobalSingleInstanceRetryInterval { get; set; } /// <summary> /// A list of connection strings for gossip channels. /// </summary> public IReadOnlyList<GossipChannelConfiguration> GossipChannels { get; set; } #endregion /// <summary> /// Connection string for the underlying data provider for liveness and reminders. eg. Azure Storage, ZooKeeper, SQL Server, ect. /// In order to override this value for reminders set <see cref="DataConnectionStringForReminders"/> /// </summary> public string DataConnectionString { get; set; } /// <summary> /// When using ADO, identifies the underlying data provider for liveness and reminders. This three-part naming syntax is also used /// when creating a new factory and for identifying the provider in an application configuration file so that the provider name, /// along with its associated connection string, can be retrieved at run time. https://msdn.microsoft.com/en-us/library/dd0w4a2z%28v=vs.110%29.aspx /// In order to override this value for reminders set <see cref="AdoInvariantForReminders"/> /// </summary> public string AdoInvariant { get; set; } /// <summary> /// Set this property to override <see cref="DataConnectionString"/> for reminders. /// </summary> public string DataConnectionStringForReminders { get { return string.IsNullOrWhiteSpace(dataConnectionStringForReminders) ? DataConnectionString : dataConnectionStringForReminders; } set { dataConnectionStringForReminders = value; } } /// <summary> /// Set this property to override <see cref="AdoInvariant"/> for reminders. /// </summary> public string AdoInvariantForReminders { get { return string.IsNullOrWhiteSpace(adoInvariantForReminders) ? AdoInvariant : adoInvariantForReminders; } set { adoInvariantForReminders = value; } } internal TimeSpan CollectionQuantum { get; set; } /// <summary> /// Specifies the maximum time that a request can take before the activation is reported as "blocked" /// </summary> public TimeSpan MaxRequestProcessingTime { get; set; } /// <summary> /// The CacheSize attribute specifies the maximum number of grains to cache directory information for. /// </summary> public int CacheSize { get; set; } /// <summary> /// The InitialTTL attribute specifies the initial (minimum) time, in seconds, to keep a cache entry before revalidating. /// </summary> public TimeSpan InitialCacheTTL { get; set; } /// <summary> /// The MaximumTTL attribute specifies the maximum time, in seconds, to keep a cache entry before revalidating. /// </summary> public TimeSpan MaximumCacheTTL { get; set; } /// <summary> /// The TTLExtensionFactor attribute specifies the factor by which cache entry TTLs should be extended when they are found to be stable. /// </summary> public double CacheTTLExtensionFactor { get; set; } /// <summary> /// Retry count for Azure Table operations. /// </summary> public int MaxStorageBusyRetries { get; private set; } /// <summary> /// The DirectoryCachingStrategy attribute specifies the caching strategy to use. /// The options are None, which means don't cache directory entries locally; /// LRU, which indicates that a standard fixed-size least recently used strategy should be used; and /// Adaptive, which indicates that an adaptive strategy with a fixed maximum size should be used. /// The Adaptive strategy is used by default. /// </summary> public DirectoryCachingStrategyType DirectoryCachingStrategy { get; set; } public bool UseVirtualBucketsConsistentRing { get; set; } public int NumVirtualBucketsConsistentRing { get; set; } /// <summary> /// The LivenessType attribute controls the liveness method used for silo reliability. /// </summary> private LivenessProviderType livenessServiceType; public LivenessProviderType LivenessType { get { return livenessServiceType; } set { if (value == LivenessProviderType.NotSpecified) throw new ArgumentException("Cannot set LivenessType to " + LivenessProviderType.NotSpecified, "LivenessType"); livenessServiceType = value; } } /// <summary> /// Assembly to use for custom MembershipTable implementation /// </summary> public string MembershipTableAssembly { get; set; } /// <summary> /// Assembly to use for custom ReminderTable implementation /// </summary> public string ReminderTableAssembly { get; set; } /// <summary> /// The ReminderServiceType attribute controls the type of the reminder service implementation used by silos. /// </summary> private ReminderServiceProviderType reminderServiceType; public ReminderServiceProviderType ReminderServiceType { get { return reminderServiceType; } set { SetReminderServiceType(value); } } // It's a separate function so we can clearly see when we set the value. // With property you can't seaprate getter from setter in intellicense. internal void SetReminderServiceType(ReminderServiceProviderType reminderType) { if (reminderType == ReminderServiceProviderType.NotSpecified) throw new ArgumentException("Cannot set ReminderServiceType to " + ReminderServiceProviderType.NotSpecified, "ReminderServiceType"); reminderServiceType = reminderType; } public TimeSpan MockReminderTableTimeout { get; set; } internal bool UseMockReminderTable; /// <summary> /// Configuration for various runtime providers. /// </summary> public IDictionary<string, ProviderCategoryConfiguration> ProviderConfigurations { get; set; } /// <summary> /// Configuration for grain services. /// </summary> public GrainServiceConfigurations GrainServiceConfigurations { get; set; } /// <summary> /// The time span between when we have added an entry for an activation to the grain directory and when we are allowed /// to conditionally remove that entry. /// Conditional deregistration is used for lazy clean-up of activations whose prompt deregistration failed for some reason (e.g., message failure). /// This should always be at least one minute, since we compare the times on the directory partition, so message delays and clcks skues have /// to be allowed. /// </summary> public TimeSpan DirectoryLazyDeregistrationDelay { get; set; } public TimeSpan ClientRegistrationRefresh { get; set; } internal bool PerformDeadlockDetection { get; set; } public string DefaultPlacementStrategy { get; set; } public CompatibilityStrategy DefaultCompatibilityStrategy { get; set; } public VersionSelectorStrategy DefaultVersionSelectorStrategy { get; set; } public TimeSpan DeploymentLoadPublisherRefreshTime { get; set; } public int ActivationCountBasedPlacementChooseOutOf { get; set; } public bool AssumeHomogenousSilosForTesting { get; set; } public bool FastKillOnCancelKeyPress { get; set; } /// <summary> /// Determines if ADO should be used for storage of Membership and Reminders info. /// True if either or both of LivenessType and ReminderServiceType are set to SqlServer, false otherwise. /// </summary> internal bool UseSqlSystemStore { get { return !String.IsNullOrWhiteSpace(DataConnectionString) && ( (LivenessEnabled && LivenessType == LivenessProviderType.SqlServer) || ReminderServiceType == ReminderServiceProviderType.SqlServer); } } /// <summary> /// Determines if ZooKeeper should be used for storage of Membership and Reminders info. /// True if LivenessType is set to ZooKeeper, false otherwise. /// </summary> internal bool UseZooKeeperSystemStore { get { return !String.IsNullOrWhiteSpace(DataConnectionString) && ( (LivenessEnabled && LivenessType == LivenessProviderType.ZooKeeper)); } } /// <summary> /// Determines if Azure Storage should be used for storage of Membership and Reminders info. /// True if either or both of LivenessType and ReminderServiceType are set to AzureTable, false otherwise. /// </summary> internal bool UseAzureSystemStore { get { return !String.IsNullOrWhiteSpace(DataConnectionString) && !UseSqlSystemStore && !UseZooKeeperSystemStore; } } internal bool RunsInAzure { get { return UseAzureSystemStore && !String.IsNullOrWhiteSpace(DeploymentId); } } private static readonly TimeSpan DEFAULT_LIVENESS_PROBE_TIMEOUT = TimeSpan.FromSeconds(10); private static readonly TimeSpan DEFAULT_LIVENESS_TABLE_REFRESH_TIMEOUT = TimeSpan.FromSeconds(60); private static readonly TimeSpan DEFAULT_LIVENESS_DEATH_VOTE_EXPIRATION_TIMEOUT = TimeSpan.FromSeconds(120); private static readonly TimeSpan DEFAULT_LIVENESS_I_AM_ALIVE_TABLE_PUBLISH_TIMEOUT = TimeSpan.FromMinutes(5); private static readonly TimeSpan DEFAULT_LIVENESS_MAX_JOIN_ATTEMPT_TIME = TimeSpan.FromMinutes(5); // 5 min private static readonly TimeSpan DEFAULT_REFRESH_CLUSTER_INTERFACEMAP_TIME = TimeSpan.FromMinutes(1); private const int DEFAULT_LIVENESS_NUM_MISSED_PROBES_LIMIT = 3; private const int DEFAULT_LIVENESS_NUM_PROBED_SILOS = 3; private const int DEFAULT_LIVENESS_NUM_VOTES_FOR_DEATH_DECLARATION = 2; private const int DEFAULT_LIVENESS_NUM_TABLE_I_AM_ALIVE_LIMIT = 2; private const bool DEFAULT_LIVENESS_USE_LIVENESS_GOSSIP = true; private const bool DEFAULT_VALIDATE_INITIAL_CONNECTIVITY = true; private const int DEFAULT_MAX_MULTICLUSTER_GATEWAYS = 10; private const bool DEFAULT_USE_GLOBAL_SINGLE_INSTANCE = true; private static readonly TimeSpan DEFAULT_BACKGROUND_GOSSIP_INTERVAL = TimeSpan.FromSeconds(30); private static readonly TimeSpan DEFAULT_GLOBAL_SINGLE_INSTANCE_RETRY_INTERVAL = TimeSpan.FromSeconds(30); private const int DEFAULT_GLOBAL_SINGLE_INSTANCE_NUMBER_RETRIES = 10; private const int DEFAULT_LIVENESS_EXPECTED_CLUSTER_SIZE = 20; private const int DEFAULT_CACHE_SIZE = 1000000; private static readonly TimeSpan DEFAULT_INITIAL_CACHE_TTL = TimeSpan.FromSeconds(30); private static readonly TimeSpan DEFAULT_MAXIMUM_CACHE_TTL = TimeSpan.FromSeconds(240); private const double DEFAULT_TTL_EXTENSION_FACTOR = 2.0; private const DirectoryCachingStrategyType DEFAULT_DIRECTORY_CACHING_STRATEGY = DirectoryCachingStrategyType.Adaptive; internal static readonly TimeSpan DEFAULT_COLLECTION_QUANTUM = TimeSpan.FromMinutes(1); internal static readonly TimeSpan DEFAULT_COLLECTION_AGE_LIMIT = TimeSpan.FromHours(2); public static bool ENFORCE_MINIMUM_REQUIREMENT_FOR_AGE_LIMIT = true; private static readonly TimeSpan DEFAULT_UNREGISTER_RACE_DELAY = TimeSpan.FromMinutes(1); private static readonly TimeSpan DEFAULT_CLIENT_REGISTRATION_REFRESH = TimeSpan.FromMinutes(5); public const bool DEFAULT_PERFORM_DEADLOCK_DETECTION = false; public static readonly string DEFAULT_PLACEMENT_STRATEGY = typeof(RandomPlacement).Name; public static readonly string DEFAULT_MULTICLUSTER_REGISTRATION_STRATEGY = typeof(GlobalSingleInstanceRegistration).Name; private static readonly TimeSpan DEFAULT_DEPLOYMENT_LOAD_PUBLISHER_REFRESH_TIME = TimeSpan.FromSeconds(1); private const int DEFAULT_ACTIVATION_COUNT_BASED_PLACEMENT_CHOOSE_OUT_OF = 2; private const bool DEFAULT_USE_VIRTUAL_RING_BUCKETS = true; private const int DEFAULT_NUM_VIRTUAL_RING_BUCKETS = 30; private static readonly TimeSpan DEFAULT_MOCK_REMINDER_TABLE_TIMEOUT = TimeSpan.FromMilliseconds(50); private string dataConnectionStringForReminders; private string adoInvariantForReminders; internal GlobalConfiguration() : base(true) { Application = new ApplicationConfiguration(); SeedNodes = new List<IPEndPoint>(); livenessServiceType = LivenessProviderType.NotSpecified; LivenessEnabled = true; ProbeTimeout = DEFAULT_LIVENESS_PROBE_TIMEOUT; TableRefreshTimeout = DEFAULT_LIVENESS_TABLE_REFRESH_TIMEOUT; DeathVoteExpirationTimeout = DEFAULT_LIVENESS_DEATH_VOTE_EXPIRATION_TIMEOUT; IAmAliveTablePublishTimeout = DEFAULT_LIVENESS_I_AM_ALIVE_TABLE_PUBLISH_TIMEOUT; NumMissedProbesLimit = DEFAULT_LIVENESS_NUM_MISSED_PROBES_LIMIT; NumProbedSilos = DEFAULT_LIVENESS_NUM_PROBED_SILOS; NumVotesForDeathDeclaration = DEFAULT_LIVENESS_NUM_VOTES_FOR_DEATH_DECLARATION; NumMissedTableIAmAliveLimit = DEFAULT_LIVENESS_NUM_TABLE_I_AM_ALIVE_LIMIT; UseLivenessGossip = DEFAULT_LIVENESS_USE_LIVENESS_GOSSIP; ValidateInitialConnectivity = DEFAULT_VALIDATE_INITIAL_CONNECTIVITY; MaxJoinAttemptTime = DEFAULT_LIVENESS_MAX_JOIN_ATTEMPT_TIME; TypeMapRefreshInterval = DEFAULT_REFRESH_CLUSTER_INTERFACEMAP_TIME; MaxMultiClusterGateways = DEFAULT_MAX_MULTICLUSTER_GATEWAYS; BackgroundGossipInterval = DEFAULT_BACKGROUND_GOSSIP_INTERVAL; UseGlobalSingleInstanceByDefault = DEFAULT_USE_GLOBAL_SINGLE_INSTANCE; GlobalSingleInstanceRetryInterval = DEFAULT_GLOBAL_SINGLE_INSTANCE_RETRY_INTERVAL; GlobalSingleInstanceNumberRetries = DEFAULT_GLOBAL_SINGLE_INSTANCE_NUMBER_RETRIES; ExpectedClusterSizeConfigValue = new ConfigValue<int>(DEFAULT_LIVENESS_EXPECTED_CLUSTER_SIZE, true); ServiceId = Guid.Empty; DeploymentId = ""; DataConnectionString = ""; // Assume the ado invariant is for sql server storage if not explicitly specified AdoInvariant = Constants.INVARIANT_NAME_SQL_SERVER; MaxRequestProcessingTime = DEFAULT_COLLECTION_AGE_LIMIT; CollectionQuantum = DEFAULT_COLLECTION_QUANTUM; CacheSize = DEFAULT_CACHE_SIZE; InitialCacheTTL = DEFAULT_INITIAL_CACHE_TTL; MaximumCacheTTL = DEFAULT_MAXIMUM_CACHE_TTL; CacheTTLExtensionFactor = DEFAULT_TTL_EXTENSION_FACTOR; DirectoryCachingStrategy = DEFAULT_DIRECTORY_CACHING_STRATEGY; DirectoryLazyDeregistrationDelay = DEFAULT_UNREGISTER_RACE_DELAY; ClientRegistrationRefresh = DEFAULT_CLIENT_REGISTRATION_REFRESH; PerformDeadlockDetection = DEFAULT_PERFORM_DEADLOCK_DETECTION; reminderServiceType = ReminderServiceProviderType.NotSpecified; DefaultPlacementStrategy = DEFAULT_PLACEMENT_STRATEGY; DeploymentLoadPublisherRefreshTime = DEFAULT_DEPLOYMENT_LOAD_PUBLISHER_REFRESH_TIME; ActivationCountBasedPlacementChooseOutOf = DEFAULT_ACTIVATION_COUNT_BASED_PLACEMENT_CHOOSE_OUT_OF; UseVirtualBucketsConsistentRing = DEFAULT_USE_VIRTUAL_RING_BUCKETS; NumVirtualBucketsConsistentRing = DEFAULT_NUM_VIRTUAL_RING_BUCKETS; UseMockReminderTable = false; MockReminderTableTimeout = DEFAULT_MOCK_REMINDER_TABLE_TIMEOUT; AssumeHomogenousSilosForTesting = false; ProviderConfigurations = new Dictionary<string, ProviderCategoryConfiguration>(); GrainServiceConfigurations = new GrainServiceConfigurations(); DefaultCompatibilityStrategy = BackwardCompatible.Singleton; DefaultVersionSelectorStrategy = AllCompatibleVersions.Singleton; FastKillOnCancelKeyPress = true; } public override string ToString() { var sb = new StringBuilder(); sb.AppendFormat(" System Ids:").AppendLine(); sb.AppendFormat(" ServiceId: {0}", ServiceId).AppendLine(); sb.AppendFormat(" DeploymentId: {0}", DeploymentId).AppendLine(); sb.Append(" Subnet: ").Append(Subnet == null ? "" : Subnet.ToStrings(x => x.ToString(CultureInfo.InvariantCulture), ".")).AppendLine(); sb.Append(" Seed nodes: "); bool first = true; foreach (IPEndPoint node in SeedNodes) { if (!first) { sb.Append(", "); } sb.Append(node.ToString()); first = false; } sb.AppendLine(); sb.AppendFormat(base.ToString()); sb.AppendFormat(" Liveness:").AppendLine(); sb.AppendFormat(" LivenessEnabled: {0}", LivenessEnabled).AppendLine(); sb.AppendFormat(" LivenessType: {0}", LivenessType).AppendLine(); sb.AppendFormat(" ProbeTimeout: {0}", ProbeTimeout).AppendLine(); sb.AppendFormat(" TableRefreshTimeout: {0}", TableRefreshTimeout).AppendLine(); sb.AppendFormat(" DeathVoteExpirationTimeout: {0}", DeathVoteExpirationTimeout).AppendLine(); sb.AppendFormat(" NumMissedProbesLimit: {0}", NumMissedProbesLimit).AppendLine(); sb.AppendFormat(" NumProbedSilos: {0}", NumProbedSilos).AppendLine(); sb.AppendFormat(" NumVotesForDeathDeclaration: {0}", NumVotesForDeathDeclaration).AppendLine(); sb.AppendFormat(" UseLivenessGossip: {0}", UseLivenessGossip).AppendLine(); sb.AppendFormat(" ValidateInitialConnectivity: {0}", ValidateInitialConnectivity).AppendLine(); sb.AppendFormat(" IAmAliveTablePublishTimeout: {0}", IAmAliveTablePublishTimeout).AppendLine(); sb.AppendFormat(" NumMissedTableIAmAliveLimit: {0}", NumMissedTableIAmAliveLimit).AppendLine(); sb.AppendFormat(" MaxJoinAttemptTime: {0}", MaxJoinAttemptTime).AppendLine(); sb.AppendFormat(" ExpectedClusterSize: {0}", ExpectedClusterSize).AppendLine(); if (HasMultiClusterNetwork) { sb.AppendLine(" MultiClusterNetwork:"); sb.AppendFormat(" ClusterId: {0}", ClusterId ?? "").AppendLine(); sb.AppendFormat(" DefaultMultiCluster: {0}", DefaultMultiCluster != null ? string.Join(",", DefaultMultiCluster) : "null").AppendLine(); sb.AppendFormat(" MaxMultiClusterGateways: {0}", MaxMultiClusterGateways).AppendLine(); sb.AppendFormat(" BackgroundGossipInterval: {0}", BackgroundGossipInterval).AppendLine(); sb.AppendFormat(" UseGlobalSingleInstanceByDefault: {0}", UseGlobalSingleInstanceByDefault).AppendLine(); sb.AppendFormat(" GlobalSingleInstanceRetryInterval: {0}", GlobalSingleInstanceRetryInterval).AppendLine(); sb.AppendFormat(" GlobalSingleInstanceNumberRetries: {0}", GlobalSingleInstanceNumberRetries).AppendLine(); sb.AppendFormat(" GossipChannels: {0}", string.Join(",", GossipChannels.Select(conf => conf.ChannelType.ToString() + ":" + conf.ConnectionString))).AppendLine(); } else { sb.AppendLine(" MultiClusterNetwork: N/A"); } sb.AppendFormat(" SystemStore:").AppendLine(); // Don't print connection credentials in log files, so pass it through redactment filter string connectionStringForLog = ConfigUtilities.RedactConnectionStringInfo(DataConnectionString); sb.AppendFormat(" SystemStore ConnectionString: {0}", connectionStringForLog).AppendLine(); string remindersConnectionStringForLog = ConfigUtilities.RedactConnectionStringInfo(DataConnectionStringForReminders); sb.AppendFormat(" Reminders ConnectionString: {0}", remindersConnectionStringForLog).AppendLine(); sb.Append(Application.ToString()).AppendLine(); sb.Append(" PlacementStrategy: ").AppendLine(); sb.Append(" ").Append(" Default Placement Strategy: ").Append(DefaultPlacementStrategy).AppendLine(); sb.Append(" ").Append(" Deployment Load Publisher Refresh Time: ").Append(DeploymentLoadPublisherRefreshTime).AppendLine(); sb.Append(" ").Append(" Activation CountBased Placement Choose Out Of: ").Append(ActivationCountBasedPlacementChooseOutOf).AppendLine(); sb.AppendFormat(" Grain directory cache:").AppendLine(); sb.AppendFormat(" Maximum size: {0} grains", CacheSize).AppendLine(); sb.AppendFormat(" Initial TTL: {0}", InitialCacheTTL).AppendLine(); sb.AppendFormat(" Maximum TTL: {0}", MaximumCacheTTL).AppendLine(); sb.AppendFormat(" TTL extension factor: {0:F2}", CacheTTLExtensionFactor).AppendLine(); sb.AppendFormat(" Directory Caching Strategy: {0}", DirectoryCachingStrategy).AppendLine(); sb.AppendFormat(" Grain directory:").AppendLine(); sb.AppendFormat(" Lazy deregistration delay: {0}", DirectoryLazyDeregistrationDelay).AppendLine(); sb.AppendFormat(" Client registration refresh: {0}", ClientRegistrationRefresh).AppendLine(); sb.AppendFormat(" Reminder Service:").AppendLine(); sb.AppendFormat(" ReminderServiceType: {0}", ReminderServiceType).AppendLine(); if (ReminderServiceType == ReminderServiceProviderType.MockTable) { sb.AppendFormat(" MockReminderTableTimeout: {0}ms", MockReminderTableTimeout.TotalMilliseconds).AppendLine(); } sb.AppendFormat(" Consistent Ring:").AppendLine(); sb.AppendFormat(" Use Virtual Buckets Consistent Ring: {0}", UseVirtualBucketsConsistentRing).AppendLine(); sb.AppendFormat(" Num Virtual Buckets Consistent Ring: {0}", NumVirtualBucketsConsistentRing).AppendLine(); sb.AppendFormat(" Providers:").AppendLine(); sb.Append(ProviderConfigurationUtility.PrintProviderConfigurations(ProviderConfigurations)); return sb.ToString(); } internal override void Load(XmlElement root) { var logger = LogManager.GetLogger("OrleansConfiguration", LoggerType.Runtime); SeedNodes = new List<IPEndPoint>(); XmlElement child; foreach (XmlNode c in root.ChildNodes) { child = c as XmlElement; if (child != null && child.LocalName == "Networking") { Subnet = child.HasAttribute("Subnet") ? ConfigUtilities.ParseSubnet(child.GetAttribute("Subnet"), "Invalid Subnet") : null; } } foreach (XmlNode c in root.ChildNodes) { child = c as XmlElement; if (child == null) continue; // Skip comment lines switch (child.LocalName) { case "Liveness": if (child.HasAttribute("LivenessEnabled")) { LivenessEnabled = ConfigUtilities.ParseBool(child.GetAttribute("LivenessEnabled"), "Invalid boolean value for the LivenessEnabled attribute on the Liveness element"); } if (child.HasAttribute("ProbeTimeout")) { ProbeTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ProbeTimeout"), "Invalid time value for the ProbeTimeout attribute on the Liveness element"); } if (child.HasAttribute("TableRefreshTimeout")) { TableRefreshTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("TableRefreshTimeout"), "Invalid time value for the TableRefreshTimeout attribute on the Liveness element"); } if (child.HasAttribute("DeathVoteExpirationTimeout")) { DeathVoteExpirationTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DeathVoteExpirationTimeout"), "Invalid time value for the DeathVoteExpirationTimeout attribute on the Liveness element"); } if (child.HasAttribute("NumMissedProbesLimit")) { NumMissedProbesLimit = ConfigUtilities.ParseInt(child.GetAttribute("NumMissedProbesLimit"), "Invalid integer value for the NumMissedIAmAlive attribute on the Liveness element"); } if (child.HasAttribute("NumProbedSilos")) { NumProbedSilos = ConfigUtilities.ParseInt(child.GetAttribute("NumProbedSilos"), "Invalid integer value for the NumProbedSilos attribute on the Liveness element"); } if (child.HasAttribute("NumVotesForDeathDeclaration")) { NumVotesForDeathDeclaration = ConfigUtilities.ParseInt(child.GetAttribute("NumVotesForDeathDeclaration"), "Invalid integer value for the NumVotesForDeathDeclaration attribute on the Liveness element"); } if (child.HasAttribute("UseLivenessGossip")) { UseLivenessGossip = ConfigUtilities.ParseBool(child.GetAttribute("UseLivenessGossip"), "Invalid boolean value for the UseLivenessGossip attribute on the Liveness element"); } if (child.HasAttribute("ValidateInitialConnectivity")) { ValidateInitialConnectivity = ConfigUtilities.ParseBool(child.GetAttribute("ValidateInitialConnectivity"), "Invalid boolean value for the ValidateInitialConnectivity attribute on the Liveness element"); } if (child.HasAttribute("IAmAliveTablePublishTimeout")) { IAmAliveTablePublishTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("IAmAliveTablePublishTimeout"), "Invalid time value for the IAmAliveTablePublishTimeout attribute on the Liveness element"); } if (child.HasAttribute("NumMissedTableIAmAliveLimit")) { NumMissedTableIAmAliveLimit = ConfigUtilities.ParseInt(child.GetAttribute("NumMissedTableIAmAliveLimit"), "Invalid integer value for the NumMissedTableIAmAliveLimit attribute on the Liveness element"); } if (child.HasAttribute("MaxJoinAttemptTime")) { MaxJoinAttemptTime = ConfigUtilities.ParseTimeSpan(child.GetAttribute("MaxJoinAttemptTime"), "Invalid time value for the MaxJoinAttemptTime attribute on the Liveness element"); } if (child.HasAttribute("ExpectedClusterSize")) { int expectedClusterSize = ConfigUtilities.ParseInt(child.GetAttribute("ExpectedClusterSize"), "Invalid integer value for the ExpectedClusterSize attribute on the Liveness element"); ExpectedClusterSizeConfigValue = new ConfigValue<int>(expectedClusterSize, false); } break; case "Azure": case "SystemStore": if (child.LocalName == "Azure") { // Log warning about deprecated <Azure> element, but then continue on to parse it for connection string info logger.Warn(ErrorCode.SiloConfigDeprecated, "The Azure element has been deprecated -- use SystemStore element instead."); } if (child.HasAttribute("SystemStoreType")) { var sst = child.GetAttribute("SystemStoreType"); if (!"None".Equals(sst, StringComparison.OrdinalIgnoreCase)) { LivenessType = (LivenessProviderType)Enum.Parse(typeof(LivenessProviderType), sst); ReminderServiceProviderType reminderServiceProviderType; if (LivenessType == LivenessProviderType.MembershipTableGrain) { // Special case for MembershipTableGrain -> ReminderTableGrain since we use the same setting // for LivenessType and ReminderServiceType even if the enum are not 100% compatible reminderServiceProviderType = ReminderServiceProviderType.ReminderTableGrain; } else { // If LivenessType = ZooKeeper then we set ReminderServiceType to disabled reminderServiceProviderType = Enum.TryParse(sst, out reminderServiceProviderType) ? reminderServiceProviderType : ReminderServiceProviderType.Disabled; } SetReminderServiceType(reminderServiceProviderType); } } if (child.HasAttribute("MembershipTableAssembly")) { MembershipTableAssembly = child.GetAttribute("MembershipTableAssembly"); if (LivenessType != LivenessProviderType.Custom) throw new FormatException("SystemStoreType should be \"Custom\" when MembershipTableAssembly is specified"); if (MembershipTableAssembly.EndsWith(".dll")) throw new FormatException("Use fully qualified assembly name for \"MembershipTableAssembly\""); } if (child.HasAttribute("ReminderTableAssembly")) { ReminderTableAssembly = child.GetAttribute("ReminderTableAssembly"); if (ReminderServiceType != ReminderServiceProviderType.Custom) throw new FormatException("ReminderServiceType should be \"Custom\" when ReminderTableAssembly is specified"); if (ReminderTableAssembly.EndsWith(".dll")) throw new FormatException("Use fully qualified assembly name for \"ReminderTableAssembly\""); } if (LivenessType == LivenessProviderType.Custom && string.IsNullOrEmpty(MembershipTableAssembly)) throw new FormatException("MembershipTableAssembly should be set when SystemStoreType is \"Custom\""); if (ReminderServiceType == ReminderServiceProviderType.Custom && String.IsNullOrEmpty(ReminderTableAssembly)) { logger.Info("No ReminderTableAssembly specified with SystemStoreType set to Custom: ReminderService will be disabled"); SetReminderServiceType(ReminderServiceProviderType.Disabled); } if (child.HasAttribute("ServiceId")) { ServiceId = ConfigUtilities.ParseGuid(child.GetAttribute("ServiceId"), "Invalid Guid value for the ServiceId attribute on the Azure element"); } if (child.HasAttribute("DeploymentId")) { DeploymentId = child.GetAttribute("DeploymentId"); } if (child.HasAttribute(Constants.DATA_CONNECTION_STRING_NAME)) { DataConnectionString = child.GetAttribute(Constants.DATA_CONNECTION_STRING_NAME); if (String.IsNullOrWhiteSpace(DataConnectionString)) { throw new FormatException("SystemStore.DataConnectionString cannot be blank"); } } if (child.HasAttribute(Constants.DATA_CONNECTION_FOR_REMINDERS_STRING_NAME)) { DataConnectionStringForReminders = child.GetAttribute(Constants.DATA_CONNECTION_FOR_REMINDERS_STRING_NAME); if (String.IsNullOrWhiteSpace(DataConnectionStringForReminders)) { throw new FormatException("SystemStore.DataConnectionStringForReminders cannot be blank"); } } if (child.HasAttribute(Constants.ADO_INVARIANT_NAME)) { var adoInvariant = child.GetAttribute(Constants.ADO_INVARIANT_NAME); if (String.IsNullOrWhiteSpace(adoInvariant)) { throw new FormatException("SystemStore.AdoInvariant cannot be blank"); } AdoInvariant = adoInvariant; } if (child.HasAttribute(Constants.ADO_INVARIANT_FOR_REMINDERS_NAME)) { var adoInvariantForReminders = child.GetAttribute(Constants.ADO_INVARIANT_FOR_REMINDERS_NAME); if (String.IsNullOrWhiteSpace(adoInvariantForReminders)) { throw new FormatException("SystemStore.adoInvariantForReminders cannot be blank"); } AdoInvariantForReminders = adoInvariantForReminders; } if (child.HasAttribute("MaxStorageBusyRetries")) { MaxStorageBusyRetries = ConfigUtilities.ParseInt(child.GetAttribute("MaxStorageBusyRetries"), "Invalid integer value for the MaxStorageBusyRetries attribute on the SystemStore element"); } if (child.HasAttribute("UseMockReminderTable")) { MockReminderTableTimeout = ConfigUtilities.ParseTimeSpan(child.GetAttribute("UseMockReminderTable"), "Invalid timeout value"); UseMockReminderTable = true; } break; case "MultiClusterNetwork": ClusterId = child.GetAttribute("ClusterId"); // we always trim cluster ids to avoid surprises when parsing comma-separated lists if (ClusterId != null) ClusterId = ClusterId.Trim(); if (string.IsNullOrEmpty(ClusterId)) throw new FormatException("MultiClusterNetwork.ClusterId cannot be blank"); if (ClusterId.Contains(",")) throw new FormatException("MultiClusterNetwork.ClusterId cannot contain commas: " + ClusterId); if (child.HasAttribute("DefaultMultiCluster")) { var toparse = child.GetAttribute("DefaultMultiCluster").Trim(); if (string.IsNullOrEmpty(toparse)) { DefaultMultiCluster = new List<string>(); // empty cluster } else { DefaultMultiCluster = toparse.Split(',').Select(id => id.Trim()).ToList(); foreach (var id in DefaultMultiCluster) if (string.IsNullOrEmpty(id)) throw new FormatException("MultiClusterNetwork.DefaultMultiCluster cannot contain blank cluster ids: " + toparse); } } if (child.HasAttribute("BackgroundGossipInterval")) { BackgroundGossipInterval = ConfigUtilities.ParseTimeSpan(child.GetAttribute("BackgroundGossipInterval"), "Invalid time value for the BackgroundGossipInterval attribute on the MultiClusterNetwork element"); } if (child.HasAttribute("UseGlobalSingleInstanceByDefault")) { UseGlobalSingleInstanceByDefault = ConfigUtilities.ParseBool(child.GetAttribute("UseGlobalSingleInstanceByDefault"), "Invalid boolean for the UseGlobalSingleInstanceByDefault attribute on the MultiClusterNetwork element"); } if (child.HasAttribute("GlobalSingleInstanceRetryInterval")) { GlobalSingleInstanceRetryInterval = ConfigUtilities.ParseTimeSpan(child.GetAttribute("GlobalSingleInstanceRetryInterval"), "Invalid time value for the GlobalSingleInstanceRetryInterval attribute on the MultiClusterNetwork element"); } if (child.HasAttribute("GlobalSingleInstanceNumberRetries")) { GlobalSingleInstanceNumberRetries = ConfigUtilities.ParseInt(child.GetAttribute("GlobalSingleInstanceNumberRetries"), "Invalid value for the GlobalSingleInstanceRetryInterval attribute on the MultiClusterNetwork element"); } if (child.HasAttribute("MaxMultiClusterGateways")) { MaxMultiClusterGateways = ConfigUtilities.ParseInt(child.GetAttribute("MaxMultiClusterGateways"), "Invalid value for the MaxMultiClusterGateways attribute on the MultiClusterNetwork element"); } var channels = new List<GossipChannelConfiguration>(); foreach (XmlNode childchild in child.ChildNodes) { var channelspec = childchild as XmlElement; if (channelspec == null || channelspec.LocalName != "GossipChannel") continue; channels.Add(new GossipChannelConfiguration() { ChannelType = (GlobalConfiguration.GossipChannelType) Enum.Parse(typeof(GlobalConfiguration.GossipChannelType), channelspec.GetAttribute("Type")), ConnectionString = channelspec.GetAttribute("ConnectionString") }); } GossipChannels = channels; break; case "SeedNode": SeedNodes.Add(ConfigUtilities.ParseIPEndPoint(child, Subnet).GetResult()); break; case "Messaging": base.Load(child); break; case "Application": Application.Load(child, logger); break; case "PlacementStrategy": if (child.HasAttribute("DefaultPlacementStrategy")) DefaultPlacementStrategy = child.GetAttribute("DefaultPlacementStrategy"); if (child.HasAttribute("DeploymentLoadPublisherRefreshTime")) DeploymentLoadPublisherRefreshTime = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DeploymentLoadPublisherRefreshTime"), "Invalid time span value for PlacementStrategy.DeploymentLoadPublisherRefreshTime"); if (child.HasAttribute("ActivationCountBasedPlacementChooseOutOf")) ActivationCountBasedPlacementChooseOutOf = ConfigUtilities.ParseInt(child.GetAttribute("ActivationCountBasedPlacementChooseOutOf"), "Invalid ActivationCountBasedPlacementChooseOutOf setting"); break; case "Caching": if (child.HasAttribute("CacheSize")) CacheSize = ConfigUtilities.ParseInt(child.GetAttribute("CacheSize"), "Invalid integer value for Caching.CacheSize"); if (child.HasAttribute("InitialTTL")) InitialCacheTTL = ConfigUtilities.ParseTimeSpan(child.GetAttribute("InitialTTL"), "Invalid time value for Caching.InitialTTL"); if (child.HasAttribute("MaximumTTL")) MaximumCacheTTL = ConfigUtilities.ParseTimeSpan(child.GetAttribute("MaximumTTL"), "Invalid time value for Caching.MaximumTTL"); if (child.HasAttribute("TTLExtensionFactor")) CacheTTLExtensionFactor = ConfigUtilities.ParseDouble(child.GetAttribute("TTLExtensionFactor"), "Invalid double value for Caching.TTLExtensionFactor"); if (CacheTTLExtensionFactor <= 1.0) { throw new FormatException("Caching.TTLExtensionFactor must be greater than 1.0"); } if (child.HasAttribute("DirectoryCachingStrategy")) DirectoryCachingStrategy = ConfigUtilities.ParseEnum<DirectoryCachingStrategyType>(child.GetAttribute("DirectoryCachingStrategy"), "Invalid value for Caching.Strategy"); break; case "Directory": if (child.HasAttribute("DirectoryLazyDeregistrationDelay")) { DirectoryLazyDeregistrationDelay = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DirectoryLazyDeregistrationDelay"), "Invalid time span value for Directory.DirectoryLazyDeregistrationDelay"); } if (child.HasAttribute("ClientRegistrationRefresh")) { ClientRegistrationRefresh = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ClientRegistrationRefresh"), "Invalid time span value for Directory.ClientRegistrationRefresh"); } break; default: if (child.LocalName.Equals("GrainServices", StringComparison.Ordinal)) { GrainServiceConfigurations = GrainServiceConfigurations.Load(child); } if (child.LocalName.EndsWith("Providers", StringComparison.Ordinal)) { var providerCategory = ProviderCategoryConfiguration.Load(child); if (ProviderConfigurations.ContainsKey(providerCategory.Name)) { var existingCategory = ProviderConfigurations[providerCategory.Name]; existingCategory.Merge(providerCategory); } else { ProviderConfigurations.Add(providerCategory.Name, providerCategory); } } break; } } } /// <summary> /// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is bootstrap provider /// </summary> /// <typeparam name="T">Non-abstract type which implements <see cref="IBootstrapProvider"/> interface</typeparam> /// <param name="providerName">Name of the bootstrap provider</param> /// <param name="properties">Properties that will be passed to bootstrap provider upon initialization</param> public void RegisterBootstrapProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : IBootstrapProvider { Type providerType = typeof(T); var providerTypeInfo = providerType.GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || !typeof(IBootstrapProvider).IsAssignableFrom(providerType)) throw new ArgumentException("Expected non-generic, non-abstract type which implements IBootstrapProvider interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.BOOTSTRAP_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties); } /// <summary> /// Registers a given bootstrap provider. /// </summary> /// <param name="providerTypeFullName">Full name of the bootstrap provider type</param> /// <param name="providerName">Name of the bootstrap provider</param> /// <param name="properties">Properties that will be passed to the bootstrap provider upon initialization </param> public void RegisterBootstrapProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.BOOTSTRAP_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } /// <summary> /// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is stream provider /// </summary> /// <typeparam name="T">Non-abstract type which implements <see cref="IStreamProvider"/> stream</typeparam> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to stream provider upon initialization</param> public void RegisterStreamProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : Orleans.Streams.IStreamProvider { Type providerType = typeof(T); var providerTypeInfo = providerType.GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || !typeof(Orleans.Streams.IStreamProvider).IsAssignableFrom(providerType)) throw new ArgumentException("Expected non-generic, non-abstract type which implements IStreamProvider interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerType.FullName, providerName, properties); } /// <summary> /// Registers a given stream provider. /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="properties">Properties that will be passed to the stream provider upon initialization </param> public void RegisterStreamProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STREAM_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } /// <summary> /// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is storage provider /// </summary> /// <typeparam name="T">Non-abstract type which implements <see cref="IStorageProvider"/> storage</typeparam> /// <param name="providerName">Name of the storage provider</param> /// <param name="properties">Properties that will be passed to storage provider upon initialization</param> public void RegisterStorageProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : IStorageProvider { Type providerType = typeof(T); var providerTypeInfo = providerType.GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || !typeof(IStorageProvider).IsAssignableFrom(providerType)) throw new ArgumentException("Expected non-generic, non-abstract type which implements IStorageProvider interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STORAGE_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties); } /// <summary> /// Registers a given storage provider. /// </summary> /// <param name="providerTypeFullName">Full name of the storage provider type</param> /// <param name="providerName">Name of the storage provider</param> /// <param name="properties">Properties that will be passed to the storage provider upon initialization </param> public void RegisterStorageProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STORAGE_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } public void RegisterStatisticsProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : IStatisticsPublisher, ISiloMetricsDataPublisher { Type providerType = typeof(T); var providerTypeInfo = providerType.GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || !( typeof(IStatisticsPublisher).IsAssignableFrom(providerType) && typeof(ISiloMetricsDataPublisher).IsAssignableFrom(providerType) )) throw new ArgumentException("Expected non-generic, non-abstract type which implements IStatisticsPublisher, ISiloMetricsDataPublisher interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STATISTICS_PROVIDER_CATEGORY_NAME, providerTypeInfo.FullName, providerName, properties); } public void RegisterStatisticsProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.STATISTICS_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } /// <summary> /// Registers a given log-consistency provider. /// </summary> /// <param name="providerTypeFullName">Full name of the log-consistency provider type</param> /// <param name="providerName">Name of the log-consistency provider</param> /// <param name="properties">Properties that will be passed to the log-consistency provider upon initialization </param> public void RegisterLogConsistencyProvider(string providerTypeFullName, string providerName, IDictionary<string, string> properties = null) { ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.LOG_CONSISTENCY_PROVIDER_CATEGORY_NAME, providerTypeFullName, providerName, properties); } /// <summary> /// Registers a given type of <typeparamref name="T"/> where <typeparamref name="T"/> is a log-consistency provider /// </summary> /// <typeparam name="T">Non-abstract type which implements <see cref="ILogConsistencyProvider"/> a log-consistency storage interface</typeparam> /// <param name="providerName">Name of the log-consistency provider</param> /// <param name="properties">Properties that will be passed to log-consistency provider upon initialization</param> public void RegisterLogConsistencyProvider<T>(string providerName, IDictionary<string, string> properties = null) where T : ILogConsistencyProvider { Type providerType = typeof(T); var providerTypeInfo = providerType.GetTypeInfo(); if (providerTypeInfo.IsAbstract || providerTypeInfo.IsGenericType || !typeof(ILogConsistencyProvider).IsAssignableFrom(providerType)) throw new ArgumentException("Expected non-generic, non-abstract type which implements ILogConsistencyProvider interface", "typeof(T)"); ProviderConfigurationUtility.RegisterProvider(ProviderConfigurations, ProviderCategoryConfiguration.LOG_CONSISTENCY_PROVIDER_CATEGORY_NAME, providerType.FullName, providerName, properties); } /// <summary> /// Retrieves an existing provider configuration /// </summary> /// <param name="providerTypeFullName">Full name of the stream provider type</param> /// <param name="providerName">Name of the stream provider</param> /// <param name="config">The provider configuration, if exists</param> /// <returns>True if a configuration for this provider already exists, false otherwise.</returns> public bool TryGetProviderConfiguration(string providerTypeFullName, string providerName, out IProviderConfiguration config) { return ProviderConfigurationUtility.TryGetProviderConfiguration(ProviderConfigurations, providerTypeFullName, providerName, out config); } /// <summary> /// Retrieves an enumeration of all currently configured provider configurations. /// </summary> /// <returns>An enumeration of all currently configured provider configurations.</returns> public IEnumerable<IProviderConfiguration> GetAllProviderConfigurations() { return ProviderConfigurationUtility.GetAllProviderConfigurations(ProviderConfigurations); } public void RegisterGrainService(string serviceName, string serviceType, IDictionary<string, string> properties = null) { GrainServiceConfigurationsUtility.RegisterGrainService(GrainServiceConfigurations, serviceName, serviceType, properties); } } }
/* * 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.Xml; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Text; using System.Threading; using log4net; namespace OpenSim.Framework.Console { public delegate void CommandDelegate(string module, string[] cmd); public class Commands { /// <summary> /// Encapsulates a command that can be invoked from the console /// </summary> private class CommandInfo { /// <value> /// The module from which this command comes /// </value> public string module; /// <value> /// Whether the module is shared /// </value> public bool shared; /// <value> /// Very short BNF description /// </value> public string help_text; /// <value> /// Longer one line help text /// </value> public string long_help; /// <value> /// Full descriptive help for this command /// </value> public string descriptive_help; /// <value> /// The method to invoke for this command /// </value> public List<CommandDelegate> fn; } /// <value> /// Commands organized by keyword in a tree /// </value> private Dictionary<string, object> tree = new Dictionary<string, object>(); /// <summary> /// Get help for the given help string /// </summary> /// <param name="helpParts">Parsed parts of the help string. If empty then general help is returned.</param> /// <returns></returns> public List<string> GetHelp(string[] cmd) { List<string> help = new List<string>(); List<string> helpParts = new List<string>(cmd); // Remove initial help keyword helpParts.RemoveAt(0); // General help if (helpParts.Count == 0) { help.AddRange(CollectHelp(tree)); help.Sort(); } else { help.AddRange(CollectHelp(helpParts)); } return help; } /// <summary> /// See if we can find the requested command in order to display longer help /// </summary> /// <param name="helpParts"></param> /// <returns></returns> private List<string> CollectHelp(List<string> helpParts) { string originalHelpRequest = string.Join(" ", helpParts.ToArray()); List<string> help = new List<string>(); Dictionary<string, object> dict = tree; while (helpParts.Count > 0) { string helpPart = helpParts[0]; if (!dict.ContainsKey(helpPart)) break; //m_log.Debug("Found {0}", helpParts[0]); if (dict[helpPart] is Dictionary<string, Object>) dict = (Dictionary<string, object>)dict[helpPart]; helpParts.RemoveAt(0); } // There was a command for the given help string if (dict.ContainsKey(String.Empty)) { CommandInfo commandInfo = (CommandInfo)dict[String.Empty]; help.Add(commandInfo.help_text); help.Add(commandInfo.long_help); help.Add(commandInfo.descriptive_help); } else { help.Add(string.Format("No help is available for {0}", originalHelpRequest)); } return help; } private List<string> CollectHelp(Dictionary<string, object> dict) { List<string> result = new List<string>(); foreach (KeyValuePair<string, object> kvp in dict) { if (kvp.Value is Dictionary<string, Object>) { result.AddRange(CollectHelp((Dictionary<string, Object>)kvp.Value)); } else { if (((CommandInfo)kvp.Value).long_help != String.Empty) result.Add(((CommandInfo)kvp.Value).help_text+" - "+ ((CommandInfo)kvp.Value).long_help); } } return result; } /// <summary> /// Add a command to those which can be invoked from the console. /// </summary> /// <param name="module"></param> /// <param name="command"></param> /// <param name="help"></param> /// <param name="longhelp"></param> /// <param name="fn"></param> public void AddCommand(string module, bool shared, string command, string help, string longhelp, CommandDelegate fn) { AddCommand(module, shared, command, help, longhelp, String.Empty, fn); } /// <summary> /// Add a command to those which can be invoked from the console. /// </summary> /// <param name="module"></param> /// <param name="command"></param> /// <param name="help"></param> /// <param name="longhelp"></param> /// <param name="descriptivehelp"></param> /// <param name="fn"></param> public void AddCommand(string module, bool shared, string command, string help, string longhelp, string descriptivehelp, CommandDelegate fn) { string[] parts = Parser.Parse(command); Dictionary<string, Object> current = tree; foreach (string s in parts) { if (current.ContainsKey(s)) { if (current[s] is Dictionary<string, Object>) { current = (Dictionary<string, Object>)current[s]; } else return; } else { current[s] = new Dictionary<string, Object>(); current = (Dictionary<string, Object>)current[s]; } } CommandInfo info; if (current.ContainsKey(String.Empty)) { info = (CommandInfo)current[String.Empty]; if (!info.shared && !info.fn.Contains(fn)) info.fn.Add(fn); return; } info = new CommandInfo(); info.module = module; info.shared = shared; info.help_text = help; info.long_help = longhelp; info.descriptive_help = descriptivehelp; info.fn = new List<CommandDelegate>(); info.fn.Add(fn); current[String.Empty] = info; } public string[] FindNextOption(string[] cmd, bool term) { Dictionary<string, object> current = tree; int remaining = cmd.Length; foreach (string s in cmd) { remaining--; List<string> found = new List<string>(); foreach (string opt in current.Keys) { if (remaining > 0 && opt == s) { found.Clear(); found.Add(opt); break; } if (opt.StartsWith(s)) { found.Add(opt); } } if (found.Count == 1 && (remaining != 0 || term)) { current = (Dictionary<string, object>)current[found[0]]; } else if (found.Count > 0) { return found.ToArray(); } else { break; // return new string[] {"<cr>"}; } } if (current.Count > 1) { List<string> choices = new List<string>(); bool addcr = false; foreach (string s in current.Keys) { if (s == String.Empty) { CommandInfo ci = (CommandInfo)current[String.Empty]; if (ci.fn.Count != 0) addcr = true; } else choices.Add(s); } if (addcr) choices.Add("<cr>"); return choices.ToArray(); } if (current.ContainsKey(String.Empty)) return new string[] { "Command help: "+((CommandInfo)current[String.Empty]).help_text}; return new string[] { new List<string>(current.Keys)[0] }; } public string[] Resolve(string[] cmd) { string[] result = cmd; int index = -1; Dictionary<string, object> current = tree; foreach (string s in cmd) { index++; List<string> found = new List<string>(); foreach (string opt in current.Keys) { if (opt == s) { found.Clear(); found.Add(opt); break; } if (opt.StartsWith(s)) { found.Add(opt); } } if (found.Count == 1) { result[index] = found[0]; current = (Dictionary<string, object>)current[found[0]]; } else if (found.Count > 0) { return new string[0]; } else { break; } } if (current.ContainsKey(String.Empty)) { CommandInfo ci = (CommandInfo)current[String.Empty]; if (ci.fn.Count == 0) return new string[0]; foreach (CommandDelegate fn in ci.fn) { if (fn != null) fn(ci.module, result); else return new string[0]; } return result; } return new string[0]; } public XmlElement GetXml(XmlDocument doc) { CommandInfo help = (CommandInfo)((Dictionary<string, object>)tree["help"])[String.Empty]; ((Dictionary<string, object>)tree["help"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["help"]).Count == 0) tree.Remove("help"); CommandInfo quit = (CommandInfo)((Dictionary<string, object>)tree["quit"])[String.Empty]; ((Dictionary<string, object>)tree["quit"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["quit"]).Count == 0) tree.Remove("quit"); XmlElement root = doc.CreateElement("", "HelpTree", ""); ProcessTreeLevel(tree, root, doc); if (!tree.ContainsKey("help")) tree["help"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["help"])[String.Empty] = help; if (!tree.ContainsKey("quit")) tree["quit"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["quit"])[String.Empty] = quit; return root; } private void ProcessTreeLevel(Dictionary<string, object> level, XmlElement xml, XmlDocument doc) { foreach (KeyValuePair<string, object> kvp in level) { if (kvp.Value is Dictionary<string, Object>) { XmlElement next = doc.CreateElement("", "Level", ""); next.SetAttribute("Name", kvp.Key); xml.AppendChild(next); ProcessTreeLevel((Dictionary<string, object>)kvp.Value, next, doc); } else { CommandInfo c = (CommandInfo)kvp.Value; XmlElement cmd = doc.CreateElement("", "Command", ""); XmlElement e; e = doc.CreateElement("", "Module", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.module)); e = doc.CreateElement("", "Shared", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.shared.ToString())); e = doc.CreateElement("", "HelpText", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.help_text)); e = doc.CreateElement("", "LongHelp", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.long_help)); e = doc.CreateElement("", "Description", ""); cmd.AppendChild(e); e.AppendChild(doc.CreateTextNode(c.descriptive_help)); xml.AppendChild(cmd); } } } public void FromXml(XmlElement root, CommandDelegate fn) { CommandInfo help = (CommandInfo)((Dictionary<string, object>)tree["help"])[String.Empty]; ((Dictionary<string, object>)tree["help"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["help"]).Count == 0) tree.Remove("help"); CommandInfo quit = (CommandInfo)((Dictionary<string, object>)tree["quit"])[String.Empty]; ((Dictionary<string, object>)tree["quit"]).Remove(string.Empty); if (((Dictionary<string, object>)tree["quit"]).Count == 0) tree.Remove("quit"); tree.Clear(); ReadTreeLevel(tree, root, fn); if (!tree.ContainsKey("help")) tree["help"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["help"])[String.Empty] = help; if (!tree.ContainsKey("quit")) tree["quit"] = (object) new Dictionary<string, object>(); ((Dictionary<string, object>)tree["quit"])[String.Empty] = quit; } private void ReadTreeLevel(Dictionary<string, object> level, XmlNode node, CommandDelegate fn) { Dictionary<string, object> next; string name; XmlNodeList nodeL = node.ChildNodes; XmlNodeList cmdL; CommandInfo c; foreach (XmlNode part in nodeL) { switch (part.Name) { case "Level": name = ((XmlElement)part).GetAttribute("Name"); next = new Dictionary<string, object>(); level[name] = next; ReadTreeLevel(next, part, fn); break; case "Command": cmdL = part.ChildNodes; c = new CommandInfo(); foreach (XmlNode cmdPart in cmdL) { switch (cmdPart.Name) { case "Module": c.module = cmdPart.InnerText; break; case "Shared": c.shared = Convert.ToBoolean(cmdPart.InnerText); break; case "HelpText": c.help_text = cmdPart.InnerText; break; case "LongHelp": c.long_help = cmdPart.InnerText; break; case "Description": c.descriptive_help = cmdPart.InnerText; break; } } c.fn = new List<CommandDelegate>(); c.fn.Add(fn); level[String.Empty] = c; break; } } } } public class Parser { public static string[] Parse(string text) { List<string> result = new List<string>(); int index; string[] unquoted = text.Split(new char[] {'"'}); for (index = 0 ; index < unquoted.Length ; index++) { if (index % 2 == 0) { string[] words = unquoted[index].Split(new char[] {' '}); foreach (string w in words) { if (w != String.Empty) result.Add(w); } } else { result.Add(unquoted[index]); } } return result.ToArray(); } } // A console that processes commands internally // public class CommandConsole : ConsoleBase { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public Commands Commands = new Commands(); public CommandConsole(string defaultPrompt) : base(defaultPrompt) { Commands.AddCommand("console", false, "help", "help [<command>]", "Get general command list or more detailed help on a specific command", Help); } private void Help(string module, string[] cmd) { List<string> help = Commands.GetHelp(cmd); foreach (string s in help) Output(s); } public void Prompt() { string line = ReadLine(m_defaultPrompt + "# ", true, true); if (line != String.Empty) { m_log.Info("[CONSOLE] Invalid command"); } } public void RunCommand(string cmd) { string[] parts = Parser.Parse(cmd); Commands.Resolve(parts); } public override string ReadLine(string p, bool isCommand, bool e) { System.Console.Write("{0}", p); string cmdinput = System.Console.ReadLine(); if (isCommand) { string[] cmd = Commands.Resolve(Parser.Parse(cmdinput)); if (cmd.Length != 0) { int i; for (i=0 ; i < cmd.Length ; i++) { if (cmd[i].Contains(" ")) cmd[i] = "\"" + cmd[i] + "\""; } return String.Empty; } } return cmdinput; } } }
namespace Epi.Windows.MakeView.Dialogs.FieldDefinitionDialogs { partial class LegalValuesFieldDefinition { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(LegalValuesFieldDefinition)); this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Column2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.lblDataSource = new System.Windows.Forms.Label(); this.txtDataSource = new System.Windows.Forms.TextBox(); this.btnDataSource = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // chkEncrypted // resources.ApplyResources(this.chkEncrypted, "chkEncrypted"); // // txtFieldName // this.txtFieldName.TextChanged += new System.EventHandler(this.txtFieldName_TextChanged); this.txtFieldName.Leave += new System.EventHandler(this.txtFieldName_Leave); // // btnCancel // resources.ApplyResources(this.btnCancel, "btnCancel"); // // btnOk // resources.ApplyResources(this.btnOk, "btnOk"); // // groupBox1 // this.groupBox1.Controls.Add(this.lblDataSource); this.groupBox1.Controls.Add(this.txtDataSource); this.groupBox1.Controls.Add(this.btnDataSource); resources.ApplyResources(this.groupBox1, "groupBox1"); this.groupBox1.Controls.SetChildIndex(this.chkEncrypted, 0); this.groupBox1.Controls.SetChildIndex(this.btnDataSource, 0); this.groupBox1.Controls.SetChildIndex(this.txtDataSource, 0); this.groupBox1.Controls.SetChildIndex(this.lblDataSource, 0); this.groupBox1.Controls.SetChildIndex(this.chkReadOnly, 0); this.groupBox1.Controls.SetChildIndex(this.chkRequired, 0); this.groupBox1.Controls.SetChildIndex(this.chkRepeatLast, 0); this.groupBox1.Controls.SetChildIndex(this.btnFieldFont, 0); this.groupBox1.Controls.SetChildIndex(this.btnPromptFont, 0); // // baseImageList // this.baseImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("baseImageList.ImageStream"))); this.baseImageList.Images.SetKeyName(0, ""); this.baseImageList.Images.SetKeyName(1, ""); this.baseImageList.Images.SetKeyName(2, ""); this.baseImageList.Images.SetKeyName(3, ""); this.baseImageList.Images.SetKeyName(4, ""); this.baseImageList.Images.SetKeyName(5, ""); this.baseImageList.Images.SetKeyName(6, ""); this.baseImageList.Images.SetKeyName(7, ""); this.baseImageList.Images.SetKeyName(8, ""); this.baseImageList.Images.SetKeyName(9, ""); this.baseImageList.Images.SetKeyName(10, ""); this.baseImageList.Images.SetKeyName(11, ""); this.baseImageList.Images.SetKeyName(12, ""); this.baseImageList.Images.SetKeyName(13, ""); this.baseImageList.Images.SetKeyName(14, ""); this.baseImageList.Images.SetKeyName(15, ""); this.baseImageList.Images.SetKeyName(16, ""); this.baseImageList.Images.SetKeyName(17, ""); this.baseImageList.Images.SetKeyName(18, ""); this.baseImageList.Images.SetKeyName(19, ""); this.baseImageList.Images.SetKeyName(20, ""); this.baseImageList.Images.SetKeyName(21, ""); this.baseImageList.Images.SetKeyName(22, ""); this.baseImageList.Images.SetKeyName(23, ""); this.baseImageList.Images.SetKeyName(24, ""); this.baseImageList.Images.SetKeyName(25, ""); this.baseImageList.Images.SetKeyName(26, ""); this.baseImageList.Images.SetKeyName(27, ""); this.baseImageList.Images.SetKeyName(28, ""); this.baseImageList.Images.SetKeyName(29, ""); this.baseImageList.Images.SetKeyName(30, ""); this.baseImageList.Images.SetKeyName(31, ""); this.baseImageList.Images.SetKeyName(32, ""); this.baseImageList.Images.SetKeyName(33, ""); this.baseImageList.Images.SetKeyName(34, ""); this.baseImageList.Images.SetKeyName(35, ""); this.baseImageList.Images.SetKeyName(36, ""); this.baseImageList.Images.SetKeyName(37, ""); this.baseImageList.Images.SetKeyName(38, ""); this.baseImageList.Images.SetKeyName(39, ""); this.baseImageList.Images.SetKeyName(40, ""); this.baseImageList.Images.SetKeyName(41, ""); this.baseImageList.Images.SetKeyName(42, ""); this.baseImageList.Images.SetKeyName(43, ""); this.baseImageList.Images.SetKeyName(44, ""); this.baseImageList.Images.SetKeyName(45, ""); this.baseImageList.Images.SetKeyName(46, ""); this.baseImageList.Images.SetKeyName(47, ""); this.baseImageList.Images.SetKeyName(48, ""); this.baseImageList.Images.SetKeyName(49, ""); this.baseImageList.Images.SetKeyName(50, ""); this.baseImageList.Images.SetKeyName(51, ""); this.baseImageList.Images.SetKeyName(52, ""); this.baseImageList.Images.SetKeyName(53, ""); this.baseImageList.Images.SetKeyName(54, ""); this.baseImageList.Images.SetKeyName(55, ""); this.baseImageList.Images.SetKeyName(56, ""); this.baseImageList.Images.SetKeyName(57, ""); this.baseImageList.Images.SetKeyName(58, ""); this.baseImageList.Images.SetKeyName(59, ""); this.baseImageList.Images.SetKeyName(60, ""); this.baseImageList.Images.SetKeyName(61, ""); this.baseImageList.Images.SetKeyName(62, ""); this.baseImageList.Images.SetKeyName(63, ""); this.baseImageList.Images.SetKeyName(64, ""); this.baseImageList.Images.SetKeyName(65, ""); this.baseImageList.Images.SetKeyName(66, ""); this.baseImageList.Images.SetKeyName(67, ""); this.baseImageList.Images.SetKeyName(68, ""); this.baseImageList.Images.SetKeyName(69, ""); this.baseImageList.Images.SetKeyName(70, ""); this.baseImageList.Images.SetKeyName(71, ""); this.baseImageList.Images.SetKeyName(72, ""); this.baseImageList.Images.SetKeyName(73, ""); this.baseImageList.Images.SetKeyName(74, ""); this.baseImageList.Images.SetKeyName(75, ""); this.baseImageList.Images.SetKeyName(76, ""); this.baseImageList.Images.SetKeyName(77, ""); this.baseImageList.Images.SetKeyName(78, ""); this.baseImageList.Images.SetKeyName(79, ""); this.baseImageList.Images.SetKeyName(80, ""); this.baseImageList.Images.SetKeyName(81, ""); this.baseImageList.Images.SetKeyName(82, ""); this.baseImageList.Images.SetKeyName(83, ""); this.baseImageList.Images.SetKeyName(84, ""); this.baseImageList.Images.SetKeyName(85, ""); this.baseImageList.Images.SetKeyName(86, ""); // // Column1 // resources.ApplyResources(this.Column1, "Column1"); this.Column1.Name = "Column1"; // // Column2 // resources.ApplyResources(this.Column2, "Column2"); this.Column2.Name = "Column2"; // // lblDataSource // resources.ApplyResources(this.lblDataSource, "lblDataSource"); this.lblDataSource.Name = "lblDataSource"; // // txtDataSource // resources.ApplyResources(this.txtDataSource, "txtDataSource"); this.txtDataSource.Name = "txtDataSource"; this.txtDataSource.ReadOnly = true; // // btnDataSource // resources.ApplyResources(this.btnDataSource, "btnDataSource"); this.btnDataSource.Name = "btnDataSource"; this.btnDataSource.UseVisualStyleBackColor = true; this.btnDataSource.Click += new System.EventHandler(this.btnDataSource_Click); // // LegalValuesFieldDefinition // resources.ApplyResources(this, "$this"); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "LegalValuesFieldDefinition"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.DataGridViewTextBoxColumn Column1; private System.Windows.Forms.DataGridViewTextBoxColumn Column2; /// <summary> /// The data source label /// </summary> protected System.Windows.Forms.Label lblDataSource; /// <summary> /// The data source text box /// </summary> protected System.Windows.Forms.TextBox txtDataSource; /// <summary> /// The data source button /// </summary> protected System.Windows.Forms.Button btnDataSource; } }
using System; using System.Collections.Generic; using Microsoft.Data.Entity.Migrations; using Microsoft.Data.Entity.Metadata; namespace PartsUnlimited.Models.Migrations { public partial class InitialMigration : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: true), NormalizedName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_IdentityRole", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Email = table.Column<string>(nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), LockoutEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), Name = table.Column<string>(nullable: true), NormalizedEmail = table.Column<string>(nullable: true), NormalizedUserName = table.Column<string>(nullable: true), PasswordHash = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), SecurityStamp = table.Column<string>(nullable: true), TwoFactorEnabled = table.Column<bool>(nullable: false), UserName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_ApplicationUser", x => x.Id); }); migrationBuilder.CreateTable( name: "Category", columns: table => new { CategoryId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Description = table.Column<string>(nullable: true), ImageUrl = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Category", x => x.CategoryId); }); migrationBuilder.CreateTable( name: "Order", columns: table => new { OrderId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Address = table.Column<string>(nullable: false), City = table.Column<string>(nullable: false), Country = table.Column<string>(nullable: false), Email = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), OrderDate = table.Column<DateTime>(nullable: false), Phone = table.Column<string>(nullable: false), PostalCode = table.Column<string>(nullable: false), Processed = table.Column<bool>(nullable: false), State = table.Column<string>(nullable: false), Total = table.Column<decimal>(nullable: false), Username = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Order", x => x.OrderId); }); migrationBuilder.CreateTable( name: "Store", columns: table => new { StoreId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Store", x => x.StoreId); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityRoleClaim<string>", x => x.Id); table.ForeignKey( name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityUserClaim<string>", x => x.Id); table.ForeignKey( name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityUserLogin<string>", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_IdentityUserRole<string>", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Product", columns: table => new { ProductId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), CategoryId = table.Column<int>(nullable: false), Created = table.Column<DateTime>(nullable: false), Description = table.Column<string>(nullable: false), Inventory = table.Column<int>(nullable: false), LeadTime = table.Column<int>(nullable: false), Price = table.Column<decimal>(nullable: false), ProductArtUrl = table.Column<string>(nullable: false), ProductDetails = table.Column<string>(nullable: false), RecommendationId = table.Column<int>(nullable: false), SalePrice = table.Column<decimal>(nullable: false), SkuNumber = table.Column<string>(nullable: false), Title = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Product", x => x.ProductId); table.ForeignKey( name: "FK_Product_Category_CategoryId", column: x => x.CategoryId, principalTable: "Category", principalColumn: "CategoryId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "CartItem", columns: table => new { CartItemId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), CartId = table.Column<string>(nullable: false), Count = table.Column<int>(nullable: false), DateCreated = table.Column<DateTime>(nullable: false), ProductId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_CartItem", x => x.CartItemId); table.ForeignKey( name: "FK_CartItem_Product_ProductId", column: x => x.ProductId, principalTable: "Product", principalColumn: "ProductId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "OrderDetail", columns: table => new { OrderDetailId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), OrderId = table.Column<int>(nullable: false), ProductId = table.Column<int>(nullable: false), Quantity = table.Column<int>(nullable: false), UnitPrice = table.Column<decimal>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_OrderDetail", x => x.OrderDetailId); table.ForeignKey( name: "FK_OrderDetail_Order_OrderId", column: x => x.OrderId, principalTable: "Order", principalColumn: "OrderId", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_OrderDetail_Product_ProductId", column: x => x.ProductId, principalTable: "Product", principalColumn: "ProductId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "Raincheck", columns: table => new { RaincheckId = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Name = table.Column<string>(nullable: true), ProductId = table.Column<int>(nullable: false), Quantity = table.Column<int>(nullable: false), SalePrice = table.Column<double>(nullable: false), StoreId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Raincheck", x => x.RaincheckId); table.ForeignKey( name: "FK_Raincheck_Product_ProductId", column: x => x.ProductId, principalTable: "Product", principalColumn: "ProductId", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_Raincheck_Store_StoreId", column: x => x.StoreId, principalTable: "Store", principalColumn: "StoreId", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable("AspNetRoleClaims"); migrationBuilder.DropTable("AspNetUserClaims"); migrationBuilder.DropTable("AspNetUserLogins"); migrationBuilder.DropTable("AspNetUserRoles"); migrationBuilder.DropTable("CartItem"); migrationBuilder.DropTable("OrderDetail"); migrationBuilder.DropTable("Raincheck"); migrationBuilder.DropTable("AspNetRoles"); migrationBuilder.DropTable("AspNetUsers"); migrationBuilder.DropTable("Order"); migrationBuilder.DropTable("Product"); migrationBuilder.DropTable("Store"); migrationBuilder.DropTable("Category"); } } }
using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using Microsoft.Win32.SafeHandles; namespace More.Net.Windows.Interop.Win32 { /// <summary> /// Provides access to NTFS junction points in .Net. /// </summary> public static class JunctionPoint { #region Public Methods /// <summary> /// Creates a junction point from the specified directory to the specified target directory. /// </summary> /// <remarks> /// Only works on NTFS. /// </remarks> /// <param name="junctionPoint">The junction point path</param> /// <param name="targetDir">The target directory</param> /// <param name="overwrite">If true overwrites an existing reparse point or empty directory</param> /// <exception cref="IOException"> /// Thrown when the junction point could not be created or when an existing directory was /// found and <paramref name="overwrite" /> if false /// </exception> public static void Create(String junctionPoint, String targetDir, Boolean overwrite) { targetDir = Path.GetFullPath(targetDir); if (!Directory.Exists(targetDir)) throw new IOException("Target path does not exist or is not a directory."); if (Directory.Exists(junctionPoint)) { if (!overwrite) throw new IOException("Directory already exists and overwrite parameter is false."); } else { Directory.CreateDirectory(junctionPoint); } using (SafeFileHandle handle = OpenReparsePoint(junctionPoint, GenericAccess.Write)) { Byte[] targetDirBytes = Encoding.Unicode.GetBytes(NonInterpretedPathPrefix + Path.GetFullPath(targetDir)); REPARSE_DATA_BUFFER reparseDataBuffer = new REPARSE_DATA_BUFFER(); reparseDataBuffer.ReparseTag = IO_REPARSE_TAG_MOUNT_POINT; reparseDataBuffer.ReparseDataLength = (UInt16)(targetDirBytes.Length + 12); reparseDataBuffer.SubstituteNameOffset = 0; reparseDataBuffer.SubstituteNameLength = (UInt16)targetDirBytes.Length; reparseDataBuffer.PrintNameOffset = (UInt16)(targetDirBytes.Length + 2); reparseDataBuffer.PrintNameLength = 0; reparseDataBuffer.PathBuffer = new Byte[0x3ff0]; Array.Copy(targetDirBytes, reparseDataBuffer.PathBuffer, targetDirBytes.Length); int inBufferSize = Marshal.SizeOf(reparseDataBuffer); IntPtr inBuffer = Marshal.AllocHGlobal(inBufferSize); try { Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false); int bytesReturned; bool result = Kernel32.DeviceIoControl(handle.DangerousGetHandle(), FSCTL_SET_REPARSE_POINT, inBuffer, targetDirBytes.Length + 20, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); if (!result) ThrowLastWin32Error("Unable to create junction point."); } finally { Marshal.FreeHGlobal(inBuffer); } } } /// <summary> /// Deletes a junction point at the specified source directory along with the directory itself. /// Does nothing if the junction point does not exist. /// </summary> /// <remarks> /// Only works on NTFS. /// </remarks> /// <param name="junctionPoint">The junction point path</param> public static void Delete(String junctionPoint) { if (!Directory.Exists(junctionPoint)) { if (File.Exists(junctionPoint)) throw new IOException("Path is not a junction point."); return; } using (SafeFileHandle handle = OpenReparsePoint(junctionPoint, GenericAccess.Write)) { REPARSE_DATA_BUFFER reparseDataBuffer = new REPARSE_DATA_BUFFER(); reparseDataBuffer.ReparseTag = IO_REPARSE_TAG_MOUNT_POINT; reparseDataBuffer.ReparseDataLength = 0; reparseDataBuffer.PathBuffer = new Byte[0x3ff0]; Int32 inBufferSize = Marshal.SizeOf(reparseDataBuffer); IntPtr inBuffer = Marshal.AllocHGlobal(inBufferSize); try { Marshal.StructureToPtr(reparseDataBuffer, inBuffer, false); Int32 bytesReturned; Boolean result = Kernel32.DeviceIoControl(handle.DangerousGetHandle(), FSCTL_DELETE_REPARSE_POINT, inBuffer, 8, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); if (!result) ThrowLastWin32Error("Unable to delete junction point."); } finally { Marshal.FreeHGlobal(inBuffer); } try { Directory.Delete(junctionPoint); } catch (IOException ex) { throw new IOException("Unable to delete junction point.", ex); } } } /// <summary> /// Determines whether the specified path exists and refers to a junction point. /// </summary> /// <param name="path">The junction point path</param> /// <returns>True if the specified path represents a junction point</returns> /// <exception cref="IOException">Thrown if the specified path is invalid /// or some other error occurs</exception> public static bool Exists(String path) { if (!Directory.Exists(path)) return false; using (SafeFileHandle handle = OpenReparsePoint(path, GenericAccess.Read)) { string target = InternalGetTarget(handle); return target != null; } } /// <summary> /// Gets the target of the specified junction point. /// </summary> /// <remarks> /// Only works on NTFS. /// </remarks> /// <param name="junctionPoint">The junction point path</param> /// <returns>The target of the junction point</returns> /// <exception cref="IOException">Thrown when the specified path does not /// exist, is invalid, is not a junction point, or some other error occurs</exception> public static String GetTarget(String junctionPoint) { using (SafeFileHandle handle = OpenReparsePoint(junctionPoint, GenericAccess.Read)) { String target = InternalGetTarget(handle); if (target == null) throw new IOException("Path is not a junction point."); return target; } } #endregion #region Private Methods private static String InternalGetTarget(SafeFileHandle handle) { Int32 outBufferSize = Marshal.SizeOf(typeof(REPARSE_DATA_BUFFER)); IntPtr outBuffer = Marshal.AllocHGlobal(outBufferSize); try { Int32 bytesReturned; Boolean result = Kernel32.DeviceIoControl(handle.DangerousGetHandle(), FSCTL_GET_REPARSE_POINT, IntPtr.Zero, 0, outBuffer, outBufferSize, out bytesReturned, IntPtr.Zero); if (!result) { Int32 error = Marshal.GetLastWin32Error(); if (error == ERROR_NOT_A_REPARSE_POINT) return null; ThrowLastWin32Error("Unable to get information about junction point."); } REPARSE_DATA_BUFFER reparseDataBuffer = (REPARSE_DATA_BUFFER) Marshal.PtrToStructure(outBuffer, typeof(REPARSE_DATA_BUFFER)); if (reparseDataBuffer.ReparseTag != IO_REPARSE_TAG_MOUNT_POINT) return null; string targetDir = Encoding.Unicode.GetString(reparseDataBuffer.PathBuffer, reparseDataBuffer.SubstituteNameOffset, reparseDataBuffer.SubstituteNameLength); if (targetDir.StartsWith(NonInterpretedPathPrefix)) targetDir = targetDir.Substring(NonInterpretedPathPrefix.Length); return targetDir; } finally { Marshal.FreeHGlobal(outBuffer); } } private static SafeFileHandle OpenReparsePoint(String reparsePoint, GenericAccess accessMode) { IntPtr file = Kernel32.CreateFile( reparsePoint, accessMode, FileShare.Read | FileShare.Write | FileShare.Delete, IntPtr.Zero, CreationDisposition.OpenExisting, FileAttributes.BackupSemantics | FileAttributes.OpenReparsePoint, IntPtr.Zero); if (Marshal.GetLastWin32Error() != 0) ThrowLastWin32Error("Unable to open reparse point."); return new SafeFileHandle(file, true); } private static void ThrowLastWin32Error(String message) { throw new IOException(message, Marshal.GetExceptionForHR( Marshal.GetHRForLastWin32Error())); } #endregion #region Reparse Data Buffer Structure /// <summary> /// /// </summary> [StructLayout(LayoutKind.Sequential)] private struct REPARSE_DATA_BUFFER { /// <summary> /// Reparse point tag. Must be a Microsoft reparse point tag. /// </summary> public UInt32 ReparseTag; /// <summary> /// Size, in bytes, of the data after the Reserved member. This can be calculated by: /// (4 * sizeof(ushort)) + SubstituteNameLength + PrintNameLength + /// (namesAreNullTerminated ? 2 * sizeof(char) : 0); /// </summary> public UInt16 ReparseDataLength; /// <summary> /// Reserved; do not use. /// </summary> public UInt16 Reserved; /// <summary> /// Offset, in bytes, of the substitute name string in the PathBuffer array. /// </summary> public UInt16 SubstituteNameOffset; /// <summary> /// Length, in bytes, of the substitute name string. If this string is null-terminated, /// SubstituteNameLength does not include space for the null character. /// </summary> public UInt16 SubstituteNameLength; /// <summary> /// Offset, in bytes, of the print name string in the PathBuffer array. /// </summary> public UInt16 PrintNameOffset; /// <summary> /// Length, in bytes, of the print name string. If this string is null-terminated, /// PrintNameLength does not include space for the null character. /// </summary> public UInt16 PrintNameLength; /// <summary> /// A buffer containing the unicode-encoded path string. The path string contains /// the substitute name string and print name string. /// </summary> [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x3FF0)] public Byte[] PathBuffer; } #endregion #region Constants /// <summary> /// The file or directory is not a reparse point. /// </summary> private const Int32 ERROR_NOT_A_REPARSE_POINT = 4390; /// <summary> /// The reparse point attribute cannot be set because it conflicts with an existing attribute. /// </summary> private const Int32 ERROR_REPARSE_ATTRIBUTE_CONFLICT = 4391; /// <summary> /// The data present in the reparse point buffer is invalid. /// </summary> private const Int32 ERROR_INVALID_REPARSE_DATA = 4392; /// <summary> /// The tag present in the reparse point buffer is invalid. /// </summary> private const Int32 ERROR_REPARSE_TAG_INVALID = 4393; /// <summary> /// There is a mismatch between the tag specified in the request and the tag present in the reparse point. /// </summary> private const Int32 ERROR_REPARSE_TAG_MISMATCH = 4394; /// <summary> /// Command to set the reparse point data block. /// </summary> private const Int32 FSCTL_SET_REPARSE_POINT = 0x000900A4; /// <summary> /// Command to get the reparse point data block. /// </summary> private const Int32 FSCTL_GET_REPARSE_POINT = 0x000900A8; /// <summary> /// Command to delete the reparse point data base. /// </summary> private const Int32 FSCTL_DELETE_REPARSE_POINT = 0x000900AC; /// <summary> /// Reparse point tag used to identify mount points and junction points. /// </summary> private const UInt32 IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003; /// <summary> /// This prefix indicates to NTFS that the path is to be treated as a non-interpreted /// path in the virtual file system. /// </summary> private const String NonInterpretedPathPrefix = @"\??\"; #endregion } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Orleans.Runtime.Scheduler; using Orleans.Runtime.Configuration; namespace Orleans.Runtime { /// <summary> /// This class collects runtime statistics for all silos in the current deployment for use by placement. /// </summary> internal class DeploymentLoadPublisher : SystemTarget, IDeploymentLoadPublisher, ISiloStatusListener { private readonly Silo silo; private readonly ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics> periodicStats; private readonly TimeSpan statisticsRefreshTime; private readonly IList<ISiloStatisticsChangeListener> siloStatisticsChangeListeners; private readonly TraceLogger logger = TraceLogger.GetLogger("DeploymentLoadPublisher", TraceLogger.LoggerType.Runtime); public static DeploymentLoadPublisher Instance { get; private set; } public ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics> PeriodicStatistics { get { return periodicStats; } } public static void CreateDeploymentLoadPublisher(Silo silo, GlobalConfiguration config) { Instance = new DeploymentLoadPublisher(silo, config.DeploymentLoadPublisherRefreshTime); } private DeploymentLoadPublisher(Silo silo, TimeSpan freshnessTime) : base(Constants.DeploymentLoadPublisherSystemTargetId, silo.SiloAddress) { this.silo = silo; statisticsRefreshTime = freshnessTime; periodicStats = new ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics>(); siloStatisticsChangeListeners = new List<ISiloStatisticsChangeListener>(); } public async Task Start() { logger.Info("Starting DeploymentLoadPublisher."); if (statisticsRefreshTime > TimeSpan.Zero) { var random = new SafeRandom(); // Randomize PublishStatistics timer, // but also upon start publish my stats to everyone and take everyone's stats for me to start with something. var randomTimerOffset = random.NextTimeSpan(statisticsRefreshTime); var t = GrainTimer.FromTaskCallback(PublishStatistics, null, randomTimerOffset, statisticsRefreshTime); t.Start(); } await RefreshStatistics(); await PublishStatistics(null); logger.Info("Started DeploymentLoadPublisher."); } private async Task PublishStatistics(object _) { try { if(logger.IsVerbose) logger.Verbose("PublishStatistics."); List<SiloAddress> members = silo.LocalSiloStatusOracle.GetApproximateSiloStatuses(true).Keys.ToList(); var tasks = new List<Task>(); var myStats = new SiloRuntimeStatistics(silo.Metrics, DateTime.UtcNow); foreach (var siloAddress in members) { try { tasks.Add(InsideRuntimeClient.Current.InternalGrainFactory.GetSystemTarget<IDeploymentLoadPublisher>( Constants.DeploymentLoadPublisherSystemTargetId, siloAddress) .UpdateRuntimeStatistics(silo.SiloAddress, myStats)); } catch (Exception) { logger.Warn(ErrorCode.Placement_RuntimeStatisticsUpdateFailure_1, String.Format("An unexpected exception was thrown by PublishStatistics.UpdateRuntimeStatistics(). Ignored.")); } } await Task.WhenAll(tasks); } catch (Exception exc) { logger.Warn(ErrorCode.Placement_RuntimeStatisticsUpdateFailure_2, String.Format("An exception was thrown by PublishStatistics.UpdateRuntimeStatistics(). Ignoring."), exc); } } public Task UpdateRuntimeStatistics(SiloAddress siloAddress, SiloRuntimeStatistics siloStats) { if (logger.IsVerbose) logger.Verbose("UpdateRuntimeStatistics from {0}", siloAddress); if (!silo.LocalSiloStatusOracle.GetApproximateSiloStatus(siloAddress).Equals(SiloStatus.Active)) return TaskDone.Done; SiloRuntimeStatistics old; // Take only if newer. if (periodicStats.TryGetValue(siloAddress, out old) && old.DateTime > siloStats.DateTime) return TaskDone.Done; periodicStats[siloAddress] = siloStats; NotifyAllStatisticsChangeEventsSubscribers(siloAddress, siloStats); return TaskDone.Done; } internal async Task<ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics>> RefreshStatistics() { if (logger.IsVerbose) logger.Verbose("RefreshStatistics."); await silo.LocalScheduler.RunOrQueueTask( () => { var tasks = new List<Task>(); List<SiloAddress> members = silo.LocalSiloStatusOracle.GetApproximateSiloStatuses(true).Keys.ToList(); foreach (var siloAddress in members) { var capture = siloAddress; Task task = InsideRuntimeClient.Current.InternalGrainFactory.GetSystemTarget<ISiloControl>(Constants.SiloControlId, capture) .GetRuntimeStatistics() .ContinueWith((Task<SiloRuntimeStatistics> statsTask) => { if (statsTask.Status == TaskStatus.RanToCompletion) { UpdateRuntimeStatistics(capture, statsTask.Result); } else { logger.Warn(ErrorCode.Placement_RuntimeStatisticsUpdateFailure_3, String.Format("An unexpected exception was thrown from RefreshStatistics by ISiloControl.GetRuntimeStatistics({0}). Will keep using stale statistics.", capture), statsTask.Exception); } }); tasks.Add(task); task.Ignore(); } return Task.WhenAll(tasks); }, SchedulingContext); return periodicStats; } public bool SubscribeToStatisticsChangeEvents(ISiloStatisticsChangeListener observer) { lock (siloStatisticsChangeListeners) { if (siloStatisticsChangeListeners.Contains(observer)) return false; siloStatisticsChangeListeners.Add(observer); return true; } } public bool UnsubscribeStatisticsChangeEvents(ISiloStatisticsChangeListener observer) { lock (siloStatisticsChangeListeners) { return siloStatisticsChangeListeners.Contains(observer) && siloStatisticsChangeListeners.Remove(observer); } } private void NotifyAllStatisticsChangeEventsSubscribers(SiloAddress silo, SiloRuntimeStatistics stats) { lock (siloStatisticsChangeListeners) { foreach (var subscriber in siloStatisticsChangeListeners) { if (stats==null) { subscriber.RemoveSilo(silo); } else { subscriber.SiloStatisticsChangeNotification(silo, stats); } } } } public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status) { if (!status.IsTerminating()) return; SiloRuntimeStatistics ignore; periodicStats.TryRemove(updatedSilo, out ignore); NotifyAllStatisticsChangeEventsSubscribers(updatedSilo, null); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // #define REGISTERALLOCATOR_SPILL_ONLY_ONE_VARIABLE #define REGISTERALLOCATOR_REPORT_SLOW_METHODS namespace Microsoft.Zelig.CodeGeneration.IR.Transformations { using System; using System.Collections.Generic; using Microsoft.Zelig.Runtime.TypeSystem; // // This class converts PseudoRegisters into PhysicalRegisters or moves the variables to stack locations. // public class GlobalRegisterAllocation { internal enum WebFlavor { Must , Should, May , } internal class WebPair { // // State // internal InterferenceNode m_node1; internal InterferenceNode m_node2; internal WebFlavor m_flavor; // // Constructor Methods // internal WebPair( InterferenceNode node1 , InterferenceNode node2 , WebFlavor flavor ) { m_node1 = node1; m_node2 = node2; m_flavor = flavor; } // // Helper methods // internal void MaximizeFlavor( WebFlavor flavor ) { if(m_flavor > flavor) { m_flavor = flavor; } } internal bool IsMatch( InterferenceNode node ) { return m_node1 == node || m_node2 == node; } internal int SpillCost() { return m_node1.m_spillCost + m_node2.m_spillCost; } internal void Remove() { m_node1.m_coalesceWeb.Remove( this ); m_node2.m_coalesceWeb.Remove( this ); } // // Debug Methods // public override string ToString() { return string.Format( "{0} <-> {1} as {2}", m_node1.m_source, m_node2.m_source, m_flavor ); } } internal class InterferenceNode { // // State // internal int m_index; internal VariableExpression m_source; internal Operator m_definition; // We are in SSA form, at most there's one definition. internal Operator[] m_uses; internal BitVector m_compatibleRegs; internal List< WebPair > m_coalesceWeb; internal PhysicalRegisterExpression m_fixed; internal PhysicalRegisterExpression m_assigned; internal int m_candidateColor; internal BitVector m_edges; internal BitVector m_liveness; internal int m_livenessLow; internal int m_livenessHigh; internal int m_degree; internal InterferenceNode m_previousStackElement; internal int m_spillCost; internal bool m_spillCandidate; internal bool m_spillWouldCreateNewWebs; // // Constructor Methods // internal InterferenceNode() // Used as an End-Of-Stack sentinel. { } internal InterferenceNode( int index , VariableExpression source , Operator definition , Operator[] uses , BitVector[] livenessMap ) { m_index = index; m_source = source; m_definition = definition; m_uses = uses; m_compatibleRegs = new BitVector(); m_coalesceWeb = new List< WebPair >(); m_liveness = livenessMap[source.SpanningTreeIndex].Clone(); // // This takes care of registers used in calling convention. // m_fixed = source.AliasedVariable as PhysicalRegisterExpression; m_assigned = m_fixed; } // // Helper methods // internal Abstractions.RegisterClass ComputeConstraintsForLHS() { return RegisterAllocationConstraintAnnotation.ComputeConstraintsForLHS( m_definition, m_source ); } internal Abstractions.RegisterClass ComputeConstraintsForRHS() { Abstractions.RegisterClass constraint = Abstractions.RegisterClass.None; foreach(Operator use in m_uses) { constraint |= RegisterAllocationConstraintAnnotation.ComputeConstraintsForRHS( use, m_source ); } return constraint; } internal void SubstituteDefinition( GlobalRegisterAllocation owner ) { owner.SubstituteDefinition( m_definition, m_source, false ); } internal void SubstituteUsage( GlobalRegisterAllocation owner ) { foreach(Operator use in m_uses) { owner.SubstituteUsage( use, m_source, false ); } } //--// internal WebPair FindPair( InterferenceNode node ) { foreach(var pair in m_coalesceWeb) { if(pair.IsMatch( this ) && pair.IsMatch( node )) { return pair; } } return null; } //--// internal void ResetCandidate() { if(m_assigned != null) { m_candidateColor = m_assigned.RegisterDescriptor.Index; } else { m_candidateColor = -1; } } internal void UpdateAdjacencies( InterferenceNode[] interferenceGraph ) { foreach(int idxEdge in m_edges) { InterferenceNode nodeEdge = interferenceGraph[idxEdge]; nodeEdge.m_degree--; } } internal void Push( InterferenceNode[] interferenceGraph , ref InterferenceNode lastStackElement , bool spillCandidate ) { m_spillCandidate = spillCandidate; m_previousStackElement = lastStackElement; lastStackElement = this; UpdateAdjacencies( interferenceGraph ); } internal bool HasLowerRelativeCost( InterferenceNode otherNode ) { int relCostThis = this .m_spillCost * otherNode.m_edges.Cardinality; int relCostOther = otherNode.m_spillCost * this .m_edges.Cardinality; return relCostThis < relCostOther; } internal bool LivenessOverlapsWith( InterferenceNode otherNode ) { if(this .m_livenessHigh < otherNode.m_livenessLow || otherNode.m_livenessHigh < this .m_livenessLow ) { // // Disjoint live ranges for sure. // return false; } return this.m_liveness.IsIntersectionEmpty( otherNode.m_liveness ) == false; } // // Debug Methods // public override string ToString() { System.Text.StringBuilder sb = new System.Text.StringBuilder(); sb.AppendFormat( "N.{0} {1}", m_index, m_source ); if(m_edges != null) { sb.AppendFormat( " => Edges {0}", m_edges ); } if(m_coalesceWeb.Count > 0) { sb.Append( " => Web [" ); foreach(var pair in m_coalesceWeb) { sb.AppendFormat( " {0} ", pair ); } sb.Append( "]" ); } if(m_fixed != null) { sb.AppendFormat( " => Fixed as {0}", m_fixed ); } if(m_assigned != null) { sb.AppendFormat( " => Assigned to {0}", m_assigned ); } if(m_candidateColor >= 0) { sb.AppendFormat( " => Candidate for {0}", m_candidateColor ); } return sb.ToString(); } } // // State // private readonly ControlFlowGraphStateForCodeTransformation m_cfg; private readonly Abstractions.RegisterDescriptor[] m_registers; private readonly InterferenceNode m_stackSentinel; private GrowOnlySet< VariableExpression > m_spillHistory; private Operator[][] m_defChains; private Operator[][] m_useChains; private int m_interferenceGraphSize; private InterferenceNode[] m_interferenceGraph; private InterferenceNode[] m_interferenceGraphLookup; private DataFlow.ControlTree.NaturalLoops m_naturalLoops; // // Constructor Methods // public GlobalRegisterAllocation( ControlFlowGraphStateForCodeTransformation cfg ) { m_cfg = cfg; //--// // // Get list of possible register candidates. // m_registers = cfg.TypeSystem.PlatformAbstraction.GetRegisters(); //--// m_stackSentinel = new InterferenceNode(); } // // Helper Methods // public static void Execute( ControlFlowGraphStateForCodeTransformation cfg ) { using(new PerformanceCounters.ContextualTiming( cfg, "GlobalRegisterAllocation" )) { GlobalRegisterAllocation gra = new GlobalRegisterAllocation( cfg ); gra.PerformAllocation(); } } private void PerformAllocation() { #if REGISTERALLOCATOR_REPORT_SLOW_METHODS System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); int iterations = 0; #endif //--// while(true) { #if REGISTERALLOCATOR_REPORT_SLOW_METHODS iterations++; #endif DisposeSpillCosts(); //--// m_cfg.TraceToFile( "RegisterAllocation-Loop" ); CHECKS.ASSERT( Transformations.StaticSingleAssignmentForm.ShouldTransformInto( m_cfg ) == false, "Control Flow Graph no longer in SSA form" ); // // 1) Ensure all the operators with register constraints have pseudo registers as parameters, not stack locations. // Operator[] operators = m_cfg.DataFlow_SpanningTree_Operators; bool fGot = false; int opLen = operators.Length; //foreach(Operator op in operators) for(int idxOp = 0; idxOp < opLen; idxOp++) { Operator op = operators[idxOp]; int opResLen = op.Results.Length; for(int idx = 0; idx < opResLen; idx++) { if(RegisterAllocationConstraintAnnotation.ShouldLhsBeMovedToPseudoRegister( op, idx )) { SubstituteDefinition( op, op.Results[idx], false ); fGot = true; } } opResLen = op.Arguments.Length; for(int idx = 0; idx < opResLen; idx++) { if(RegisterAllocationConstraintAnnotation.ShouldRhsBeMovedToPseudoRegister( op, idx )) { SubstituteUsage( op, (VariableExpression)op.Arguments[idx], false ); fGot = true; } } // // If an operator has some coupling constraints, we create temporary variables for the expressions involved in the constraint. // This relies some of the pressure from the graph coloring algorithm, since these constraints add 'MUST' web edges. // foreach(var an in op.FilterAnnotations< RegisterCouplingConstraintAnnotation >()) { if(an.IsResult1) { var ex = op.Results[an.VarIndex1]; if(!(ex is PseudoRegisterExpression)) { SubstituteDefinition( op, ex, true ); fGot = true; } } else { var ex = (VariableExpression)op.Arguments[an.VarIndex1]; if(!(ex is PseudoRegisterExpression)) { SubstituteUsage( op, ex, true ); fGot = true; } } if(an.IsResult2) { var ex = op.Results[an.VarIndex2]; if(!(ex is PseudoRegisterExpression)) { SubstituteDefinition( op, ex, true ); fGot = true; } } else { var ex = (VariableExpression)op.Arguments[an.VarIndex2]; if(!(ex is PseudoRegisterExpression)) { SubstituteUsage( op, ex, true ); fGot = true; } } } } if(fGot) { continue; } // // 1b) Create Use chains and liveness analysis. // VariableExpression[] variables = m_cfg.DataFlow_SpanningTree_Variables; BitVector[] livenessMap = m_cfg.DataFlow_VariableLivenessMap; // It's indexed as Operator[<variable index>][<operator index>] // // 2) Build interference graph. Any variables that have overlapping liveness are set to interfere. // using(new PerformanceCounters.ContextualTiming( m_cfg, "BuildInterferenceGraph" )) { m_interferenceGraphSize = 0; m_interferenceGraph = new InterferenceNode[variables.Length]; m_interferenceGraphLookup = new InterferenceNode[variables.Length]; m_defChains = m_cfg.DataFlow_DefinitionChains; m_useChains = m_cfg.DataFlow_UseChains; bool fRestart = false; int varLen = variables.Length; //foreach(VariableExpression var in variables) for(int idxVar = 0; idxVar < varLen; idxVar++) { VariableExpression var = variables[idxVar]; Operator[] defChain = m_defChains[var.SpanningTreeIndex]; CHECKS.ASSERT( defChain.Length <= 1, "Not in SSA form!" ); VariableExpression varAliased = var.AliasedVariable; bool fInclude = false; if(varAliased is PhysicalRegisterExpression) { fInclude = true; } else if(varAliased is PseudoRegisterExpression) { // // Some variables are not actually defined, because: // 1) they are just aliases for low-level expressions, // 2) they are passed as inputs. // if(defChain.Length == 1 || ((PseudoRegisterExpression)varAliased).SourceVariable.Type.FullName.Equals( "Microsoft.Zelig.Runtime.TypeSystem.CodePointer" )) { fInclude = true; } else { CHECKS.ASSERT( m_useChains[var.SpanningTreeIndex].Length == 0, "Cannot have a use of an undefined non-argument variable." ); } } if(fInclude) { InterferenceNode node = new InterferenceNode( m_interferenceGraphSize, var, defChain.Length == 1 ? defChain[0] : null, m_useChains[var.SpanningTreeIndex], livenessMap ); //--// Abstractions.RegisterClass constraintLHS = node.ComputeConstraintsForLHS(); Abstractions.RegisterClass constraintRHS = node.ComputeConstraintsForRHS(); Abstractions.RegisterClass constraint = constraintLHS | constraintRHS; bool fGotLHS = false; int regLen = m_registers.Length; //foreach(Abstractions.RegisterDescriptor regDesc in m_registers) for(int idxReg = 0; idxReg < regLen; idxReg++) { Abstractions.RegisterDescriptor regDesc = m_registers[idxReg]; if(regDesc.CanAllocate && regDesc.PhysicalStorageSize == node.m_source.Type.SizeOfHoldingVariableInWords) { if((regDesc.ComputeCapabilities & constraintLHS) == constraintLHS) { fGotLHS = true; } if((regDesc.ComputeCapabilities & constraint) == constraint) { node.m_compatibleRegs.Set( regDesc.Index ); } } } // // If no compatible registers, we need to reassign. // if(node.m_compatibleRegs.Cardinality == 0) { fRestart = true; } // // If the variable is already assigned to a physical register, // it has to be either a compatible register or a register that cannot be allocated (special usage registers). // if(node.m_fixed != null) { int idx = node.m_fixed.Number; if(m_registers[idx].CanAllocate) { if(node.m_compatibleRegs[idx] == false) { fRestart = true; } } } if(fRestart) { if(fGotLHS == false) { node.SubstituteDefinition( this ); } else { node.SubstituteUsage( this ); } break; } m_interferenceGraph[m_interferenceGraphSize++] = node; m_interferenceGraphLookup[var.SpanningTreeIndex] = node; } } if(fRestart) { continue; } //--// if(m_interferenceGraphSize != 0) { for(int idx = 0; idx < m_interferenceGraphSize; idx++) { InterferenceNode node = m_interferenceGraph[idx]; node.m_edges = new BitVector( m_interferenceGraphSize ); } //--// // // The data from the liveness analysis doesn't work directly for building the interference graph, // because if a register is invalidated as part of the calling convention but not used in the method, // it won't be marked as alive by the liveness analysis (correctly, since it's not used), // although it should be added to the interference set so that we don't assign scratch registers across method calls. // // Same thing for all the variables that are defined but not used, because their definition leads to a side-effect. // BitVector done = new BitVector(); BitVector tmp = new BitVector( opLen ); for(int idx = 0; idx < opLen; idx++) { Operator op = operators[idx]; foreach(var an in op.FilterAnnotations< PreInvalidationAnnotation >()) { var reg = an.Target.AliasedVariable as PhysicalRegisterExpression; if(reg != null && done[reg.Number] == false) { done[reg.Number] = true; tmp.ClearAll(); for(int idx2 = idx; idx2 < opLen; idx2++) { foreach(var an2 in operators[idx2].FilterAnnotations< InvalidationAnnotation >()) { var reg2 = an2.Target.AliasedVariable as PhysicalRegisterExpression; if(reg2 != null) { if(reg2.Number == reg.Number) { tmp.Set( idx2 ); } } } } for(int idx2 = 0; idx2 < m_interferenceGraphSize; idx2++) { InterferenceNode node = m_interferenceGraph[idx2]; if(node.m_fixed == reg) { node.m_liveness.OrInPlace( tmp ); } } } } int resLen = op.Results.Length; //foreach(var lhs in op.Results) for(int lIdx = 0; lIdx < resLen; lIdx++) { var lhs = op.Results[lIdx]; int lhsIdx = lhs.SpanningTreeIndex; if(m_useChains[lhsIdx].Length == 0) { InterferenceNode node = m_interferenceGraphLookup[lhsIdx]; if(node != null) { node.m_liveness.Set( idx ); } } } foreach(var an in op.FilterAnnotations< PostInvalidationAnnotation >()) { var reg = an.Target.AliasedVariable as PhysicalRegisterExpression; if(reg != null && done[reg.Number] == false) { done[reg.Number] = true; tmp.ClearAll(); for(int idx2 = idx; idx2 < opLen; idx2++) { foreach(var an2 in operators[idx2].FilterAnnotations< InvalidationAnnotation >()) { var reg2 = an2.Target.AliasedVariable as PhysicalRegisterExpression; if(reg2 != null) { if(reg2.Number == reg.Number) { tmp.Set( idx2 ); } } } } for(int idx2 = 0; idx2 < m_interferenceGraphSize; idx2++) { InterferenceNode node = m_interferenceGraph[idx2]; if(node.m_fixed == reg) { node.m_liveness.OrInPlace( tmp ); } } } } } for(int idx = 0; idx < m_interferenceGraphSize; idx++) { InterferenceNode node = m_interferenceGraph[idx]; node.m_liveness.GetRange( out node.m_livenessLow, out node.m_livenessHigh ); } } } if(m_interferenceGraphSize == 0) { // // Nothing to do, probably because there's nothing to compute in this method... // break; } //--// // // 3) Create adjacency information for all the pseudo registers and physical registers. // using(new PerformanceCounters.ContextualTiming( m_cfg, "ComputeAdjacencyMatrix" )) { for(int idx = 0; idx < m_interferenceGraphSize; idx++) { InterferenceNode node = m_interferenceGraph[idx]; for(int idx2 = idx + 1; idx2 < m_interferenceGraphSize; idx2++) { InterferenceNode node2 = m_interferenceGraph[idx2]; if(node.LivenessOverlapsWith( node2 )) { // // The two nodes interfere, so create an edge between them. // node .m_edges.Set( node2.m_index ); node2.m_edges.Set( node .m_index ); } } node.m_degree = node.m_edges.Cardinality; } } // // 4) Is the graph N-colorable? If not, select a candidate for spilling, update the interference graph and repeat. // // Look for any node interfering with less than N other nodes. // Remove it from the graph, put it on a stack, update the edges of the other nodes. // Repeat until no more such nodes are left in the graph. // If at the end the graph has no nodes, it's colorable. // InterferenceNode lastStackElement = m_stackSentinel; for(int nodesToPush = m_interferenceGraphSize; nodesToPush > 0; ) { bool fSpilled = false; for(int idx = 0; idx < m_interferenceGraphSize; idx++) { InterferenceNode node = m_interferenceGraph[idx]; if(node.m_previousStackElement == null) { if(node.m_degree < node.m_compatibleRegs.Cardinality) { node.Push( m_interferenceGraph, ref lastStackElement, false ); fSpilled = true; nodesToPush--; } } } if(fSpilled == false) { // // Coulnd't find any node with degree < N. // Select a node with the lowest spill cost, push it as a candidate and continue. // InterferenceNode nodeToSpill = SelectNodeToSpillOptimistically(); nodeToSpill.Push( m_interferenceGraph, ref lastStackElement, true ); nodesToPush--; } } if(ColorGraph( lastStackElement )) { // // 5) Assign pseudo registers to physical registers. // // // We have a coloring. Substitute registers for candidate variables. // foreach(Operator op in m_cfg.DataFlow_SpanningTree_Operators) { ConvertToPhysicalRegisters( op ); } break; } else { // // Failed to color, spill all interfering nodes, selecting the least expensive ones. // SpillVariables(); } } DisposeSpillCosts(); m_cfg.TraceToFile( "RegisterAllocation-Done" ); while(Transformations.CommonMethodRedundancyElimination.Execute( m_cfg )) { } Transformations.StaticSingleAssignmentForm.ConvertOut( m_cfg, false ); m_cfg.TraceToFile( "RegisterAllocation-Post" ); // // Remove temporary copy propagation blocks. // int stoLen = m_cfg.DataFlow_SpanningTree_Operators.Length; //foreach(Operator op in m_cfg.DataFlow_SpanningTree_Operators) for(int idxSto = 0; idxSto < stoLen; idxSto++) { Operator op = m_cfg.DataFlow_SpanningTree_Operators[idxSto]; foreach(var an in op.FilterAnnotations< BlockCopyPropagationAnnotation >()) { if(an.IsTemporary) { op.RemoveAnnotation( an ); } } } #if REGISTERALLOCATOR_REPORT_SLOW_METHODS sw.Stop(); int totalSeconds = (int)(sw.ElapsedMilliseconds / 1000); if(totalSeconds >= 2) { Console.WriteLine( "NOTICE: Register allocation for method '{0}' took {1} seconds and {2} iterations! [{3} variables and {4} operators]", m_cfg.Method.ToShortString(), totalSeconds, iterations, m_cfg.DataFlow_SpanningTree_Variables.Length, m_cfg.DataFlow_SpanningTree_Operators.Length ); Console.WriteLine( "NOTICE: Interference graph for method '{0}' has {1} nodes!" , m_cfg.Method.ToShortString(), m_interferenceGraphSize ); Console.WriteLine(); } #endif } //--// private int EstimateCostOfOperator( Operator op ) { if(op == null) { return 0; } int depth = m_naturalLoops.GetDepthOfBasicBlock( op.BasicBlock ); return (int)Math.Pow( 8, depth ); } private void DisposeSpillCosts() { if(m_naturalLoops != null) { m_naturalLoops.Dispose(); m_naturalLoops = null; } } private void ComputeSpillCosts() { if(m_naturalLoops == null) { m_naturalLoops = DataFlow.ControlTree.NaturalLoops.Execute( m_cfg ); //--// Abstractions.Platform pa = m_cfg.TypeSystem.PlatformAbstraction; int cost_definition = pa.EstimatedCostOfStoreOperation; int cost_use = pa.EstimatedCostOfLoadOperation; using(new PerformanceCounters.ContextualTiming( m_cfg, "ComputeSpillCosts" )) { for(int idx = 0; idx < m_interferenceGraphSize; idx++) { InterferenceNode node = m_interferenceGraph[idx]; int cost = 0; foreach(Operator def in m_defChains[node.m_source.SpanningTreeIndex]) { cost += cost_definition * EstimateCostOfOperator( def ); } foreach(Operator use in m_useChains[node.m_source.SpanningTreeIndex]) { cost += cost_use * EstimateCostOfOperator( use ); } node.m_spillCost = cost; //--// // // It makes sense to consider the node as a spill candidate // only if removing it would improve the chances of coloring the graph. // BitVector postLiveness = new BitVector(); if(node.m_definition != null) { postLiveness.Set( node.m_definition.SpanningTreeIndex ); } foreach(Operator use in node.m_uses) { postLiveness.Set( use.SpanningTreeIndex ); } node.m_spillWouldCreateNewWebs = false; if(node.m_fixed == null) { foreach(int idxEdge in node.m_edges) { InterferenceNode otherNode = m_interferenceGraph[idxEdge]; if(postLiveness.IsIntersectionEmpty( otherNode.m_liveness )) { node.m_spillWouldCreateNewWebs = true; break; } } } } } } } private InterferenceNode SelectNodeToSpillOptimistically() { ComputeSpillCosts(); InterferenceNode lastNode = null; InterferenceNode firstPhysical = null; for(int idx = 0; idx < m_interferenceGraphSize; idx++) { InterferenceNode node = m_interferenceGraph[idx]; // // Only look for nodes not in the stack yet. // if(node.m_previousStackElement == null) { if(node.m_fixed != null) { // // Just remember the first node associated with a physical register, but don't include them in the estimation. // if(firstPhysical == null) { firstPhysical = node; } } else { if(lastNode == null || node.HasLowerRelativeCost( lastNode )) { lastNode = node; } } } } if(lastNode == null) { // // We didn't find a node with a pseudo register, but we need to push something, so we push a physical register. // lastNode = firstPhysical; } CHECKS.ASSERT( lastNode != null, "Cannot find a candidate for spilling, even if the graph is not colorable" ); return lastNode; } //--// private void SpillVariables() { ComputeSpillCosts(); if(m_spillHistory == null) { m_spillHistory = SetFactory.NewWithReferenceEquality< VariableExpression >(); } InterferenceNode[] candidates = new InterferenceNode[m_interferenceGraphSize]; for(int idx = 0; idx < m_interferenceGraphSize; idx++) { InterferenceNode node = m_interferenceGraph[idx]; if(node.m_fixed != null) { continue; } if(m_spillHistory.Contains( node.m_source )) { continue; } if(node.m_edges.Cardinality < node.m_compatibleRegs.Cardinality && node.m_candidateColor >= 0) { // // This node can be colored for sure, because it interferes with less nodes than available registers. // continue; } candidates[idx] = node; } int iSpilled = 0; while(true) { InterferenceNode nodeToSpill = SelectNodeToSpill( candidates ); if(nodeToSpill == null) { break; } iSpilled++; SpillVariable( candidates, nodeToSpill ); #if REGISTERALLOCATOR_SPILL_ONLY_ONE_VARIABLE break; #endif } if(iSpilled == 0) { throw TypeConsistencyErrorException.Create( "Failed to find a pseudo register to spill in {0}", m_cfg ); } } private void SpillVariable( InterferenceNode[] candidates , InterferenceNode node ) { Operator opDef = node.m_definition; VariableExpression var = node.m_source; PseudoRegisterExpression source = (PseudoRegisterExpression)var.AliasedVariable; StackLocationExpression stackVar = null; ConstantExpression constVar = null; Expression targetVar; //--// m_spillHistory.Insert( var ); // // Remove this node and all the nodes it interferes with from the set of variables viable for spilling. // candidates[node.m_index] = null; foreach(int idxEdge in node.m_edges) { InterferenceNode otherNode = m_interferenceGraph[idxEdge]; candidates[otherNode.m_index] = null; } //--// // // Is this an assignment from an already spilled variables? // If so, we don't need to create a new variable. // if(opDef is SingleAssignmentOperator) { var rhs = opDef.FirstArgument; stackVar = rhs as StackLocationExpression; constVar = rhs as ConstantExpression; if(stackVar != null) { if(m_spillHistory.Contains( stackVar ) == false) { stackVar = null; } } } if(constVar != null) { // // No need to spill, it's a constant. // opDef.Delete(); targetVar = constVar; } else if(stackVar == null) { // // Don't associate the spill variable with the source variable, it would create a wrong alias for aggregate types. // stackVar = m_cfg.AllocateLocalStackLocation( source.Type, source.DebugName, null, 0 ); if(opDef is SingleAssignmentOperator || opDef is PhiOperator ) { opDef.SubstituteDefinition( var, stackVar ); } else { opDef.AddOperatorAfter( SingleAssignmentOperator.New( opDef.DebugInfo, stackVar, var ) ); } m_spillHistory.Insert( stackVar ); targetVar = stackVar; } else { opDef.Delete(); targetVar = stackVar; } //--// foreach(Operator opUse in m_useChains[var.SpanningTreeIndex]) { if(opUse is SingleAssignmentOperator || opUse is PhiOperator ) { // // No need to create a pseudo register and then assign it to the left side. Just substitute the usage. // opUse.SubstituteUsage( var, targetVar ); } else { PseudoRegisterExpression tmp = m_cfg.AllocatePseudoRegister( source.Type, source.DebugName, source.SourceVariable, source.SourceOffset ); opUse.AddOperatorBefore( SingleAssignmentOperator.New( opUse.DebugInfo, tmp, targetVar ) ); opUse.SubstituteUsage( var, tmp ); m_spillHistory.Insert( tmp ); } } } private InterferenceNode SelectNodeToSpill( InterferenceNode[] candidates ) { InterferenceNode lastNode; lastNode = SelectNodeToSpill( candidates, true , true , false ); if(lastNode != null) return lastNode; lastNode = SelectNodeToSpill( candidates, true , false, true ); if(lastNode != null) return lastNode; lastNode = SelectNodeToSpill( candidates, true , false, false ); if(lastNode != null) return lastNode; lastNode = SelectNodeToSpill( candidates, false, true , false ); if(lastNode != null) return lastNode; lastNode = SelectNodeToSpill( candidates, false, false, true ); if(lastNode != null) return lastNode; lastNode = SelectNodeToSpill( candidates, false, false, false ); return lastNode; } private InterferenceNode SelectNodeToSpill( InterferenceNode[] candidates , bool fOnlyConsiderNewWebs , bool fOnlyConsiderSpillCandidates , bool fOnlyConsiderFailures ) { InterferenceNode lastNode = null; for(int idx = 0; idx < candidates.Length; idx++) { InterferenceNode node = candidates[idx]; if(node == null) { continue; } // // Only look at the nodes that, if spilled, would create a new web? // if(fOnlyConsiderNewWebs && node.m_spillWouldCreateNewWebs == false) { continue; } // // Only look at the nodes that have been optimistically pushed on the stack? // if(fOnlyConsiderSpillCandidates && node.m_spillCandidate == false) { continue; } // // Only look at the nodes that failed to be assigned a color? // if(fOnlyConsiderFailures && node.m_candidateColor >= 0) { continue; } if(lastNode == null || node.HasLowerRelativeCost( lastNode )) { lastNode = node; } } return lastNode; } //--// private void ConvertToPhysicalRegisters( Operator op ) { foreach(var lhs in op.Results) { var node = GetInterferenceNode( lhs ); if(node != null) { if(lhs != node.m_assigned) { op.SubstituteDefinition( lhs, node.m_assigned ); } } } foreach(var rhs in op.Arguments) { var node = GetInterferenceNode( rhs ); if(node != null) { if(rhs != node.m_assigned) { op.SubstituteUsage( rhs, node.m_assigned ); } } } } private InterferenceNode GetInterferenceNode( Expression ex ) { if(ex is VariableExpression) { return m_interferenceGraphLookup[ex.SpanningTreeIndex]; } return null; } //--// private void SubstituteDefinition( Operator op , VariableExpression var , bool fBlockCopyPropagation ) { LowLevelVariableExpression source = var as LowLevelVariableExpression; PseudoRegisterExpression tmp = m_cfg.AllocatePseudoRegister( var.Type, var.DebugName, source != null ? source.SourceVariable : null, source != null ? source.SourceOffset : 0 ); op.SubstituteDefinition( var, tmp ); var opNew = SingleAssignmentOperator.New( op.DebugInfo, var, tmp ); if(fBlockCopyPropagation) { opNew.AddAnnotation( BlockCopyPropagationAnnotation.Create( m_cfg.TypeSystem, 0, false, true ) ); } op.AddOperatorAfter( opNew ); } private void SubstituteUsage( Operator op , VariableExpression var , bool fBlockCopyPropagation ) { LowLevelVariableExpression source = var as LowLevelVariableExpression; var sourceVariable = source != null ? source.SourceVariable : null; var sourceOffset = source != null ? source.SourceOffset : 0; if(op is PhiOperator) { PhiOperator opPhi = (PhiOperator)op; var rhs = opPhi.Arguments; var origins = opPhi.Origins; for(int i = 0; i < rhs.Length; i++) { if(rhs[i] == var) { PseudoRegisterExpression tmp = m_cfg.AllocatePseudoRegister( var.Type, var.DebugName, sourceVariable, sourceOffset ); var opNew = SingleAssignmentOperator.New( op.DebugInfo, tmp, var ); if(fBlockCopyPropagation) { opNew.AddAnnotation( BlockCopyPropagationAnnotation.Create( m_cfg.TypeSystem, 0, true, true ) ); } origins[i].AddOperator( opNew ); op.SubstituteUsage( i, tmp ); } } } else { PseudoRegisterExpression tmp = m_cfg.AllocatePseudoRegister( var.Type, var.DebugName, sourceVariable, sourceOffset ); var opNew = SingleAssignmentOperator.New( op.DebugInfo, tmp, var ); if(fBlockCopyPropagation) { opNew.AddAnnotation( BlockCopyPropagationAnnotation.Create( m_cfg.TypeSystem, 0, true, true ) ); } op.AddOperatorBefore( opNew ); op.SubstituteUsage( var, tmp ); } } //--// private bool ColorGraph( InterferenceNode root ) { using(new PerformanceCounters.ContextualTiming( m_cfg, "ColorGraph" )) { InterferenceNode node; bool fFound; // // Prep candidate coloring. // for(node = root; node != m_stackSentinel; node = node.m_previousStackElement) { node.ResetCandidate(); } // // If we cannot find a coloring without the constraints of the coalescing web, we should give up immediately. // fFound = FindColorCandidates( root ); if(fFound) { // // Build the coalesce web. // for(node = root; node != m_stackSentinel; node = node.m_previousStackElement) { node.m_coalesceWeb.Clear(); } for(node = root; node != m_stackSentinel; node = node.m_previousStackElement) { Operator op = node.m_definition; if(op is SingleAssignmentOperator || op is PiOperator ) { MergeCoalesceCandidates( node, op.FirstArgument, WebFlavor.Should ); } if(op is PhiOperator) { foreach(Expression ex in op.Arguments) { MergeCoalesceCandidates( node, ex, WebFlavor.Should ); } } foreach(Operator opUse in node.m_uses) { if(opUse is AbstractAssignmentOperator) { MergeCoalesceCandidates( node, opUse.FirstResult, WebFlavor.Should ); if(opUse is PhiOperator) { foreach(Expression ex in opUse.Arguments) { MergeCoalesceCandidates( node, ex, WebFlavor.Should ); } } } } if(op != null) { foreach(var an in op.FilterAnnotations< RegisterCouplingConstraintAnnotation >()) { var coupledSource = an.FindCoupledExpression( node.m_definition, node.m_source ); if(coupledSource != null) { MergeCoalesceCandidates( node, coupledSource, WebFlavor.Must ); } } } } while(true) { // // Reset colors. // for(node = root; node != m_stackSentinel; node = node.m_previousStackElement) { node.ResetCandidate(); } fFound = FindColorCandidates( root ); if(fFound) { // // Because of the aggressive use of coalesce webs, we might generate an incorrect coloring. // If so, revert the work and try again. // for(node = root; node != m_stackSentinel; node = node.m_previousStackElement) { if(node.m_assigned == null) { foreach(int idxEdge in node.m_edges) { InterferenceNode nodeEdge = m_interferenceGraph[idxEdge]; if(nodeEdge.m_candidateColor == node.m_candidateColor) { nodeEdge.ResetCandidate(); node .ResetCandidate(); fFound = false; } } } } } if(fFound) { AllocateRegisters( root ); break; } // // Remove one node from a coalesce web, retry. // ComputeSpillCosts(); BitVector web = new BitVector(); WebPair bestVictim = null; bestVictim = SelectWebToBreak( root, bestVictim, web, true , true ); bestVictim = SelectWebToBreak( root, bestVictim, web, true , false ); bestVictim = SelectWebToBreak( root, bestVictim, web, false, true ); bestVictim = SelectWebToBreak( root, bestVictim, web, false, false ); CHECKS.ASSERT( bestVictim != null, "Cannot find victim for removal from coalesce web" ); bestVictim.Remove(); } } return fFound; } } private WebPair SelectWebToBreak( InterferenceNode root , WebPair bestVictim , BitVector web , bool fIncludeFailuresOnly , bool fSkipPhysicalWebs ) { if(bestVictim != null) { // // Exit as soon as we find a victim. // return bestVictim; } for(var node = root; node != m_stackSentinel; node = node.m_previousStackElement) { // // On the first pass, skip nodes that have been successfully colored. // if(fIncludeFailuresOnly && node.m_candidateColor >= 0) { continue; } if(node.m_coalesceWeb.Count > 0) { web.ClearAll(); ComputeCoalesceSet( node, web ); bool fSkip = false; if(fSkipPhysicalWebs) { foreach(int idx in web) { InterferenceNode candidate = m_interferenceGraph[idx]; if(candidate.m_fixed != null) { fSkip = true; break; } } } if(fSkip) { continue; } //--// // // Try to find a victim to remove from the web based on its location, // giving higher score to variables from outside loops. // foreach(int idx in web) { InterferenceNode candidate = m_interferenceGraph[idx]; foreach(var pair in candidate.m_coalesceWeb) { if(pair.m_flavor != WebFlavor.Must) { if(bestVictim == null || bestVictim.SpillCost() > pair.SpillCost()) { bestVictim = pair; } } } } } } return bestVictim; } private bool FindColorCandidates( InterferenceNode root ) { var web = new BitVector(); bool fFound = true; for(InterferenceNode node = root; node != m_stackSentinel; node = node.m_previousStackElement) { if(node.m_candidateColor < 0) { BitVector availableRegs = node.m_compatibleRegs.Clone(); web.ClearAll(); ComputeCoalesceSet( node, web ); foreach(int idx in web) { if(UpdateAvailableRegisters( availableRegs, m_interferenceGraph[idx] ) == false) { break; } } bool fGot = false; foreach(int idx in web) { InterferenceNode coalesceNode = m_interferenceGraph[idx]; if(coalesceNode.m_candidateColor >= 0) { // // Assign the same color to all the nodes in the coalesce web, otherwise fail. // if(availableRegs[coalesceNode.m_candidateColor]) { node.m_candidateColor = coalesceNode.m_candidateColor; } fGot = true; break; } } if(fGot == false) { Abstractions.RegisterClass regClass; var td = node.m_source.Type; // // Make sure we select a register that is compatible with the type of variable. // if(td.IsNumeric) { switch(td.BuiltInType) { case TypeRepresentation.BuiltInTypes.R4: regClass = Abstractions.RegisterClass.SinglePrecision; break; case TypeRepresentation.BuiltInTypes.R8: regClass = Abstractions.RegisterClass.DoublePrecision; break; default: regClass = Abstractions.RegisterClass.Integer; break; } } else { regClass = Abstractions.RegisterClass.Address; } foreach(int regIdx in availableRegs) { if((m_registers[regIdx].StorageCapabilities & regClass) == regClass) { node.m_candidateColor = regIdx; break; } } } if(node.m_candidateColor < 0) { fFound = false; } else { foreach(int idx in web) { InterferenceNode coalesceNode = m_interferenceGraph[idx]; if(coalesceNode.m_candidateColor < 0) { if(coalesceNode.m_compatibleRegs[node.m_candidateColor]) { coalesceNode.m_candidateColor = node.m_candidateColor; } } } } } } return fFound; } private void AllocateRegisters( InterferenceNode node ) { for(; node != m_stackSentinel; node = node.m_previousStackElement) { if(node.m_assigned == null) { LowLevelVariableExpression source = (LowLevelVariableExpression)node.m_source.AliasedVariable; node.m_assigned = m_cfg.AllocateTypedPhysicalRegister( source.Type, m_registers[node.m_candidateColor], source.DebugName, source.SourceVariable, source.SourceOffset ); } } } private void ComputeCoalesceSet( InterferenceNode node , BitVector coalesceSet ) { if(coalesceSet.Set( node.m_index )) { var web = node.m_coalesceWeb; if(web != null) { foreach(var pair in web) { ComputeCoalesceSet( pair.m_node1, coalesceSet ); ComputeCoalesceSet( pair.m_node2, coalesceSet ); } } } } private void MergeCoalesceCandidates( InterferenceNode node , Expression ex , WebFlavor webFlavor ) { InterferenceNode nodeSrc = GetInterferenceNode( ex ); if(nodeSrc != null && nodeSrc != node && nodeSrc.m_assigned == null && nodeSrc.LivenessOverlapsWith( node ) == false) { WebPair oldPair = node.FindPair( nodeSrc ); if(oldPair != null) { oldPair.MaximizeFlavor( webFlavor ); } else { var vec = new BitVector(); var vecSrc = new BitVector(); ComputeCoalesceSet( node , vec ); ComputeCoalesceSet( nodeSrc, vecSrc ); if(DoesItInterfereWithCoalesceWeb( node , vecSrc ) || DoesItInterfereWithCoalesceWeb( nodeSrc, vec ) ) { return; } var pair = new WebPair( node, nodeSrc, webFlavor ); node .m_coalesceWeb.Add( pair ); nodeSrc.m_coalesceWeb.Add( pair ); } } } private bool DoesItInterfereWithCoalesceWeb( InterferenceNode node , BitVector vec ) { foreach(int idx in vec) { InterferenceNode other = m_interferenceGraph[idx]; if(other.LivenessOverlapsWith( node )) { return true; } } return false; } private bool UpdateAvailableRegisters( BitVector availableRegs , InterferenceNode node ) { foreach(int idxEdge in node.m_edges) { InterferenceNode nodeEdge = m_interferenceGraph[idxEdge]; int candidateIdx = nodeEdge.m_candidateColor; if(candidateIdx >= 0) { availableRegs.Clear( candidateIdx ); Abstractions.RegisterDescriptor regDesc = m_registers[candidateIdx]; foreach(Abstractions.RegisterDescriptor regDescInterfere in regDesc.InterfersWith) { availableRegs.Clear( regDescInterfere.Index ); } if(availableRegs.Cardinality == 0) { return false; } } } return true; } // // Access Methods // } }
//----------------------------------------------------------------------- // <copyright file="BusinessBase.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>This is the base class from which most business objects</summary> //----------------------------------------------------------------------- using System; using System.ComponentModel; using System.Linq.Expressions; using System.Reflection; using Csla.Properties; using Csla.Core; using Csla.Reflection; using System.Threading.Tasks; namespace Csla { /// <summary> /// This is the base class from which most business objects /// will be derived. /// </summary> /// <remarks> /// <para> /// This class is the core of the CSLA .NET framework. To create /// a business object, inherit from this class. /// </para><para> /// Please refer to 'Expert C# 2008 Business Objects' for /// full details on the use of this base class to create business /// objects. /// </para> /// </remarks> /// <typeparam name="T">Type of the business object being defined.</typeparam> [Serializable] public abstract class BusinessBase<T> : Core.BusinessBase, Core.ISavable, Core.ISavable<T>, IBusinessBase where T : BusinessBase<T> { #region Object ID Value /// <summary> /// Override this method to return a unique identifying /// value for this object. /// </summary> protected virtual object GetIdValue() { return null; } #endregion #region System.Object Overrides /// <summary> /// Returns a text representation of this object by /// returning the <see cref="GetIdValue"/> value /// in text form. /// </summary> public override string ToString() { object id = GetIdValue(); if (id == null) return base.ToString(); else return id.ToString(); } #endregion #region Clone /// <summary> /// Creates a clone of the object. /// </summary> /// <returns> /// A new object containing the exact data of the original object. /// </returns> public T Clone() { return (T)GetClone(); } #endregion #region Data Access /// <summary> /// Gets an instance of the client-side /// data portal for use in lazy loading /// of child types. /// </summary> /// <typeparam name="C">Type of child.</typeparam> protected IDataPortal<C> GetDataPortal<C>() { return (IDataPortal<C>)ApplicationContext.CurrentServiceProvider.GetService(typeof(IDataPortal<C>)); } /// <summary> /// Saves the object to the database. /// </summary> /// <remarks> /// <para> /// Calling this method starts the save operation, causing the object /// to be inserted, updated or deleted within the database based on the /// object's current state. /// </para><para> /// If <see cref="Core.BusinessBase.IsDeleted" /> is true /// the object will be deleted. Otherwise, if <see cref="Core.BusinessBase.IsNew" /> /// is true the object will be inserted. /// Otherwise the object's data will be updated in the database. /// </para><para> /// All this is contingent on <see cref="Core.BusinessBase.IsDirty" />. If /// this value is false, no data operation occurs. /// It is also contingent on <see cref="Core.BusinessBase.IsValid" />. /// If this value is false an /// exception will be thrown to indicate that the UI attempted to save an /// invalid object. /// </para><para> /// It is important to note that this method returns a new version of the /// business object that contains any data updated during the save operation. /// You MUST update all object references to use this new version of the /// business object in order to have access to the correct object data. /// </para><para> /// You can override this method to add your own custom behaviors to the save /// operation. For instance, you may add some security checks to make sure /// the user can save the object. If all security checks pass, you would then /// invoke the base Save method via <c>base.Save()</c>. /// </para> /// </remarks> /// <returns>A new object containing the saved values.</returns> public T Save() { try { return SaveAsync(false, null, true).Result; } catch (AggregateException ex) { if (ex.InnerExceptions.Count > 0) throw ex.InnerExceptions[0]; else throw; } } /// <summary> /// Saves the object to the database. /// </summary> public async Task<T> SaveAsync() { return await SaveAsync(false); } /// <summary> /// Saves the object to the database. /// </summary> /// <param name="forceUpdate"> /// If true, triggers overriding IsNew and IsDirty. /// If false then it is the same as calling Save(). /// </param> public async Task<T> SaveAsync(bool forceUpdate) { return await SaveAsync(forceUpdate, null, false); } /// <summary> /// Saves the object to the database. /// </summary> /// <param name="forceUpdate"> /// If true, triggers overriding IsNew and IsDirty. /// If false then it is the same as calling Save(). /// </param> /// <param name="userState">User state data.</param> /// <param name="isSync">True if the save operation should be synchronous.</param> protected async virtual Task<T> SaveAsync(bool forceUpdate, object userState, bool isSync) { if (forceUpdate && IsNew) { // mark the object as old - which makes it // not dirty MarkOld(); // now mark the object as dirty so it can save MarkDirty(true); } T result = default; if (this.IsChild) throw new InvalidOperationException(Resources.NoSaveChildException); if (EditLevel > 0) throw new InvalidOperationException(Resources.NoSaveEditingException); if (!IsValid && !IsDeleted) throw new Rules.ValidationException(Resources.NoSaveInvalidException); if (IsBusy) throw new InvalidOperationException(Resources.BusyObjectsMayNotBeSaved); if (IsDirty) { var dp = ApplicationContext.CreateInstanceDI<DataPortal<T>>(); if (isSync) { result = dp.Update((T)this); } else { if (ApplicationContext.AutoCloneOnUpdate) MarkBusy(); try { result = await dp.UpdateAsync((T)this); } finally { if (ApplicationContext.AutoCloneOnUpdate) { if (result != null) result.MarkIdle(); MarkIdle(); } } } } else { result = (T)this; } OnSaved(result, null, userState); return result; } /// <summary> /// Saves the object to the database, forcing /// IsNew to false and IsDirty to True. /// </summary> /// <param name="forceUpdate"> /// If true, triggers overriding IsNew and IsDirty. /// If false then it is the same as calling Save(). /// </param> /// <returns>A new object containing the saved values.</returns> /// <remarks> /// This overload is designed for use in web applications /// when implementing the Update method in your /// data wrapper object. /// </remarks> public T Save(bool forceUpdate) { if (forceUpdate && IsNew) { // mark the object as old - which makes it // not dirty MarkOld(); // now mark the object as dirty so it can save MarkDirty(true); } return this.Save(); } /// <summary> /// Saves the object to the database, merging /// any resulting updates into the existing /// object graph. /// </summary> public async Task SaveAndMergeAsync() { await SaveAndMergeAsync(false); } /// <summary> /// Saves the object to the database, merging /// any resulting updates into the existing /// object graph. /// </summary> /// <param name="forceUpdate"> /// If true, triggers overriding IsNew and IsDirty. /// If false then it is the same as calling SaveAndMergeAsync(). /// </param> public async Task SaveAndMergeAsync(bool forceUpdate) { new GraphMerger().MergeGraph(this, await SaveAsync(forceUpdate)); } #endregion #region ISavable Members void Csla.Core.ISavable.SaveComplete(object newObject) { OnSaved((T)newObject, null, null); } void Csla.Core.ISavable<T>.SaveComplete(T newObject) { OnSaved(newObject, null, null); } object Csla.Core.ISavable.Save() { return Save(); } object Csla.Core.ISavable.Save(bool forceUpdate) { return Save(forceUpdate); } [NonSerialized] [NotUndoable] private EventHandler<Csla.Core.SavedEventArgs> _nonSerializableSavedHandlers; [NotUndoable] private EventHandler<Csla.Core.SavedEventArgs> _serializableSavedHandlers; /// <summary> /// Event raised when an object has been saved. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods")] public event EventHandler<Csla.Core.SavedEventArgs> Saved { add { if (value.Method.IsPublic && (value.Method.DeclaringType.IsSerializable || value.Method.IsStatic)) _serializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>) System.Delegate.Combine(_serializableSavedHandlers, value); else _nonSerializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>) System.Delegate.Combine(_nonSerializableSavedHandlers, value); } remove { if (value.Method.IsPublic && (value.Method.DeclaringType.IsSerializable || value.Method.IsStatic)) _serializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>) System.Delegate.Remove(_serializableSavedHandlers, value); else _nonSerializableSavedHandlers = (EventHandler<Csla.Core.SavedEventArgs>) System.Delegate.Remove(_nonSerializableSavedHandlers, value); } } async Task<object> ISavable.SaveAsync() { return await SaveAsync(); } async Task<object> ISavable.SaveAsync(bool forceUpdate) { return await SaveAsync(forceUpdate); } /// <summary> /// Raises the Saved event, indicating that the /// object has been saved, and providing a reference /// to the new object instance. /// </summary> /// <param name="newObject">The new object instance.</param> /// <param name="e">Exception that occurred during operation.</param> /// <param name="userState">User state object.</param> [EditorBrowsable(EditorBrowsableState.Advanced)] protected virtual void OnSaved(T newObject, Exception e, object userState) { Csla.Core.SavedEventArgs args = new Csla.Core.SavedEventArgs(newObject, e, userState); if (_nonSerializableSavedHandlers != null) _nonSerializableSavedHandlers.Invoke(this, args); if (_serializableSavedHandlers != null) _serializableSavedHandlers.Invoke(this, args); } #endregion #region Register Properties/Methods /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P"> /// Type of property. /// </typeparam> /// <param name="info"> /// PropertyInfo object for the property. /// </param> /// <returns> /// The provided IPropertyInfo object. /// </returns> protected static PropertyInfo<P> RegisterProperty<P>(PropertyInfo<P> info) { return Core.FieldManager.PropertyInfoManager.RegisterProperty<P>(typeof(T), info); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyName">Property name from nameof()</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(string propertyName) { return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty<P>(reflectedPropertyInfo.Name); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyName">Property name from nameof()</param> /// <param name="relationship">Relationship with property value.</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, RelationshipTypes relationship) { return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, string.Empty, relationship)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="relationship">Relationship with property value.</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, RelationshipTypes relationship) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty<P>(reflectedPropertyInfo.Name, relationship); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyName">Property name from nameof()</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, string friendlyName) { return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, friendlyName)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty<P>(reflectedPropertyInfo.Name, friendlyName); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyName">Property name from nameof()</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <param name="defaultValue">Default Value for the property</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, string friendlyName, P defaultValue) { return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, friendlyName, defaultValue)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <param name="defaultValue">Default Value for the property</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName, P defaultValue) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty(reflectedPropertyInfo.Name, friendlyName, defaultValue); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyName">Property name from nameof()</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <param name="defaultValue">Default Value for the property</param> /// <param name="relationship">Relationship with property value.</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(string propertyName, string friendlyName, P defaultValue, RelationshipTypes relationship) { return RegisterProperty(Csla.Core.FieldManager.PropertyInfoFactory.Factory.Create<P>(typeof(T), propertyName, friendlyName, defaultValue, relationship)); } /// <summary> /// Indicates that the specified property belongs /// to the business object type. /// </summary> /// <typeparam name="P">Type of property</typeparam> /// <param name="propertyLambdaExpression">Property Expression</param> /// <param name="friendlyName">Friendly description for a property to be used in databinding</param> /// <param name="defaultValue">Default Value for the property</param> /// <param name="relationship">Relationship with property value.</param> /// <returns></returns> protected static PropertyInfo<P> RegisterProperty<P>(Expression<Func<T, object>> propertyLambdaExpression, string friendlyName, P defaultValue, RelationshipTypes relationship) { PropertyInfo reflectedPropertyInfo = Reflect<T>.GetProperty(propertyLambdaExpression); return RegisterProperty(reflectedPropertyInfo.Name, friendlyName, defaultValue, relationship); } /// <summary> /// Registers a method for use in Authorization. /// </summary> /// <param name="methodName">Method name from nameof()</param> /// <returns></returns> protected static MethodInfo RegisterMethod(string methodName) { return RegisterMethod(typeof(T), methodName); } /// <summary> /// Registers a method for use in Authorization. /// </summary> /// <param name="methodLambdaExpression">The method lambda expression.</param> /// <returns></returns> protected static MethodInfo RegisterMethod(Expression<Action<T>> methodLambdaExpression) { System.Reflection.MethodInfo reflectedMethodInfo = Reflect<T>.GetMethod(methodLambdaExpression); return RegisterMethod(reflectedMethodInfo.Name); } #endregion } }
/// APPLICATION: CreateuStoreProxy /// VERSION: 1.0.1 /// DATE: January 19, 2015 /// AUTHOR: Johan Cyprich /// AUTHOR URL: www.cyprich.com /// AUTHOR EMAIL: jcyprich@live.com /// /// LICENSE: /// The MIT License (MIT) /// /// Copyright (c) 2014 Johan Cyprich. All rights reserved. /// /// 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. /// /// SUMMARY: /// Create the httpd.conf file in proxy server for XMPie uStore. The file is written on /// local folder and then copied to the proxy server path defined by _outputPath. // Used to give a ReadKey prompt after app installs new .conf file if app is run from // the Windows desktop. Comment this out if run in command line mode. #define DESKTOP using System; using System.Collections.Generic; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; namespace CreateuStoreProxy { class Program { public static string connectionString; private static string _dbHost; // database server hosting uStore private static string _dbDatabase; // uStore database private static string _dbUser; // user name for uStore database private static string _dbPassword; // password for uStore database private static string _storeURL; // URL for uStore, assuming all are the same private static string _helioconName; private static string _helioconCode; private static string _outputPath; // path to httpd.conf on Heliocon folder in the uStore server private static string _appFolder = Directory.GetCurrentDirectory (); // path to this applications's folder /////////////////////////////////////////////////////////////////////////////////////////////// /// SUMMARY: /// Read the settings in CreateuStoreProxy.Settings.xml. /// /// GLOBAL VARIABLES: /// Values retrieved for the following global variables from the settings file: /// _dbHost /// _dbDatabase /// _dbUser /// _dbPassord /// _helioconName /// _helioconCode /// _outputPath /////////////////////////////////////////////////////////////////////////////////////////////// static protected void ReadSettings () { string element = ""; XmlTextReader reader = new XmlTextReader (_appFolder + @"\CreateuStoreProxy.Settings.xml"); while (reader.Read ()) { switch (reader.NodeType) { case XmlNodeType.Element: element = reader.Name; break; case XmlNodeType.Text: if (element == "Host") _dbHost = reader.Value; else if (element == "Database") _dbDatabase = reader.Value; else if (element == "User") _dbUser = reader.Value; else if (element == "Password") _dbPassword = reader.Value; else if (element == "RegistrationName") _helioconName = reader.Value; else if (element == "RegistrationCode") _helioconCode = reader.Value; else if (element == "Output") _outputPath = reader.Value; break; } // switch (reader.NodeType) } // while (reader.Read ()) } // static protected void ReadSettings () /////////////////////////////////////////////////////////////////////////////////////////////// /// SUMMARY: /// Write the final block of data for httpd.conf. /// /// GLOBAL VARIABLES: /// _storeURL /////////////////////////////////////////////////////////////////////////////////////////////// static protected void WriteEndConf () { using (StreamWriter w = new StreamWriter (_appFolder + "\\httpd.conf", true)) { w.WriteLine ("####USTORE_PROXY_STORE_FOLDER_SECTION_END########USTORE_PROXY_FINALIZE_SECTION_BEGIN####"); w.WriteLine ("#General rules to access uStore and uStore.CommonControls"); w.WriteLine (""); w.WriteLine (""); w.WriteLine (""); w.WriteLine ("RewriteCond %{HTTPS} off"); w.WriteLine ("RewriteCond %{HTTP_Host} ^" + _storeURL + "$"); w.WriteLine (@"RewriteProxy /aspnet_client/(.*) http\://" + _storeURL + "/aspnet_client/$1 [NC,U,L]"); w.WriteLine (""); w.WriteLine (""); w.WriteLine ("RewriteCond %{HTTPS} off"); w.WriteLine ("RewriteCond %{HTTP_Host} ^" + _storeURL + "$"); w.WriteLine (@"RewriteProxy ^/ustore((\.|/).*)?$ http\://" + _storeURL + "/ustore$1 [NC,U,L]"); w.WriteLine (""); w.WriteLine (""); w.WriteLine ("#--------------------------------------#"); w.WriteLine ("# uStore Proxy Shared - SSL"); w.WriteLine ("#--------------------------------------#"); w.WriteLine (""); w.WriteLine (""); w.WriteLine ("RewriteCond %{HTTPS} on"); w.WriteLine ("RewriteCond %{HTTP_Host} ^" + _storeURL + "$"); w.WriteLine (@"RewriteProxy /aspnet_client/(.*) https\://" + _storeURL + "/aspnet_client/$1 [NC,U,L]"); w.WriteLine (""); w.WriteLine (""); w.WriteLine ("RewriteCond %{HTTPS} on"); w.WriteLine ("RewriteCond %{HTTP_Host} ^" + _storeURL + "$"); w.WriteLine (@"RewriteProxy ^/ustore((\.|/).*)?$ https\://" + _storeURL + "/ustore$1 [NC,U,L]"); w.WriteLine (""); w.WriteLine (""); w.WriteLine ("####USTORE_PROXY_FINALIZE_SECTION_END####"); w.WriteLine ("####USTORE_END####"); } } // static protected void WriteEndConf () /////////////////////////////////////////////////////////////////////////////////////////////// /// SUMMARY: /// Write the starting block of data for httpd.conf. /// /// GLOBAL VARIABLES: /// _appFolder /// _helioconName /// _helioconCode /////////////////////////////////////////////////////////////////////////////////////////////// static protected void WriteStartConf () { using (StreamWriter w = new StreamWriter (_appFolder + @"\httpd.conf")) { w.WriteLine ("# Helicon ISAPI_Rewrite configuration file"); w.WriteLine ("# Version 3.1.0.99"); w.WriteLine (""); w.WriteLine (""); w.WriteLine ("# Registration info"); w.WriteLine ("RegistrationName= " + _helioconName); w.WriteLine ("RegistrationCode= " + _helioconCode); w.WriteLine ("####USTORE_BEGIN####"); w.WriteLine (""); w.WriteLine (""); } } // static protected void WriteStartConf () /////////////////////////////////////////////////////////////////////////////////////////////// /// SUMMARY: /// Builds the redirect code for the httpd.conf by reading information from the Store folder /// on the uStore database. /// /// GLOBAL VARIABLES: /// _storeURL /////////////////////////////////////////////////////////////////////////////////////////////// static protected void WriteStoresConf () { using (StreamWriter w = new StreamWriter (_appFolder + @"\httpd.conf", true)) { w.WriteLine ("# Stores"); int storeID = 0; // StoreID from Store table string landingFolder = ""; // LandingFolder from Store table using (SqlConnection conn = new SqlConnection (connectionString)) { conn.Open (); string sql = "SELECT StoreID, LandingDomain, LandingFolder, StatusID" + " FROM Store" + " WHERE StatusID=1"; using (SqlCommand command = new SqlCommand (sql, conn)) using (SqlDataReader reader = command.ExecuteReader ()) { while (reader.Read ()) { storeID = reader.GetInt32 (0); _storeURL = reader.GetString (1); // setting global variable, hopefully all URLs are the same landingFolder = reader.GetString (2); w.WriteLine ("####USTORE_PROXY_STORE_FOLDER_SECTION_BEGIN####"); w.WriteLine ("####STORE ID: " + storeID + "_BEGIN####"); w.WriteLine (""); w.WriteLine (""); w.WriteLine ("RewriteCond %{HTTPS} off"); w.WriteLine ("RewriteCond %{HTTP_Host} ^" + _storeURL + "$"); w.WriteLine ("RewriteProxy ^/" + landingFolder + @"(/)?$ http\://" + _storeURL + @"/ustore/default.aspx\?storeid=" + storeID + " [NC,U,L]"); w.WriteLine (""); w.WriteLine (""); w.WriteLine ("RewriteCond %{HTTPS} off"); w.WriteLine ("RewriteCond %{HTTP_Host} ^" + _storeURL + "$"); w.WriteLine ("RewriteProxy ^/" + landingFolder + @"/(.*)$ http\://" + _storeURL + "/uStore/$1 [NC,U,L]"); w.WriteLine (""); w.WriteLine (""); w.WriteLine ("#--------------------------------------#"); w.WriteLine ("# uStore Proxy store with folder - SSL"); w.WriteLine ("#--------------------------------------#"); w.WriteLine (""); w.WriteLine (""); w.WriteLine ("RewriteCond %{HTTPS} on"); w.WriteLine ("RewriteCond %{HTTP_Host} ^" + _storeURL + "$"); w.WriteLine ("RewriteProxy ^/" + landingFolder + @"(/)?$ https\://" + _storeURL + @"/ustore/default.aspx\?storeid=" + storeID + " [NC,U,L]"); w.WriteLine (""); w.WriteLine (""); w.WriteLine ("RewriteCond %{HTTPS} on"); w.WriteLine ("RewriteCond %{HTTP_Host} ^" + _storeURL + "$"); w.WriteLine ("RewriteProxy ^/" + landingFolder + @"/(.*)$ https\://" + _storeURL + "/ustore/$1 [NC,U,L]"); w.WriteLine (""); w.WriteLine (""); w.WriteLine ("####STORE ID: " + storeID + "_END####"); w.WriteLine ("####USTORE_PROXY_STORE_FOLDER_SECTION_END####"); w.WriteLine (""); w.WriteLine (""); } // while (reader.Read ()) } // using (SqlDataReader reader = command.ExecuteReader ()) conn.Close (); } // using (SqlConnection conn = new SqlConnection (connectionString)) } } // static protected void WriteStoresConf () /////////////////////////////////////////////////////////////////////////////////////////////// /// SUMMARY: /// Copy the httpd.conf created in the application folder to the uStore server. The existing /// .conf file will be renamed before the new file is copied to the folder. The old file will /// have the date (YYYYMMDD-HHMMSS) appended to its filename. /// /// GLOBAL VARIABLES: /// _appFolder /// _outputPath /////////////////////////////////////////////////////////////////////////////////////////////// static protected void CopyConf () { if (File.Exists (_outputPath + @"\httpd.conf")) { DateTime nowDate = DateTime.Now; // get the current date // Rename active httpd.conf to httpd.conf.YYYYMMDD File.Move (_outputPath + @"\httpd.conf", _outputPath + @"\httpd.conf." + nowDate.Year.ToString () + nowDate.Month.ToString ("00") + nowDate.Day.ToString ("00") + "-" + nowDate.Hour.ToString ("00") + nowDate.Minute.ToString ("00") + nowDate.Second.ToString ("00")); // Copy new httpd.conf to uStore Proxy server. File.Copy (_appFolder + @"\httpd.conf", _outputPath + @"\httpd.conf"); } } // static protected void CopyConf () /*** MAIN *******************************************************************************************************************/ static void Main (string [] args) { Console.WriteLine ("Create uStore Proxy 1.0.0"); Console.WriteLine ("by Johan Cyprich"); Console.WriteLine ("Copyright (C) 2014-2015 Johan Cyprich. All rights reserved."); Console.WriteLine ("Licenced under the MIT License."); Console.WriteLine (""); ReadSettings (); connectionString = "Data Source=" + _dbHost + ";" + "Initial Catalog=" + _dbDatabase + ";" + "User id=" + _dbUser + ";" + "Password=" + _dbPassword; WriteStartConf (); WriteStoresConf (); WriteEndConf (); if (_outputPath != "") CopyConf (); Console.WriteLine ("httpd.conf generated"); #if DESKTOP Console.ReadKey (); #endif } // static void Main (string [] args) } // class Program } // namespace CreateuStoreProxy
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 STEM_Db.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using Umbraco.Core.Events; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Persistence; using Umbraco.Core.Persistence.Querying; using Umbraco.Core.Persistence.UnitOfWork; namespace Umbraco.Core.Services { public class PublicAccessService : RepositoryService, IPublicAccessService { public PublicAccessService(IDatabaseUnitOfWorkProvider provider, RepositoryFactory repositoryFactory, ILogger logger, IEventMessagesFactory eventMessagesFactory) : base(provider, repositoryFactory, logger, eventMessagesFactory) { } /// <summary> /// Gets all defined entries and associated rules /// </summary> /// <returns></returns> public IEnumerable<PublicAccessEntry> GetAll() { using (var repo = RepositoryFactory.CreatePublicAccessRepository(UowProvider.GetUnitOfWork())) { return repo.GetAll(); } } /// <summary> /// Gets the entry defined for the content item's path /// </summary> /// <param name="content"></param> /// <returns>Returns null if no entry is found</returns> public PublicAccessEntry GetEntryForContent(IContent content) { return GetEntryForContent(content.Path.EnsureEndsWith("," + content.Id)); } /// <summary> /// Gets the entry defined for the content item based on a content path /// </summary> /// <param name="contentPath"></param> /// <returns>Returns null if no entry is found</returns> /// <remarks> /// NOTE: This method get's called *very* often! This will return the results from cache /// </remarks> public PublicAccessEntry GetEntryForContent(string contentPath) { //Get all ids in the path for the content item and ensure they all // parse to ints that are not -1. var ids = contentPath.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => { int val; if (int.TryParse(x, out val)) { return val; } return -1; }) .Where(x => x != -1) .ToList(); //start with the deepest id ids.Reverse(); using (var repo = RepositoryFactory.CreatePublicAccessRepository(UowProvider.GetUnitOfWork())) { //This will retrieve from cache! var entries = repo.GetAll().ToArray(); foreach (var id in ids) { var found = entries.FirstOrDefault(x => x.ProtectedNodeId == id); if (found != null) return found; } } return null; } /// <summary> /// Returns true if the content has an entry for it's path /// </summary> /// <param name="content"></param> /// <returns></returns> public Attempt<PublicAccessEntry> IsProtected(IContent content) { var result = GetEntryForContent(content); return Attempt.If(result != null, result); } /// <summary> /// Returns true if the content has an entry based on a content path /// </summary> /// <param name="contentPath"></param> /// <returns></returns> public Attempt<PublicAccessEntry> IsProtected(string contentPath) { var result = GetEntryForContent(contentPath); return Attempt.If(result != null, result); } [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use AddRule instead, this method will be removed in future versions")] public Attempt<OperationStatus<PublicAccessEntry, OperationStatusType>> AddOrUpdateRule(IContent content, string ruleType, string ruleValue) { return AddRule(content, ruleType, ruleValue); } /// <summary> /// Adds a rule /// </summary> /// <param name="content"></param> /// <param name="ruleType"></param> /// <param name="ruleValue"></param> /// <returns></returns> public Attempt<OperationStatus<PublicAccessEntry, OperationStatusType>> AddRule(IContent content, string ruleType, string ruleValue) { var evtMsgs = EventMessagesFactory.Get(); var uow = UowProvider.GetUnitOfWork(); using (var repo = RepositoryFactory.CreatePublicAccessRepository(uow)) { var entry = repo.GetAll().FirstOrDefault(x => x.ProtectedNodeId == content.Id); if (entry == null) return Attempt<OperationStatus<PublicAccessEntry, OperationStatusType>>.Fail(); var existingRule = entry.Rules.FirstOrDefault(x => x.RuleType == ruleType && x.RuleValue == ruleValue); if (existingRule == null) { entry.AddRule(ruleValue, ruleType); } else { //If they are both the same already then there's nothing to update, exit return Attempt<OperationStatus<PublicAccessEntry, OperationStatusType>>.Succeed( new OperationStatus<PublicAccessEntry, OperationStatusType>(entry, OperationStatusType.Success, evtMsgs)); } if (Saving.IsRaisedEventCancelled( new SaveEventArgs<PublicAccessEntry>(entry, evtMsgs), this)) { return Attempt<OperationStatus<PublicAccessEntry, OperationStatusType>>.Fail( new OperationStatus<PublicAccessEntry, OperationStatusType>(entry, OperationStatusType.FailedCancelledByEvent, evtMsgs)); } repo.AddOrUpdate(entry); uow.Commit(); Saved.RaiseEvent(new SaveEventArgs<PublicAccessEntry>(entry, false, evtMsgs), this); return Attempt<OperationStatus<PublicAccessEntry, OperationStatusType>>.Succeed( new OperationStatus<PublicAccessEntry, OperationStatusType>(entry, OperationStatusType.Success, evtMsgs)); } } /// <summary> /// Removes a rule /// </summary> /// <param name="content"></param> /// <param name="ruleType"></param> /// <param name="ruleValue"></param> public Attempt<OperationStatus> RemoveRule(IContent content, string ruleType, string ruleValue) { var evtMsgs = EventMessagesFactory.Get(); var uow = UowProvider.GetUnitOfWork(); using (var repo = RepositoryFactory.CreatePublicAccessRepository(uow)) { var entry = repo.GetAll().FirstOrDefault(x => x.ProtectedNodeId == content.Id); if (entry == null) return Attempt<OperationStatus>.Fail(); var existingRule = entry.Rules.FirstOrDefault(x => x.RuleType == ruleType && x.RuleValue == ruleValue); if (existingRule == null) return Attempt<OperationStatus>.Fail(); entry.RemoveRule(existingRule); if (Saving.IsRaisedEventCancelled( new SaveEventArgs<PublicAccessEntry>(entry, evtMsgs), this)) { return Attempt.Fail(OperationStatus.Cancelled(evtMsgs)); } repo.AddOrUpdate(entry); uow.Commit(); Saved.RaiseEvent(new SaveEventArgs<PublicAccessEntry>(entry, false, evtMsgs), this); return Attempt.Succeed(OperationStatus.Success(evtMsgs)); } } /// <summary> /// Saves the entry /// </summary> /// <param name="entry"></param> public Attempt<OperationStatus> Save(PublicAccessEntry entry) { var evtMsgs = EventMessagesFactory.Get(); if (Saving.IsRaisedEventCancelled( new SaveEventArgs<PublicAccessEntry>(entry, evtMsgs), this)) { return Attempt.Fail(OperationStatus.Cancelled(evtMsgs)); } var uow = UowProvider.GetUnitOfWork(); using (var repo = RepositoryFactory.CreatePublicAccessRepository(uow)) { repo.AddOrUpdate(entry); uow.Commit(); } Saved.RaiseEvent(new SaveEventArgs<PublicAccessEntry>(entry, false, evtMsgs), this); return Attempt.Succeed(OperationStatus.Success(evtMsgs)); } /// <summary> /// Deletes the entry and all associated rules /// </summary> /// <param name="entry"></param> public Attempt<OperationStatus> Delete(PublicAccessEntry entry) { var evtMsgs = EventMessagesFactory.Get(); if (Deleting.IsRaisedEventCancelled( new DeleteEventArgs<PublicAccessEntry>(entry, evtMsgs), this)) { return Attempt.Fail(OperationStatus.Cancelled(evtMsgs)); } var uow = UowProvider.GetUnitOfWork(); using (var repo = RepositoryFactory.CreatePublicAccessRepository(uow)) { repo.Delete(entry); uow.Commit(); } Deleted.RaiseEvent(new DeleteEventArgs<PublicAccessEntry>(entry, false, evtMsgs), this); return Attempt.Succeed(OperationStatus.Success(evtMsgs)); } /// <summary> /// Occurs before Save /// </summary> public static event TypedEventHandler<IPublicAccessService, SaveEventArgs<PublicAccessEntry>> Saving; /// <summary> /// Occurs after Save /// </summary> public static event TypedEventHandler<IPublicAccessService, SaveEventArgs<PublicAccessEntry>> Saved; /// <summary> /// Occurs before Delete /// </summary> public static event TypedEventHandler<IPublicAccessService, DeleteEventArgs<PublicAccessEntry>> Deleting; /// <summary> /// Occurs after Delete /// </summary> public static event TypedEventHandler<IPublicAccessService, DeleteEventArgs<PublicAccessEntry>> Deleted; } }
/* $Id: Extensions.cs 333 2014-01-20 02:31:45Z catwalkagogo@gmail.com $ */ using System; using System.Reflection; using System.Linq; using System.Linq.Expressions; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Threading; namespace CW { public static partial class Ext{ #region Exception public static void ThrowIfNull(this object obj) { if(obj == null) { throw new ArgumentNullException(); } } public static void ThrowIfNull(this object obj, string message) { if(obj == null) { throw new ArgumentNullException(message); } } public static void ThrowIfNull(this IntPtr obj) { if(obj == IntPtr.Zero) { throw new ArgumentNullException(); } } public static void ThrowIfNull(this IntPtr obj, string message) { if(obj == IntPtr.Zero) { throw new ArgumentNullException(message); } } public static void ThrowIfOutOfRange(this int n, int min, int max) { if((n < min) || (max < n)) { throw new ArgumentOutOfRangeException(); } } public static void ThrowIfOutOfRange(this int n, int min, int max, string message) { if((n < min) || (max < n)) { throw new ArgumentOutOfRangeException(message); } } public static void ThrowIfOutOfRange(this int n, int min) { if(n < min) { throw new ArgumentOutOfRangeException(); } } public static void ThrowIfOutOfRange(this int n, int min, string message) { if(n < min) { throw new ArgumentOutOfRangeException(message); } } public static void ThrowIfOutOfRange(this double n, double min, double max) { if((n < min) || (max < n)) { throw new ArgumentOutOfRangeException(); } } public static void ThrowIfOutOfRange(this double n, double min, double max, string message) { if((n < min) || (max < n)) { throw new ArgumentOutOfRangeException(message); } } public static void ThrowIfOutOfRange(this double n, double min) { if(n < min) { throw new ArgumentOutOfRangeException(); } } public static void ThrowIfOutOfRange(this double n, double min, string message) { if(n < min) { throw new ArgumentOutOfRangeException(message); } } public static void ThrowIfOutOfRange(this long n, long min, long max) { if((n < min) || (max < n)) { throw new ArgumentOutOfRangeException(); } } public static void ThrowIfOutOfRange(this long n, long min, long max, string message) { if((n < min) || (max < n)) { throw new ArgumentOutOfRangeException(message); } } public static void ThrowIfOutOfRange(this long n, long min) { if(n < min) { throw new ArgumentOutOfRangeException(); } } public static void ThrowIfOutOfRange(this long n, long min, string message) { if(n < min) { throw new ArgumentOutOfRangeException(message); } } public static void ThrowIfNullOrEmpty(this string str, string message) { if(str == null) { throw new ArgumentNullException(message); } if(str == "") { throw new ArgumentException(message); } } #endregion #region Assembly public static string GetInformationalVersion(this Assembly asm) { var ver = asm.GetCustomAttributes().OfType<AssemblyInformationalVersionAttribute>().FirstOrDefault(); return (ver != null) ? ver.InformationalVersion : null; } public static Version GetVersion(this Assembly asm) { return asm.GetName().Version; } public static string GetCopyright(this Assembly asm) { var copy = asm.GetCustomAttributes().OfType<AssemblyCopyrightAttribute>().FirstOrDefault(); return (copy != null) ? copy.Copyright : null; } public static string GetDescription(this Assembly asm) { var dscr = asm.GetCustomAttributes().OfType<AssemblyDescriptionAttribute>().FirstOrDefault(); return (dscr != null) ? dscr.Description : null; } #endregion #region string public static bool IsNullOrEmpty(this string str) { return String.IsNullOrEmpty(str); } public static bool IsNullOrWhitespace(this string str){ return String.IsNullOrWhiteSpace(str); } /* public static bool IsMatchWildCard(this string str, string mask) { return PathMatchSpec(str, mask); } [DllImport("shlwapi.dll", EntryPoint = "PathMatchSpec", CharSet = CharSet.Auto)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool PathMatchSpec([MarshalAs(UnmanagedType.LPTStr)] string path, [MarshalAs(UnmanagedType.LPTStr)] string spec); */ public static int IndexOfRegex(this string str, string pattern) { return IndexOfRegex(str, pattern, 0, RegexOptions.None); } public static int IndexOfRegex(this string str, string pattern, int start) { return IndexOfRegex(str, pattern, start, RegexOptions.None); } public static int IndexOfRegex(this string str, string pattern, int start, RegexOptions options) { var rex = new Regex(pattern); var match = rex.Match(str, start); return (match.Success) ? match.Index : match.Index; } public static string ReplaceRegex(this string str, string pattern, string replacement) { return Regex.Replace(str, pattern, replacement); } public static string ReplaceRegex(this string str, string pattern, string replacement, RegexOptions option) { return Regex.Replace(str, pattern, replacement, option); } public static string ReplaceRegex(this string str, string pattern, MatchEvaluator eval) { return Regex.Replace(str, pattern, eval); } public static string ReplaceRegex(this string str, string pattern, MatchEvaluator eval, RegexOptions option) { return Regex.Replace(str, pattern, eval, option); } public static string Replace(this string str, string[] oldValues, string newValue) { foreach(var value in oldValues){ str = str.Replace(value, newValue); } return str; } public static Match Match(this string str, string pattern){ return Regex.Match(str, pattern); } public static Match Match(this string str, string pattern, RegexOptions options){ return Regex.Match(str, pattern, options); } public static Match MatchIgnoreCase(this string str, string pattern, RegexOptions options){ return Regex.Match(str, pattern, RegexOptions.IgnoreCase); } public static string Join(this IEnumerable<string> source, string separator) { return String.Join(separator, source.ToArray()); } public static string Join<T>(this IEnumerable<T> source, string separator) { return String.Join(separator, source.Select(o => o.ToString()).ToArray()); } #endregion #region char public static bool IsDecimalNumber(this char c){ return (('0' <= c) && (c <= '9')); } public static bool IsSmallAlphabet(this char c){ int n = (int)c; return (('a' <= n) && (n <= 'z')); } public static bool IsLargeAlphabet(this char c){ int n = (int)c; return (('A' <= n) && (n <= 'Z')); } public static bool IsHiragana(this char c) { return 0x3040 <= c && c <= 0x309F; } public static bool IsKatakana(this char c) { return (0x30a1 <= c) && (c <= 0x30fa); } public static bool IsKanji(this char c) { return (0x4e00 <= c) && (c <= 0x9fff); } #endregion #region Array public static void Shuffle<T>(T[] array){ var n = array.Length; var rnd = new Random(); while(n > 1){ var k = rnd.Next(n); n--; var temp = array[n]; array[n] = array[k]; array[k] = temp; } } public static void StableSort<T>(this T[] array){ array.MergeSort(Comparer<T>.Default); } public static void StableSort<T>(this T[] array, IComparer<T> comparer){ array.MergeSort(comparer); } public static void MergeSort<T>(this T[] array){ array.MergeSort(Comparer<T>.Default); } public static void MergeSort<T>(this T[] array, IComparer<T> comparer){ array.MergeSort(comparer, 0, array.Length, new T[array.Length]); } private const int MergeSortThreshold = 16; private static void MergeSort<T>(this T[] array, IComparer<T> comparer, int left, int right, T[] temp){ if(left >= (right - 1)){ return; } int count = right - left; if(count <= MergeSortThreshold){ array.InsertSort(comparer, left, right); }else{ int middle = (left + right) >> 1; array.MergeSort(comparer, left, middle, temp); array.MergeSort(comparer, middle, right, temp); array.Merge(comparer, left, middle, right, temp); } } private static void Merge<T>(this T[] array, IComparer<T> comparer, int left, int middle, int right, T[] temp){ Array.Copy(array, left, temp, left, middle - left); int i, j; for(i = middle, j = right - 1; i < right; i++, j--){ temp[i] = array[j]; } i = left; j = right - 1; for(int k = left; k < right; k++){ if(comparer.Compare(temp[i], temp[j]) < 0){ array[k] = temp[i++]; }else{ array[k] = temp[j--]; } } } /* public static void ParallelMergeSort<T>(this T[] array){ array.ParallelMergeSort(Comparer<T>.Default); } public static void ParallelMergeSort<T>(this T[] array, IComparer<T> comparer){ if(array.Length < 1024){ array.MergeSort(comparer); }else{ var temp = new T[array.Length]; array.ParallelMergeSort(comparer, 0, array.Length, temp); } } private static int threadCount = 1; private static void ParallelMergeSort<T>(this T[] array, IComparer<T> comparer, int left, int right, T[] temp){ if(left >= (right - 1)){ return; } int count = right - left; if(count <= MergeSortThreshold){ array.InsertSort(comparer, left, right); }else if(threadCount < Environment.ProcessorCount){ int middle = (left + right) >> 1; Interlocked.Increment(ref threadCount); var thread1 = new Thread(new ThreadStart(delegate{ array.ParallelMergeSort(comparer, left, middle, temp); Interlocked.Decrement(ref threadCount); })); thread1.Start(); array.ParallelMergeSort(comparer, middle, right, temp); thread1.Join(); array.Merge(comparer, left, middle, right, temp); }else{ int middle = (left + right) >> 1; array.ParallelMergeSort(comparer, left, middle, temp); array.ParallelMergeSort(comparer, middle, right, temp); array.Merge(comparer, left, middle, right, temp); } } */ public static void InsertSort<T>(this T[] array){ array.InsertSort(Comparer<T>.Default, 0, array.Length); } private static void InsertSort<T>(this T[] array, IComparer<T> comparer, int left, int right){ for(int i = left + 1; i < right; i++){ for(int j = i; j >= left + 1 && comparer.Compare(array[j - 1], array[j]) > 0; --j){ Swap(ref array[j], ref array[j - 1]); } } } public static void ShellSort<T>(this T[] array){ array.ShellSort(Comparer<T>.Default, 0, array.Length); } private static void ShellSort<T>(this T[] array, IComparer<T> comparer, int left, int right){ int j, h; T temp; h = left + 1; while (h < right){ h = (h * 3) + 1; } int left2 = left + 1; while(h > left2){ h = h / 3; for(int i = h; i < right; i++){ temp = array[i]; j = i - h; while(comparer.Compare(temp, array[j]) < 0){ array[j + h] = array[j]; j = j - h; if(j < left){ break; } } array[j + h] = temp; } } } private static void Swap<T>(ref T x, ref T y){ T temp = x; x = y; y = temp; } public static void HeapSort<T>(this T[] array){ array.HeapSort(Comparer<T>.Default, 0, array.Length); } private static void HeapSort<T>(this T[] array, IComparer<T> comparer, int left, int right){ int max = right - 1; for(int i = (max - 1) >> 1; i >= left; i--){ array.MakeHeap(comparer, i, max); } for(int i = max; i > left; i--){ Swap(ref array[left], ref array[i]); array.MakeHeap(comparer, left, i - 1); } } private static void MakeHeap<T>(this T[] array, IComparer<T> comparer, int i, int right){ T v = array[i]; while(true){ int j = (i << 1) + 1; if(j > right){ break; } if(j != right){ if(comparer.Compare(array[j + 1], array[j]) > 0){ j = j + 1; } } if(comparer.Compare(v, array[j]) >= 0){ break; } array[i] = array[j]; i = j; } array[i] = v; } #endregion #region Event public static void Raise(this Delegate handler, params object[] args){ if(handler != null){ handler.DynamicInvoke(args); } } #endregion #region WeakReference public static bool IsAlive<T>(this WeakReference<T> reference) where T : class { reference.ThrowIfNull("reference"); T v; return reference.TryGetTarget(out v); } #endregion } }
// <copyright file="Startup.cs" company="Microsoft Open Technologies, Inc."> // Copyright 2011-2013 Microsoft Open Technologies, 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> using System; using System.Collections.Concurrent; using System.IO; using System.Linq; using System.Security.Claims; using System.Security.Principal; using System.Threading.Tasks; using Katana.Sandbox.WebServer; using Microsoft.Owin; using Microsoft.Owin.Extensions; using Microsoft.Owin.Logging; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Cookies; using Microsoft.Owin.Security.Facebook; using Microsoft.Owin.Security.Google; using Microsoft.Owin.Security.Infrastructure; using Microsoft.Owin.Security.OAuth; using Microsoft.Owin.Security.WsFederation; using Owin; [assembly: OwinStartup(typeof(Startup))] namespace Katana.Sandbox.WebServer { public class Startup { private readonly ConcurrentDictionary<string, string> _authenticationCodes = new ConcurrentDictionary<string, string>(StringComparer.Ordinal); public void Configuration(IAppBuilder app) { var logger = app.CreateLogger("Katana.Sandbox.WebServer"); logger.WriteInformation("Application Started"); app.Use(async (context, next) => { context.Get<TextWriter>("host.TraceOutput").WriteLine("{0} {1}{2}", context.Request.Method, context.Request.PathBase, context.Request.Path); await next(); context.Get<TextWriter>("host.TraceOutput").WriteLine("{0} {1}{2}", context.Response.StatusCode, context.Request.PathBase, context.Request.Path); }); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "Application", // LoginPath = new PathString("/Account/Login"), }); app.SetDefaultSignInAsAuthenticationType("External"); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "External", AuthenticationMode = AuthenticationMode.Active, CookieName = CookieAuthenticationDefaults.CookiePrefix + "External", ExpireTimeSpan = TimeSpan.FromMinutes(5), }); app.UseFacebookAuthentication(new FacebookAuthenticationOptions { AppId = "454990987951096", AppSecret = "ca7cbddf944f91f23c1ed776f265478e", // Scope = "email user_birthday user_website" }); app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() { ClientId = "1033034290282-6h0n78feiepoltpqkmsrqh1ngmeh4co7.apps.googleusercontent.com", ClientSecret = "6l7lHh-B0_awzoTrlTGWh7km", }); app.UseTwitterAuthentication("6XaCTaLbMqfj6ww3zvZ5g", "Il2eFzGIrYhz6BWjYhVXBPQSfZuS4xoHpSSyD9PI"); app.UseMicrosoftAccountAuthentication("000000004C0EA787", "QZde5m5HHZPxdieV0lOy7bBVTbVqR9Ju"); // app.UseAspNetAuthSession(); /* app.UseCookieAuthentication(new CookieAuthenticationOptions() { SessionStore = new InMemoryAuthSessionStore() }); app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType); */ app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions() { Wtrealm = "http://Katana.Sandbox.WebServer", MetadataAddress = "https://login.windows.net/cdc690f9-b6b8-4023-813a-bae7143d1f87/FederationMetadata/2007-06/FederationMetadata.xml", }); /* app.UseOpenIdConnectAuthentication(new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions() { // Change vdir to http://localhost:63786/ // User adaluser@adale2etenant1.ccsctp.net Authority = "https://login.windows-ppe.net/adale2etenant1.ccsctp.net", ClientId = "a81cf7a1-5a2d-4382-9f4b-0fa91a8992dc", }); */ /* app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions { }); // CORS support app.Use(async (context, next) => { IOwinRequest req = context.Request; IOwinResponse res = context.Response; // for auth2 token requests, and web api requests if (req.Path.StartsWithSegments(new PathString("/Token")) || req.Path.StartsWithSegments(new PathString("/api"))) { // if there is an origin header var origin = req.Headers.Get("Origin"); if (!string.IsNullOrEmpty(origin)) { // allow the cross-site request res.Headers.Set("Access-Control-Allow-Origin", origin); } // if this is pre-flight request if (req.Method == "OPTIONS") { // respond immediately with allowed request methods and headers res.StatusCode = 200; res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST"); res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", "authorization"); // no further processing return; } } // continue executing pipeline await next(); }); app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions { AuthorizeEndpointPath = new PathString("/Authorize"), TokenEndpointPath = new PathString("/Token"), ApplicationCanDisplayErrors = true, #if DEBUG AllowInsecureHttp = true, #endif Provider = new OAuthAuthorizationServerProvider { OnValidateClientRedirectUri = ValidateClientRedirectUri, OnValidateClientAuthentication = ValidateClientAuthentication, OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials, }, AuthorizationCodeProvider = new AuthenticationTokenProvider { OnCreate = CreateAuthenticationCode, OnReceive = ReceiveAuthenticationCode, }, RefreshTokenProvider = new AuthenticationTokenProvider { OnCreate = CreateRefreshToken, OnReceive = ReceiveRefreshToken, } }); /* app.Map("/Account/Login", map => { map.Run(context => { // context.Authentication.Challenge("Google"); return Task.FromResult(0); }); }); */ app.Use((context, next) => { var user = context.Authentication.User; if (user == null || user.Identity == null || !user.Identity.IsAuthenticated) { context.Authentication.Challenge(); return Task.FromResult(0); } return next(); }); app.Run(async context => { var response = context.Response; var user = context.Authentication.User; var identity = user.Identities.First(); // var properties = result.Properties.Dictionary; response.ContentType = "application/json"; response.Write("{\"Details\":["); foreach (var claim in identity.Claims) { response.Write("{\"Name\":\""); response.Write(claim.Type); response.Write("\",\"Value\":\""); response.Write(claim.Value); response.Write("\",\"Issuer\":\""); response.Write(claim.Issuer); response.Write("\"},"); // TODO: No comma on the last one } response.Write("],\"Properties\":["); /* foreach (var pair in properties) { response.Write("{\"Name\":\""); response.Write(pair.Key); response.Write("\",\"Value\":\""); response.Write(pair.Value); response.Write("\"},"); // TODO: No comma on the last one }*/ response.Write("]}"); }); } private Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context) { if (context.ClientId == "123456") { context.Validated("http://localhost:18002/Katana.Sandbox.WebClient/ClientApp.aspx"); } else if (context.ClientId == "7890ab") { context.Validated("http://localhost:18002/Katana.Sandbox.WebClient/ClientPageSignIn.html"); } return Task.FromResult(0); } private Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context) { string clientId; string clientSecret; if (context.TryGetBasicCredentials(out clientId, out clientSecret) || context.TryGetFormCredentials(out clientId, out clientSecret)) { if (clientId == "123456" && clientSecret == "abcdef") { context.Validated(); } else if (context.ClientId == "7890ab" && clientSecret == "7890ab") { context.Validated(); } } return Task.FromResult(0); } private Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { var identity = new ClaimsIdentity(new GenericIdentity(context.UserName, OAuthDefaults.AuthenticationType), context.Scope.Select(x => new Claim("urn:oauth:scope", x))); context.Validated(identity); return Task.FromResult(0); } private void CreateAuthenticationCode(AuthenticationTokenCreateContext context) { context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n")); _authenticationCodes[context.Token] = context.SerializeTicket(); } private void ReceiveAuthenticationCode(AuthenticationTokenReceiveContext context) { string value; if (_authenticationCodes.TryRemove(context.Token, out value)) { context.DeserializeTicket(value); } } private void CreateRefreshToken(AuthenticationTokenCreateContext context) { context.SetToken(context.SerializeTicket()); } private void ReceiveRefreshToken(AuthenticationTokenReceiveContext context) { context.DeserializeTicket(context.Token); } } }
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 VideoIndexerOrchestrationWeb.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; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Net.Test.Common; using System.Threading; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class AcceptAsync { private readonly ITestOutputHelper _log; public AcceptAsync(ITestOutputHelper output) { _log = TestLogging.GetInstance(); } public void OnAcceptCompleted(object sender, SocketAsyncEventArgs args) { _log.WriteLine("OnAcceptCompleted event handler"); EventWaitHandle handle = (EventWaitHandle)args.UserToken; handle.Set(); } public void OnConnectCompleted(object sender, SocketAsyncEventArgs args) { _log.WriteLine("OnConnectCompleted event handler"); EventWaitHandle handle = (EventWaitHandle)args.UserToken; handle.Set(); } [Fact] [Trait("IPv4", "true")] public void AcceptAsync_IpV4_Success() { Assert.True(Capability.IPv4Support()); AutoResetEvent completed = new AutoResetEvent(false); AutoResetEvent completedClient = new AutoResetEvent(false); using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = sock.BindToAnonymousPort(IPAddress.Loopback); sock.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnAcceptCompleted; args.UserToken = completed; Assert.True(sock.AcceptAsync(args)); _log.WriteLine("IPv4 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs(); argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, port); argsClient.Completed += OnConnectCompleted; argsClient.UserToken = completedClient; client.ConnectAsync(argsClient); _log.WriteLine("IPv4 Client: Connecting."); Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection"); Assert.Equal<SocketError>(SocketError.Success, args.SocketError); Assert.NotNull(args.AcceptSocket); Assert.True(args.AcceptSocket.Connected, "IPv4 Accept Socket was not connected"); Assert.NotNull(args.AcceptSocket.RemoteEndPoint); Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint); } } } [Fact] [Trait("IPv6", "true")] public void AcceptAsync_IPv6_Success() { Assert.True(Capability.IPv6Support()); AutoResetEvent completed = new AutoResetEvent(false); AutoResetEvent completedClient = new AutoResetEvent(false); using (Socket sock = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { int port = sock.BindToAnonymousPort(IPAddress.IPv6Loopback); sock.Listen(1); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.Completed += OnAcceptCompleted; args.UserToken = completed; Assert.True(sock.AcceptAsync(args)); _log.WriteLine("IPv6 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { SocketAsyncEventArgs argsClient = new SocketAsyncEventArgs(); argsClient.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, port); argsClient.Completed += OnConnectCompleted; argsClient.UserToken = completedClient; client.ConnectAsync(argsClient); _log.WriteLine("IPv6 Client: Connecting."); Assert.True(completed.WaitOne(5000), "IPv6: Timed out while waiting for connection"); Assert.Equal<SocketError>(SocketError.Success, args.SocketError); Assert.NotNull(args.AcceptSocket); Assert.True(args.AcceptSocket.Connected, "IPv6 Accept Socket was not connected"); Assert.NotNull(args.AcceptSocket.RemoteEndPoint); Assert.Equal(client.LocalEndPoint, args.AcceptSocket.RemoteEndPoint); } } } [Fact] [PlatformSpecific(PlatformID.Windows)] public void AcceptAsync_WithReceiveBuffer_Success() { Assert.True(Capability.IPv4Support()); AutoResetEvent accepted = new AutoResetEvent(false); using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = server.BindToAnonymousPort(IPAddress.Loopback); server.Listen(1); const int acceptBufferOverheadSize = 288; // see https://msdn.microsoft.com/en-us/library/system.net.sockets.socket.acceptasync(v=vs.110).aspx const int acceptBufferDataSize = 256; const int acceptBufferSize = acceptBufferOverheadSize + acceptBufferDataSize; byte[] sendBuffer = new byte[acceptBufferDataSize]; new Random().NextBytes(sendBuffer); SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs(); acceptArgs.Completed += OnAcceptCompleted; acceptArgs.UserToken = accepted; acceptArgs.SetBuffer(new byte[acceptBufferSize], 0, acceptBufferSize); Assert.True(server.AcceptAsync(acceptArgs)); _log.WriteLine("IPv4 Server: Waiting for clients."); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { client.Connect(IPAddress.Loopback, port); client.Send(sendBuffer); client.Shutdown(SocketShutdown.Both); } Assert.True( accepted.WaitOne(Configuration.PassingTestTimeout), "Test completed in alotted time"); Assert.Equal( SocketError.Success, acceptArgs.SocketError); Assert.Equal( acceptBufferDataSize, acceptArgs.BytesTransferred); Assert.Equal( new ArraySegment<byte>(sendBuffer), new ArraySegment<byte>(acceptArgs.Buffer, 0, acceptArgs.BytesTransferred)); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void AcceptAsync_WithReceiveBuffer_Failure() { // // Unix platforms don't yet support receiving data with AcceptAsync. // Assert.True(Capability.IPv4Support()); using (Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { int port = server.BindToAnonymousPort(IPAddress.Loopback); server.Listen(1); SocketAsyncEventArgs acceptArgs = new SocketAsyncEventArgs(); acceptArgs.Completed += OnAcceptCompleted; acceptArgs.UserToken = new ManualResetEvent(false); byte[] buffer = new byte[1024]; acceptArgs.SetBuffer(buffer, 0, buffer.Length); Assert.Throws<PlatformNotSupportedException>(() => server.AcceptAsync(acceptArgs)); } } #region GC Finalizer test // This test assumes sequential execution of tests and that it is going to be executed after other tests // that used Sockets. [Fact] public void TestFinalizers() { // Making several passes through the FReachable list. for (int i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } } #endregion } }
// // Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.LayoutRenderers { using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using System.Xml; using Internal.Fakeables; using NLog.Config; using NLog.Internal; using NLog.Targets; /// <summary> /// XML event description compatible with log4j, Chainsaw and NLogViewer. /// </summary> [LayoutRenderer("log4jxmlevent")] public class Log4JXmlEventLayoutRenderer : LayoutRenderer, IUsesStackTrace { private static readonly DateTime log4jDateBase = new DateTime(1970, 1, 1); private static readonly string dummyNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid(); private static readonly string dummyNLogNamespace = "http://nlog-project.org/dummynamespace/" + Guid.NewGuid(); /// <summary> /// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class. /// </summary> public Log4JXmlEventLayoutRenderer() : this(AppDomainWrapper.CurrentDomain) { } /// <summary> /// Initializes a new instance of the <see cref="Log4JXmlEventLayoutRenderer" /> class. /// </summary> public Log4JXmlEventLayoutRenderer(IAppDomain appDomain) { this.IncludeNLogData = true; this.NdcItemSeparator = " "; #if SILVERLIGHT this.AppInfo = "Silverlight Application"; #elif __IOS__ this.AppInfo = "MonoTouch Application"; #else this.AppInfo = string.Format( CultureInfo.InvariantCulture, "{0}({1})", appDomain.FriendlyName, ThreadIDHelper.Instance.CurrentProcessID); #endif this.Parameters = new List<NLogViewerParameterInfo>(); } /// <summary> /// Gets or sets a value indicating whether to include NLog-specific extensions to log4j schema. /// </summary> /// <docgen category='Payload Options' order='10' /> [DefaultValue(true)] public bool IncludeNLogData { get; set; } /// <summary> /// Gets or sets a value indicating whether the XML should use spaces for indentation. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IndentXml { get; set; } /// <summary> /// Gets or sets the AppInfo field. By default it's the friendly name of the current AppDomain. /// </summary> /// <docgen category='Payload Options' order='10' /> public string AppInfo { get; set; } /// <summary> /// Gets or sets a value indicating whether to include call site (class and method name) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeCallSite { get; set; } /// <summary> /// Gets or sets a value indicating whether to include source info (file name and line number) in the information sent over the network. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeSourceInfo { get; set; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="MappedDiagnosticsContext"/> dictionary. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeMdc { get; set; } /// <summary> /// Gets or sets a value indicating whether to include contents of the <see cref="NestedDiagnosticsContext"/> stack. /// </summary> /// <docgen category='Payload Options' order='10' /> public bool IncludeNdc { get; set; } /// <summary> /// Gets or sets the NDC item separator. /// </summary> /// <docgen category='Payload Options' order='10' /> [DefaultValue(" ")] public string NdcItemSeparator { get; set; } /// <summary> /// Gets the level of stack trace information required by the implementing class. /// </summary> StackTraceUsage IUsesStackTrace.StackTraceUsage { get { if (this.IncludeSourceInfo) { return StackTraceUsage.Max; } if (this.IncludeCallSite) { return StackTraceUsage.WithoutSource; } return StackTraceUsage.None; } } internal IList<NLogViewerParameterInfo> Parameters { get; set; } internal void AppendToStringBuilder(StringBuilder sb, LogEventInfo logEvent) { this.Append(sb, logEvent); } /// <summary> /// Renders the XML logging event and appends it to the specified <see cref="StringBuilder" />. /// </summary> /// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param> /// <param name="logEvent">Logging event.</param> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { var settings = new XmlWriterSettings { Indent = this.IndentXml, ConformanceLevel = ConformanceLevel.Fragment, IndentChars = " ", }; var sb = new StringBuilder(); using (XmlWriter xtw = XmlWriter.Create(sb, settings)) { xtw.WriteStartElement("log4j", "event", dummyNamespace); xtw.WriteAttributeSafeString("xmlns", "nlog", null, dummyNLogNamespace); xtw.WriteAttributeSafeString("logger", logEvent.LoggerName); xtw.WriteAttributeSafeString("level", logEvent.Level.Name.ToUpper(CultureInfo.InvariantCulture)); xtw.WriteAttributeSafeString("timestamp", Convert.ToString((long)(logEvent.TimeStamp.ToUniversalTime() - log4jDateBase).TotalMilliseconds, CultureInfo.InvariantCulture)); xtw.WriteAttributeSafeString("thread", System.Threading.Thread.CurrentThread.ManagedThreadId.ToString(CultureInfo.InvariantCulture)); xtw.WriteElementSafeString("log4j", "message", dummyNamespace, logEvent.FormattedMessage); if (logEvent.Exception != null) { xtw.WriteElementSafeString("log4j", "throwable", dummyNamespace, logEvent.Exception.ToString()); } if (this.IncludeNdc) { xtw.WriteElementSafeString("log4j", "NDC", dummyNamespace, string.Join(this.NdcItemSeparator, NestedDiagnosticsContext.GetAllMessages())); } if (logEvent.Exception != null) { xtw.WriteStartElement("log4j", "throwable", dummyNamespace); xtw.WriteSafeCData(logEvent.Exception.ToString()); xtw.WriteEndElement(); } if (this.IncludeCallSite || this.IncludeSourceInfo) { System.Diagnostics.StackFrame frame = logEvent.UserStackFrame; if (frame != null) { MethodBase methodBase = frame.GetMethod(); Type type = methodBase.DeclaringType; xtw.WriteStartElement("log4j", "locationInfo", dummyNamespace); if (type != null) { xtw.WriteAttributeSafeString("class", type.FullName); } xtw.WriteAttributeSafeString("method", methodBase.ToString()); #if !SILVERLIGHT if (this.IncludeSourceInfo) { xtw.WriteAttributeSafeString("file", frame.GetFileName()); xtw.WriteAttributeSafeString("line", frame.GetFileLineNumber().ToString(CultureInfo.InvariantCulture)); } #endif xtw.WriteEndElement(); if (this.IncludeNLogData) { xtw.WriteElementSafeString("nlog", "eventSequenceNumber", dummyNLogNamespace, logEvent.SequenceID.ToString(CultureInfo.InvariantCulture)); xtw.WriteStartElement("nlog", "locationInfo", dummyNLogNamespace); if (type != null) { xtw.WriteAttributeSafeString("assembly", type.Assembly.FullName); } xtw.WriteEndElement(); xtw.WriteStartElement("nlog", "properties", dummyNLogNamespace); foreach (var contextProperty in logEvent.Properties) { xtw.WriteStartElement("nlog", "data", dummyNLogNamespace); xtw.WriteAttributeSafeString("name", Convert.ToString(contextProperty.Key, CultureInfo.InvariantCulture)); xtw.WriteAttributeSafeString("value", Convert.ToString(contextProperty.Value, CultureInfo.InvariantCulture)); xtw.WriteEndElement(); } xtw.WriteEndElement(); } } } xtw.WriteStartElement("log4j", "properties", dummyNamespace); if (this.IncludeMdc) { foreach (KeyValuePair<string, object> entry in MappedDiagnosticsContext.ThreadDictionary) { xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", entry.Key); xtw.WriteAttributeSafeString("value", String.Format(logEvent.FormatProvider, "{0}", entry.Value)); xtw.WriteEndElement(); } } foreach (NLogViewerParameterInfo parameter in this.Parameters) { xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", parameter.Name); xtw.WriteAttributeSafeString("value", parameter.Layout.Render(logEvent)); xtw.WriteEndElement(); } xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", "log4japp"); xtw.WriteAttributeSafeString("value", this.AppInfo); xtw.WriteEndElement(); xtw.WriteStartElement("log4j", "data", dummyNamespace); xtw.WriteAttributeSafeString("name", "log4jmachinename"); #if SILVERLIGHT xtw.WriteAttributeSafeString("value", "silverlight"); #else xtw.WriteAttributeSafeString("value", Environment.MachineName); #endif xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.WriteEndElement(); xtw.Flush(); // get rid of 'nlog' and 'log4j' namespace declarations sb.Replace(" xmlns:log4j=\"" + dummyNamespace + "\"", string.Empty); sb.Replace(" xmlns:nlog=\"" + dummyNLogNamespace + "\"", string.Empty); builder.Append(sb.ToString()); } } } }
using System; using Microsoft.SPOT; using Microsoft.SPOT.Presentation.Media; using Skewworks.NETMF; using Skewworks.NETMF.Controls; namespace Skewworks.Tinkr.Controls { [Serializable] public class Listview : Control { #region Variables private ListviewColumn[] _cols; private ListviewItem[] _items; private Font _header; private Font _item; private Color _headerC, _itemC, _selC, _selTextC; //TODO: check wat _colDown was intended to do //private int _colDown = -1; private int _rowDown = -1; private int _iSel = -1; private bool _bMoved; private int _scrollY; //private bool _continueScroll; //private int _asr; // Animated Scroll Remaining //private int _ass; // Animated Scroll Speed private int _autoW; // Automatic Column Width #endregion #region Constructors public Listview(string name, Font headerFont, Font itemFont, int x, int y, int width, int height) { Name = name; // ReSharper disable DoNotCallOverridableMethodsInConstructor X = x; Y = y; Width = width; Height = height; // ReSharper restore DoNotCallOverridableMethodsInConstructor _header = headerFont; _item = itemFont; UpdateColumns(); DefaultColors(); } public Listview(string name, Font headerFont, Font itemFont, int x, int y, int width, int height, string[] columns) { Name = name; // ReSharper disable DoNotCallOverridableMethodsInConstructor X = x; Y = y; Width = width; Height = height; // ReSharper restore DoNotCallOverridableMethodsInConstructor _header = headerFont; _item = itemFont; if (columns != null) { _cols = new ListviewColumn[columns.Length]; for (int i = 0; i < columns.Length; i++) _cols[i] = new ListviewColumn("column" + i, columns[i]); } UpdateColumns(); DefaultColors(); } public Listview(string name, Font headerFont, Font itemFont, int x, int y, int width, int height, ListviewColumn[] columns) { Name = name; // ReSharper disable DoNotCallOverridableMethodsInConstructor X = x; Y = y; Width = width; Height = height; // ReSharper restore DoNotCallOverridableMethodsInConstructor _header = headerFont; _item = itemFont; _cols = columns; UpdateColumns(); DefaultColors(); } #endregion #region Events public event OnSelectedIndexChanged SelectedIndexChanged; protected virtual void OnSelectedIndexChanged(object sender, int index) { if (SelectedIndexChanged != null) SelectedIndexChanged(sender, index); } #endregion #region Properties public ListviewColumn[] Columns { get { return _cols; } set { if (_cols == value) return; _cols = value; Invalidate(); } } public Color HeaderColor { get { return _headerC; } set { if (_headerC == value) return; _headerC = value; Invalidate(); } } public Font HeaderFont { get { return _header; } set { if (_header == value) return; _header = value; Invalidate(); } } public ListviewItem[] Items { get { return _items; } set { if (_items == value) return; _items = value; Invalidate(); } } public Color ItemColor { get { return _itemC; } set { if (_itemC == value) return; _itemC = value; Invalidate(); } } public Font ItemFont { get { return _item; } set { if (_item == value) return; _item = value; Invalidate(); } } public int SelectedIndex { get { return _iSel; } set { if (_iSel == value) return; _iSel = value; Invalidate(); } } public Color SelectionColor { get { return _selC; } set { if (_selC == value) return; _selC = value; Invalidate(); } } public Color SelectedTextColor { get { return _selTextC; } set { if (_selTextC == value) return; _selTextC = value; Invalidate(); } } #endregion #region Touch protected override void TouchDownMessage(object sender, point point, ref bool handled) { point.X -= Left; point.Y -= Top; if (_cols != null && point.Y < _header.Height + 9) { point.X--; for (int i = 0; i < _cols.Length; i++) { var bounds = new rect(_cols[i].X, 1, _cols[i].W, _header.Height + 8); if (bounds.Contains(point)) { //_colDown = i; return; } } //_colDown = -1; return; } _rowDown = (point.Y - 9 - _header.Height + _scrollY) / (_item.Height + 8); } protected override void TouchMoveMessage(object sender, point point, ref bool handled) { try { if (_items != null) { int diff = point.Y - LastTouch.Y; if (diff == 0 || !Touching || (diff < 10 && diff > -10)) { return; } int max = _items.Length*(_item.Height + 8) - (Height - 3 - (_header.Height + 9)); if (max <= 0) { return; } int ns = _scrollY - diff; if (ns < 0) { ns = 0; } else if (ns > max) { ns = max; } if (_scrollY != ns) { _scrollY = ns; Invalidate(); } LastTouch = point; _bMoved = true; } } finally { base.TouchMoveMessage(sender, point, ref handled); } } protected override void TouchUpMessage(object sender, point point, ref bool handled) { //_colDown = -1; point.X -= Left; point.Y -= Top; if (_items == null || _bMoved) { if (_bMoved) { _bMoved = false; Invalidate(); } _rowDown = -1; } else if (_rowDown != -1 && _iSel != _rowDown && (point.Y - 9 - _header.Height + _scrollY) / (_item.Height + 8) == _rowDown) { if (_rowDown < _items.Length) { _iSel = _rowDown; } else { _iSel = -1; } OnSelectedIndexChanged(this, _iSel); Invalidate(); } base.TouchUpMessage(sender, point, ref handled); } #endregion #region Public Methods public void AddColumn(ListviewColumn column) { if (_cols == null) { _cols = new[] { column }; } else { var tmp = new ListviewColumn[_cols.Length + 1]; Array.Copy(_cols, tmp, _cols.Length); tmp[tmp.Length - 1] = column; _cols = tmp; } UpdateColumns(); Invalidate(); } public void ClearColumns() { if (_cols != null) { _cols = null; UpdateColumns(); Invalidate(); } } public void RemoveColumn(ListviewColumn column) { if (_cols == null) return; for (int i = 0; i < _cols.Length; i++) { if (_cols[i] == column) { RemoveColumnAt(i); return; } } } public void RemoveColumnAt(int index) { if (_cols == null || index < 0 || index >= _cols.Length) return; if (_cols.Length == 1) { _cols = null; } else { var tmp = new ListviewColumn[_cols.Length - 1]; int c = 0; for (int i = 0; i < _cols.Length; i++) { if (i != index) tmp[c++] = _cols[i]; } _cols = tmp; } UpdateColumns(); Invalidate(); } public void AddLine(ListviewItem line) { if (_items == null) _items = new[] { line }; else { var tmp = new ListviewItem[_items.Length + 1]; Array.Copy(_items, tmp, _items.Length); tmp[tmp.Length - 1] = line; _items = tmp; } Invalidate(); } public void AddLines(ListviewItem[] lines) { if (lines == null) return; if (_items == null) _items = lines; else { var tmp = new ListviewItem[_items.Length + lines.Length]; Array.Copy(_items, tmp, _items.Length); Array.Copy(lines, 0, tmp, _items.Length, lines.Length); _items = tmp; } Invalidate(); } public void ClearLines() { _items = null; Invalidate(); } public void RemoveLine(ListviewItem line) { if (_items == null) return; for (int i = 0; i < _items.Length; i++) { if (_items[i] == line) { RemoveLineAt(i); return; } } } public void RemoveLineAt(int index) { if (_items == null || index < 0 || index >= _items.Length) return; if (_items.Length == 1) { _items = null; } else { var tmp = new ListviewItem[_items.Length - 1]; int c = 0; for (int i = 0; i < _items.Length; i++) { if (i != index) tmp[c++] = _items[i]; } _items = tmp; } Invalidate(); } #endregion #region GUI // ReSharper disable RedundantAssignment protected override void OnRender(int x, int y, int width, int height) // ReSharper restore RedundantAssignment { x = Left; y = Top; // Draw Background Core.Screen.DrawRectangle((Focused) ? Core.SystemColors.SelectionColor : Core.SystemColors.BorderColor, 1, Left, Top, Width - 1, Height - 1, 0, 0, Core.SystemColors.WindowColor, 0, 0, Core.SystemColors.WindowColor, 0, 0, 256); // Draw Drop Core.Screen.DrawLine(Colors.White, 1, x + Width - 1, y, x + Width - 1, y + Height - 1); Core.Screen.DrawLine(Colors.White, 1, x, y + Height - 1, x + Width - 1, y + Height - 1); // Draw Data height = _header.Height + 9; bool bOn = true; x++; y++; Core.Screen.DrawRectangle(0, 0, x, y, Width - 3, height, 0, 0, Core.SystemColors.ControlTop, x, y, Core.SystemColors.ControlBottom, x, y + 4, 256); Core.Screen.DrawLine(Core.SystemColors.BorderColor, 1, x, y + height, x + Width - 3, y + height); if (_cols != null) { // Columns for (int i = 0; i < _cols.Length; i++) { width = _cols[i].W; if (width == -1) width = _autoW; _cols[i].X = x; Core.Screen.DrawTextInRect(_cols[i].Text, x + 4, y + 4, width - 8, _header.Height, Bitmap.DT_TrimmingCharacterEllipsis, _headerC, _header); x += width; Core.Screen.DrawLine(Core.SystemColors.BorderColor, 1, x - 1, y + 1, x - 1, y + height - 2); } y += height + 1; // Items Core.ClipForControl(this, Left + 1, y, Width - 3, Height - height - 4); y -= _scrollY; height = _item.Height + 8; if (_items != null) { for (int i = 0; i < _items.Length; i++) { bOn = !bOn; x = Left + 1; if (y + height > 0) { if (_iSel == i) Core.Screen.DrawRectangle(0, 0, Left + 1, y, Width - 3, height, 0, 0, _selC, 0, 0, _selC, 0, 0, 256); else if (bOn) Core.Screen.DrawRectangle(0, 0, Left + 1, y, Width - 3, height, 0, 0, Colors.Ghost, 0, 0, Colors.Ghost, 0, 0, 256); if (_items[i].Values != null) { int c = (_items[i].Values.Length < _cols.Length) ? _items[i].Values.Length : _cols.Length; for (int j = 0; j < c; j++) { width = _cols[j].Width; if (width == -1) width = _autoW; Core.Screen.DrawTextInRect(_items[i].Values[j], x + 4, y + 4, width - 8, _item.Height, Bitmap.DT_TrimmingCharacterEllipsis, (i == _iSel) ? _selTextC : _itemC, _item); x += width; } } } y += height; if (y >= Top + Height - 2) break; } } } // Scroll if (_bMoved && _items != null) { Core.ClipForControl(this, Left, Top, Width, Height); int lineHeight = _item.Height + 8; int msa = (_items.Length * lineHeight) - (Height - _header.Height - 16); int iGripSize = (Height - _header.Height - 16) - (msa / lineHeight); if (iGripSize < 8) iGripSize = 8; int iOffset = Top + _header.Height + 14 + (int)(((Height - _header.Height - 16) - iGripSize) * (_scrollY / (float)msa)); Core.Screen.DrawRectangle(Colors.Black, 0, Left + Width - 7, iOffset, 4, iGripSize, 0, 0, 0, 0, 0, 0, 0, 0, 80); } } #endregion #region Private Methods //TODO: check what AnimateScroll was intended to do /*private void AnimateScroll() { while (_continueScroll && _scrollY != _asr) { if (!_continueScroll) { Invalidate(); break; } _scrollY += _ass; if (_ass > 0 && _scrollY > _asr) { _scrollY = _asr; _continueScroll = false; } else if (_ass < 0 && _scrollY < _asr) { _scrollY = _asr; _continueScroll = false; } Invalidate(); } }*/ private void DefaultColors() { _headerC = Core.SystemColors.FontColor; _itemC = Core.SystemColors.FontColor; _selC = Core.SystemColors.SelectionColor; _selTextC = Core.SystemColors.SelectedFontColor; } private void UpdateColumns() { if (_cols == null) return; int availW = Width - 3; int unsizedCols = 0; int i; // Check unsized columns for (i = 0; i < _cols.Length; i++) { if (_cols[i].Width < 1) unsizedCols++; else availW -= _cols[i].Width; } if (unsizedCols == 0) return; _autoW = availW / unsizedCols; if (_autoW < 10) _autoW = 10; } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using NUnit.Framework; namespace Azure.Data.Tables.Tests { public class TableEntityTests { private TableEntity emptyEntity = new TableEntity { { "My value was nulled!", null } }; private TableEntity fullEntity = new TableEntity("partition", "row") { { TableConstants.PropertyNames.Timestamp, default(DateTimeOffset) }, { "binary", new byte[] { 1, 2 }}, { "binarydata", new BinaryData( new byte[] { 1, 2 })}, { "boolean", true }, { "datetime", new DateTime() }, { "datetimeoffset", new DateTimeOffset() }, { "double", (double)2.0 }, { "guid", new Guid() }, { "int32", int.MaxValue }, { "int64", long.MaxValue }, { "string", "hello!" }}; private string nulledPropertyKey = "My value was nulled!"; private string nonexistentKey = "My value was never set!"; /// <summary> /// Validates the typed getters. /// </summary> [Test] public void ValidateDictionaryEntityGetTypes() { Assert.That(fullEntity.GetBinary("binary"), Is.InstanceOf(typeof(byte[]))); Assert.That(fullEntity.GetBinaryData("binarydata"), Is.InstanceOf(typeof(BinaryData))); Assert.That(fullEntity.GetBoolean("boolean"), Is.InstanceOf(typeof(bool?))); Assert.That(fullEntity.GetDateTime("datetime"), Is.InstanceOf(typeof(DateTime?))); Assert.That(fullEntity.GetDateTimeOffset("datetimeoffset"), Is.InstanceOf(typeof(DateTimeOffset?))); Assert.That(fullEntity.GetDouble("double"), Is.InstanceOf(typeof(double?))); Assert.That(fullEntity.GetGuid("guid"), Is.InstanceOf(typeof(Guid))); Assert.That(fullEntity.GetInt32("int32"), Is.InstanceOf(typeof(int?))); Assert.That(fullEntity.GetInt64("int64"), Is.InstanceOf(typeof(long?))); Assert.That(fullEntity.GetString("string"), Is.InstanceOf(typeof(string))); } /// <summary> /// Validates the typed getters throws InvalidOperationException when the retrieved value doesn't match the type. /// </summary> [Test] public void DictionaryEntityGetWrongTypesThrows() { Assert.That(() => fullEntity.GetBinary("boolean"), Throws.InstanceOf<InvalidOperationException>(), "GetBinary should validate that the value for the inputted key is a Binary."); Assert.That(() => fullEntity.GetBinaryData("boolean"), Throws.InstanceOf<InvalidOperationException>(), "GetBinary should validate that the value for the inputted key is a BinaryData."); Assert.That(() => fullEntity.GetBoolean("datetime"), Throws.InstanceOf<InvalidOperationException>(), "GetBoolean should validate that the value for the inputted key is a Boolean."); Assert.That(() => fullEntity.GetDateTime("double"), Throws.InstanceOf<InvalidOperationException>(), "GetDateTime should validate that the value for the inputted key is a DateTime."); Assert.That(() => fullEntity.GetDouble("guid"), Throws.InstanceOf<InvalidOperationException>(), "GetDouble should validate that the value for the inputted key is an Double."); Assert.That(() => fullEntity.GetGuid("int32"), Throws.InstanceOf<InvalidOperationException>(), "GetGuid should validate that the value for the inputted key is an Guid."); Assert.That(() => fullEntity.GetInt32("int64"), Throws.InstanceOf<InvalidOperationException>(), "GetInt32 should validate that the value for the inputted key is a Int32."); Assert.That(() => fullEntity.GetInt64("binary"), Throws.InstanceOf<InvalidOperationException>(), "GetInt64 should validate that the value for the inputted key is a Int64."); Assert.That(() => fullEntity.GetString("binary"), Throws.InstanceOf<InvalidOperationException>(), "GetString should validate that the value for the inputted key is a string."); } /// <summary> /// Validates typed getters for nonexistent properties. /// </summary> [Test] public void ValidateDictionaryEntityGetTypeForNonexistentProperties() { Assert.That(fullEntity.GetBinary(nonexistentKey), Is.Null); Assert.That(fullEntity.GetBinaryData(nonexistentKey), Is.Null); Assert.That(fullEntity.GetBoolean(nonexistentKey), Is.Null); Assert.That(fullEntity.GetDateTime(nonexistentKey), Is.Null); Assert.That(fullEntity.GetDateTimeOffset(nonexistentKey), Is.Null); Assert.That(fullEntity.GetDouble(nonexistentKey), Is.Null); Assert.That(fullEntity.GetGuid(nonexistentKey), Is.Null); Assert.That(fullEntity.GetInt32(nonexistentKey), Is.Null); Assert.That(fullEntity.GetInt64(nonexistentKey), Is.Null); Assert.That(fullEntity.GetString(nonexistentKey), Is.Null); } /// <summary> /// Validates typed getters for nulled properties. /// </summary> [Test] public void ValidateDictionaryEntityGetTypeForNulledProperties() { Assert.That(emptyEntity.GetBinary(nulledPropertyKey), Is.Null); Assert.That(emptyEntity.GetBoolean(nulledPropertyKey), Is.Null); Assert.That(emptyEntity.GetDateTime(nulledPropertyKey), Is.Null); Assert.That(emptyEntity.GetDateTimeOffset(nulledPropertyKey), Is.Null); Assert.That(emptyEntity.GetDouble(nulledPropertyKey), Is.Null); Assert.That(emptyEntity.GetGuid(nulledPropertyKey), Is.Null); Assert.That(emptyEntity.GetInt32(nulledPropertyKey), Is.Null); Assert.That(emptyEntity.GetInt64(nulledPropertyKey), Is.Null); Assert.That(emptyEntity.GetString(nulledPropertyKey), Is.Null); } /// <summary> /// Validates the typed getters. /// </summary> [Test] public void ValidateDictionaryEntityGetPropertiesWithIndexer() { Assert.That(fullEntity["binary"], Is.Not.Null); Assert.That(fullEntity["binary"], Is.InstanceOf(typeof(byte[]))); Assert.That(fullEntity["boolean"], Is.Not.Null); Assert.That(fullEntity["boolean"], Is.InstanceOf(typeof(bool?))); Assert.That(fullEntity["datetime"], Is.Not.Null); Assert.That(fullEntity["datetime"], Is.InstanceOf(typeof(DateTime?))); Assert.That(fullEntity["datetimeoffset"], Is.Not.Null); Assert.That(fullEntity["datetimeoffset"], Is.InstanceOf(typeof(DateTimeOffset?))); Assert.That(fullEntity["double"], Is.Not.Null); Assert.That(fullEntity["double"], Is.Not.Null); Assert.That(fullEntity["double"], Is.InstanceOf(typeof(double?))); Assert.That(fullEntity["guid"], Is.Not.Null); Assert.That(fullEntity["guid"], Is.InstanceOf(typeof(Guid))); Assert.That(fullEntity["int32"], Is.Not.Null); Assert.That(fullEntity["int32"], Is.InstanceOf(typeof(int?))); Assert.That(fullEntity["int64"], Is.Not.Null); Assert.That(fullEntity["int64"], Is.InstanceOf(typeof(long?))); Assert.That(fullEntity["string"], Is.Not.Null); Assert.That(fullEntity["string"], Is.InstanceOf(typeof(string))); // Timestamp property returned as object casted as DateTimeOffset? Assert.That(fullEntity.Timestamp, Is.Not.Null); Assert.That(fullEntity.Timestamp, Is.InstanceOf(typeof(DateTimeOffset?))); } /// <summary> /// Validates getting properties with the indexer that either don't exist or were set to null. /// </summary> [Test] public void DictionaryEntityGetNullOrNonexistentPropertiesWithIndexer() { var nonexistentKey = "I was never set!"; // Test getting nonexistent property works. Assert.That(emptyEntity[nonexistentKey], Is.Null); // Test getting a property that was set to null. Assert.That(emptyEntity[nulledPropertyKey], Is.Null); } /// <summary> /// Validates setting values makes correct changes. /// </summary> [Test] public void ValidateDictionaryEntitySetType() { var entity = new TableEntity("partition", "row") { { "exampleBool", true } }; // Test setting an existing property with the same type works. entity["exampleBool"] = false; Assert.That(entity.GetBoolean("exampleBool").Value, Is.False); } /// <summary> /// Validates setting required and additional properties involving null. /// </summary> [Test] public void DictionaryEntitySetNullProperties() { var entity = new TableEntity("partition", "row"); // Test setting new property works. string stringKey = "key :D"; string stringValue = "value D:"; Assert.That(entity[stringKey], Is.Null); entity[stringKey] = stringValue; Assert.That(entity[stringKey], Is.EqualTo(stringValue)); // Test setting existing value to null. entity[stringKey] = null; Assert.That(entity[stringKey], Is.Null); // Test setting existing null value to a non-null value. entity[stringKey] = stringValue; Assert.That(entity[stringKey], Is.EqualTo(stringValue)); } [Test] public void TypeCoercionForNumericTypes() { var entity = new TableEntity("partition", "row"); // Initialize a property to an int value entity["Foo"] = 0; Assert.That(entity["Foo"] is int); Assert.That(entity["Foo"], Is.EqualTo(0)); // Try to change the value to a double entity["Foo"] = 1.1; Assert.That(entity["Foo"] is double); Assert.That(entity["Foo"], Is.EqualTo(1.1)); // Change to a double compatible int entity["Foo"] = 0; Assert.That(entity["Foo"] is double); Assert.That(entity["Foo"], Is.EqualTo(0)); // Change to a double compatible int entity["Foo"] = 1; Assert.That(entity["Foo"] is double); Assert.That(entity["Foo"], Is.EqualTo(1)); // Initialize a property to an int value entity["Foo2"] = 0; Assert.That(entity["Foo2"] is int); Assert.That(entity["Foo2"], Is.EqualTo(0)); // Change to a long entity["Foo2"] = 5L; Assert.That(entity["Foo2"] is long); Assert.That(entity["Foo2"], Is.EqualTo(5L)); // Change to a long compatible int entity["Foo2"] = 0; Assert.That(entity["Foo2"] is long); Assert.That(entity["Foo2"], Is.EqualTo(0)); // Initialize a property to an int value entity["Foo3"] = 0; Assert.That(entity["Foo3"] is int); Assert.That(entity["Foo3"], Is.EqualTo(0)); // Validate invalid conversions entity["Foo3"] = "fail"; Assert.That(entity["Foo3"], Is.EqualTo("fail")); Assert.That(entity["Foo3"] is string); entity["Foo3"] = new byte[] { 0x02 }; Assert.That(entity["Foo3"], Is.EqualTo(new byte[] { 0x02 })); Assert.That(entity["Foo3"] is byte[]); entity["Foo3"] = false; Assert.That(entity["Foo3"], Is.EqualTo(false)); Assert.That(entity["Foo3"] is bool); var guid = Guid.NewGuid(); entity["Foo3"] = guid; Assert.That(entity["Foo3"], Is.EqualTo(guid)); Assert.That(entity["Foo3"] is Guid); var now = DateTime.Now; entity["Foo3"] = now; Assert.That(entity["Foo3"], Is.EqualTo(now)); Assert.That(entity["Foo3"] is DateTime); } [Test] public void TypeCoercionForDateTimeTypes() { var entity = new TableEntity("partition", "row"); var offsetNow = DateTimeOffset.UtcNow; var dateNow = offsetNow.UtcDateTime; // Initialize a property to an DateTimeOffset value entity["DTOffset"] = offsetNow; Assert.That(entity["DTOffset"] is DateTimeOffset); Assert.That(entity["DTOffset"], Is.EqualTo(offsetNow)); Assert.That(entity.GetDateTimeOffset("DTOffset"), Is.EqualTo(offsetNow)); Assert.That(entity.GetDateTime("DTOffset"), Is.EqualTo(dateNow)); // Initialize a property to an DateTime value entity["DT"] = dateNow; Assert.AreEqual(typeof(DateTime), entity["DT"].GetType()); DateTimeOffset dtoffset = (DateTime)entity["DT"]; Assert.That(entity["DT"], Is.EqualTo(dateNow)); Assert.That(entity.GetDateTime("DT"), Is.EqualTo(dateNow)); Assert.That(entity.GetDateTimeOffset("DT"), Is.EqualTo(offsetNow)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Diagnostics; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; namespace System.IO { /// <summary>Provides an implementation of a file stream for Unix files.</summary> internal sealed partial class UnixFileStream : FileStreamBase { /// <summary>The file descriptor wrapped in a file handle.</summary> private readonly SafeFileHandle _fileHandle; /// <summary>The path to the opened file.</summary> private readonly string _path; /// <summary>File mode.</summary> private readonly FileMode _mode; /// <summary>Whether the file is opened for reading, writing, or both.</summary> private readonly FileAccess _access; /// <summary>Advanced options requested when opening the file.</summary> private readonly FileOptions _options; /// <summary>If the file was opened with FileMode.Append, the length of the file when opened; otherwise, -1.</summary> private readonly long _appendStart = -1; /// <summary>Whether asynchronous read/write/flush operations should be performed using async I/O.</summary> private readonly bool _useAsyncIO; /// <summary>The length of the _buffer.</summary> private readonly int _bufferLength; /// <summary>Lazily-initialized buffer data from Write waiting to be written to the underlying handle, or data read from the underlying handle and waiting to be Read.</summary> private byte[] _buffer; /// <summary>The number of valid bytes in _buffer.</summary> private int _readLength; /// <summary>The next available byte to be read from the _buffer.</summary> private int _readPos; /// <summary>The next location in which a write should occur to the buffer.</summary> private int _writePos; /// <summary>Lazily-initialized value for whether the file supports seeking.</summary> private bool? _canSeek; /// <summary>Whether the file stream's handle has been exposed.</summary> private bool _exposedHandle; /// <summary> /// Currently cached position in the stream. This should always mirror the underlying file descriptor's actual position, /// and should only ever be out of sync if another stream with access to this same file descriptor manipulates it, at which /// point we attempt to error out. /// </summary> private long _filePosition; /// <summary>Initializes a stream for reading or writing a Unix file.</summary> /// <param name="path">The path to the file.</param> /// <param name="mode">How the file should be opened.</param> /// <param name="access">Whether the file will be read, written, or both.</param> /// <param name="share">What other access to the file should be allowed. This is currently ignored.</param> /// <param name="bufferSize">The size of the buffer to use when buffering.</param> /// <param name="options">Additional options for working with the file.</param> internal UnixFileStream(String path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options, FileStream parent) : base(parent) { // FileStream performs most of the general argument validation. We can assume here that the arguments // are all checked and consistent (e.g. non-null-or-empty path; valid enums in mode, access, share, and options; etc.) // Store the arguments _path = path; _access = access; _mode = mode; _options = options; _bufferLength = bufferSize; _useAsyncIO = (options & FileOptions.Asynchronous) != 0; // Translate the arguments into arguments for an open call Interop.libc.OpenFlags openFlags = PreOpenConfigurationFromOptions(mode, access, options); // FileShare currently ignored Interop.libc.Permissions openPermissions = Interop.libc.Permissions.S_IRWXU; // creator has read/write/execute permissions; no permissions for anyone else // Open the file and store the safe handle. Subsequent code in this method expects the safe handle to be initialized. _fileHandle = SafeFileHandle.Open(path, openFlags, (int)openPermissions); _fileHandle.IsAsync = _useAsyncIO; // Lock the file if requested via FileShare. This is only advisory locking. FileShare.None implies an exclusive // lock on the file and all other modes use a shared lock. While this is not as granular as Windows, not mandatory, // and not atomic with file opening, it's better than nothing. try { Interop.libc.LockOperations lockOperation = (share == FileShare.None) ? Interop.libc.LockOperations.LOCK_EX : Interop.libc.LockOperations.LOCK_SH; SysCall<Interop.libc.LockOperations, int>((fd, op, _) => Interop.libc.flock(fd, op), lockOperation | Interop.libc.LockOperations.LOCK_NB); } catch { _fileHandle.Dispose(); throw; } // Perform additional configurations on the stream based on the provided FileOptions PostOpenConfigureStreamFromOptions(); // Jump to the end of the file if opened as Append. if (_mode == FileMode.Append) { _appendStart = SeekCore(0, SeekOrigin.End); } } /// <summary>Performs additional configuration of the opened stream based on provided options.</summary> partial void PostOpenConfigureStreamFromOptions(); /// <summary>Initializes a stream from an already open file handle (file descriptor).</summary> /// <param name="handle">The handle to the file.</param> /// <param name="access">Whether the file will be read, written, or both.</param> /// <param name="bufferSize">The size of the buffer to use when buffering.</param> /// <param name="useAsyncIO">Whether access to the stream is performed asynchronously.</param> internal UnixFileStream(SafeFileHandle handle, FileAccess access, int bufferSize, bool useAsyncIO, FileStream parent) : base(parent) { // Make sure the handle is open if (handle.IsInvalid) throw new ArgumentException(SR.Arg_InvalidHandle, "handle"); if (handle.IsClosed) throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); if (access < FileAccess.Read || access > FileAccess.ReadWrite) throw new ArgumentOutOfRangeException("access", SR.ArgumentOutOfRange_Enum); if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", SR.ArgumentOutOfRange_NeedNonNegNum); if (handle.IsAsync.HasValue && useAsyncIO != handle.IsAsync.Value) throw new ArgumentException(SR.Arg_HandleNotAsync, "handle"); _fileHandle = handle; _access = access; _exposedHandle = true; _bufferLength = bufferSize; _useAsyncIO = useAsyncIO; if (CanSeek) { SeekCore(0, SeekOrigin.Current); } } /// <summary>Gets the array used for buffering reading and writing. If the array hasn't been allocated, this will lazily allocate it.</summary> /// <returns>The buffer.</returns> private byte[] GetBuffer() { Debug.Assert(_buffer == null || _buffer.Length == _bufferLength); return _buffer ?? (_buffer = new byte[_bufferLength]); } /// <summary>Translates the FileMode, FileAccess, and FileOptions values into flags to be passed when opening the file.</summary> /// <param name="mode">The FileMode provided to the stream's constructor.</param> /// <param name="access">The FileAccess provided to the stream's constructor</param> /// <param name="options">The FileOptions provided to the stream's constructor</param> /// <returns>The flags value to be passed to the open system call.</returns> private static Interop.libc.OpenFlags PreOpenConfigurationFromOptions(FileMode mode, FileAccess access, FileOptions options) { // Translate FileMode. Most of the values map cleanly to one or more options for open. Interop.libc.OpenFlags flags = default(Interop.libc.OpenFlags); switch (mode) { default: case FileMode.Open: // Open maps to the default behavior for open(...). No flags needed. break; case FileMode.Append: // Append is the same as OpenOrCreate, except that we'll also separately jump to the end later case FileMode.OpenOrCreate: flags |= Interop.libc.OpenFlags.O_CREAT; break; case FileMode.Create: flags |= (Interop.libc.OpenFlags.O_CREAT | Interop.libc.OpenFlags.O_TRUNC); break; case FileMode.CreateNew: flags |= (Interop.libc.OpenFlags.O_CREAT | Interop.libc.OpenFlags.O_EXCL); break; case FileMode.Truncate: flags |= Interop.libc.OpenFlags.O_TRUNC; break; } // Translate FileAccess. All possible values map cleanly to corresponding values for open. switch (access) { case FileAccess.Read: flags |= Interop.libc.OpenFlags.O_RDONLY; break; case FileAccess.ReadWrite: flags |= Interop.libc.OpenFlags.O_RDWR; break; case FileAccess.Write: flags |= Interop.libc.OpenFlags.O_WRONLY; break; } // Translate some FileOptions; some just aren't supported, and others will be handled after calling open. switch (options) { case FileOptions.Asynchronous: // Handled in ctor, setting _useAsync and SafeFileHandle.IsAsync to true case FileOptions.DeleteOnClose: // DeleteOnClose doesn't have a Unix equivalent, but we approximate it in Dispose case FileOptions.Encrypted: // Encrypted does not have an equivalent on Unix and is ignored. case FileOptions.RandomAccess: // Implemented after open if posix_fadvise is available case FileOptions.SequentialScan: // Implemented after open if posix_fadvise is available break; case FileOptions.WriteThrough: flags |= Interop.libc.OpenFlags.O_SYNC; break; } return flags; } /// <summary>Gets a value indicating whether the current stream supports reading.</summary> public override bool CanRead { [Pure] get { return !_fileHandle.IsClosed && (_access & FileAccess.Read) != 0; } } /// <summary>Gets a value indicating whether the current stream supports writing.</summary> public override bool CanWrite { [Pure] get { return !_fileHandle.IsClosed && (_access & FileAccess.Write) != 0; } } /// <summary>Gets a value indicating whether the current stream supports seeking.</summary> public override bool CanSeek { get { if (_fileHandle.IsClosed) { return false; } if (!_canSeek.HasValue) { // Lazily-initialize whether we're able to seek, tested by seeking to our current location. _canSeek = SysCall<int, int>((fd, _, __) => Interop.libc.lseek(fd, 0, Interop.libc.SeekWhence.SEEK_CUR), throwOnError: false) >= 0; } return _canSeek.Value; } } /// <summary>Gets a value indicating whether the stream was opened for I/O to be performed synchronously or asynchronously.</summary> public override bool IsAsync { get { return _useAsyncIO; } } /// <summary>Gets the length of the stream in bytes.</summary> public override long Length { get { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } // Get the length of the file as reported by the OS long length = SysCall<int, int>((fd, _, __) => { Interop.Sys.FileStatus status; int result = Interop.Sys.FStat(fd, out status); return result >= 0 ? status.Size : result; }); // But we may have buffered some data to be written that puts our length // beyond what the OS is aware of. Update accordingly. if (_writePos > 0 && _filePosition + _writePos > length) { length = _writePos + _filePosition; } return length; } } /// <summary>Gets the path that was passed to the constructor.</summary> public override String Name { get { return _path ?? SR.IO_UnknownFileName; } } /// <summary>Gets the SafeFileHandle for the file descriptor encapsulated in this stream.</summary> public override SafeFileHandle SafeFileHandle { get { _parent.Flush(); _exposedHandle = true; return _fileHandle; } } /// <summary>Gets or sets the position within the current stream</summary> public override long Position { get { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } VerifyBufferInvariants(); VerifyOSHandlePosition(); // We may have read data into our buffer from the handle, such that the handle position // is artificially further along than the consumer's view of the stream's position. // Thus, when reading, our position is really starting from the handle position negatively // offset by the number of bytes in the buffer and positively offset by the number of // bytes into that buffer we've read. When writing, both the read length and position // must be zero, and our position is just the handle position offset positive by how many // bytes we've written into the buffer. return (_filePosition - _readLength) + _readPos + _writePos; } set { if (value < 0) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NeedNonNegNum); } _parent.Seek(value, SeekOrigin.Begin); } } /// <summary>Verifies that state relating to the read/write buffer is consistent.</summary> [Conditional("DEBUG")] private void VerifyBufferInvariants() { // Read buffer values must be in range: 0 <= _bufferReadPos <= _bufferReadLength <= _bufferLength Debug.Assert(0 <= _readPos && _readPos <= _readLength && _readLength <= _bufferLength); // Write buffer values must be in range: 0 <= _bufferWritePos <= _bufferLength Debug.Assert(0 <= _writePos && _writePos <= _bufferLength); // Read buffering and write buffering can't both be active Debug.Assert((_readPos == 0 && _readLength == 0) || _writePos == 0); } /// <summary> /// Verify that the actual position of the OS's handle equals what we expect it to. /// This will fail if someone else moved the UnixFileStream's handle or if /// our position updating code is incorrect. /// </summary> private void VerifyOSHandlePosition() { bool verifyPosition = _exposedHandle; // in release, only verify if we've given out the handle such that someone else could be manipulating it #if DEBUG verifyPosition = true; // in debug, always make sure our position matches what the OS says it should be #endif if (verifyPosition && _parent.CanSeek) { long oldPos = _filePosition; // SeekCore will override the current _position, so save it now long curPos = SeekCore(0, SeekOrigin.Current); if (oldPos != curPos) { // For reads, this is non-fatal but we still could have returned corrupted // data in some cases, so discard the internal buffer. For writes, // this is a problem; discard the buffer and error out. _readPos = _readLength = 0; if (_writePos > 0) { _writePos = 0; throw new IOException(SR.IO_FileStreamHandlePosition); } } } } /// <summary>Releases the unmanaged resources used by the stream.</summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected override void Dispose(bool disposing) { // Flush and close the file try { if (_fileHandle != null && !_fileHandle.IsClosed) { FlushWriteBuffer(); // Unix doesn't directly support DeleteOnClose but we can mimick it. if ((_options & FileOptions.DeleteOnClose) != 0) { // Since we still have the file open, this will end up deleting // it (assuming we're the only link to it) once it's closed. Interop.libc.unlink(_path); // ignore any error } } } finally { if (_fileHandle != null && !_fileHandle.IsClosed) { _fileHandle.Dispose(); } base.Dispose(disposing); } } /// <summary>Finalize the stream.</summary> ~UnixFileStream() { Dispose(false); } /// <summary>Clears buffers for this stream and causes any buffered data to be written to the file.</summary> public override void Flush() { _parent.Flush(flushToDisk: false); } /// <summary> /// Clears buffers for this stream, and if <param name="flushToDisk"/> is true, /// causes any buffered data to be written to the file. /// </summary> public override void Flush(Boolean flushToDisk) { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } FlushInternalBuffer(); if (flushToDisk && _parent.CanWrite) { FlushOSBuffer(); } } /// <summary>Flushes the OS buffer. This does not flush the internal read/write buffer.</summary> private void FlushOSBuffer() { SysCall<int, int>((fd, _, __) => Interop.libc.fsync(fd)); } /// <summary> /// Flushes the internal read/write buffer for this stream. If write data has been buffered, /// that data is written out to the underlying file. Or if data has been buffered for /// reading from the stream, the data is dumped and our position in the underlying file /// is rewound as necessary. This does not flush the OS buffer. /// </summary> private void FlushInternalBuffer() { VerifyBufferInvariants(); if (_writePos > 0) { FlushWriteBuffer(); } else if (_readPos < _readLength && _parent.CanSeek) { FlushReadBuffer(); } } /// <summary>Writes any data in the write buffer to the underlying stream and resets the buffer.</summary> private void FlushWriteBuffer() { VerifyBufferInvariants(); if (_writePos > 0) { WriteCore(GetBuffer(), 0, _writePos); _writePos = 0; } } /// <summary>Dumps any read data in the buffer and rewinds our position in the stream, accordingly, as necessary.</summary> private void FlushReadBuffer() { VerifyBufferInvariants(); int rewind = _readPos - _readLength; if (rewind != 0) { SeekCore(rewind, SeekOrigin.Current); } _readPos = _readLength = 0; } /// <summary>Asynchronously clears all buffers for this stream, causing any buffered data to be written to the underlying device.</summary> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous flush operation.</returns> public override Task FlushAsync(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled(cancellationToken); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } // As with Win32FileStream, flush the buffers synchronously to avoid race conditions. try { FlushInternalBuffer(); } catch (Exception e) { return Task.FromException(e); } // We then separately flush to disk asynchronously. This is only // necessary if we support writing; otherwise, we're done. if (_parent.CanWrite) { return Task.Factory.StartNew( state => ((UnixFileStream)state).FlushOSBuffer(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { return Task.CompletedTask; } } /// <summary>Sets the length of this stream to the given value.</summary> /// <param name="value">The new length of the stream.</param> public override void SetLength(long value) { if (value < 0) { throw new ArgumentOutOfRangeException("value", SR.ArgumentOutOfRange_NeedNonNegNum); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } if (!_parent.CanWrite) { throw __Error.GetWriteNotSupported(); } FlushInternalBuffer(); if (_appendStart != -1 && value < _appendStart) { throw new IOException(SR.IO_SetLengthAppendTruncate); } long origPos = _filePosition; VerifyOSHandlePosition(); if (_filePosition != value) { SeekCore(value, SeekOrigin.Begin); } SysCall<long, int>((fd, length, _) => Interop.libc.ftruncate(fd, length), value); // Return file pointer to where it was before setting length if (origPos != value) { if (origPos < value) { SeekCore(origPos, SeekOrigin.Begin); } else { SeekCore(0, SeekOrigin.End); } } } /// <summary>Reads a block of bytes from the stream and writes the data in a given buffer.</summary> /// <param name="array"> /// When this method returns, contains the specified byte array with the values between offset and /// (offset + count - 1) replaced by the bytes read from the current source. /// </param> /// <param name="offset">The byte offset in array at which the read bytes will be placed.</param> /// <param name="count">The maximum number of bytes to read. </param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> public override int Read([In, Out] byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); PrepareForReading(); // Are there any bytes available in the read buffer? If yes, // we can just return from the buffer. If the buffer is empty // or has no more available data in it, we can either refill it // (and then read from the buffer into the user's buffer) or // we can just go directly into the user's buffer, if they asked // for more data than we'd otherwise buffer. int numBytesAvailable = _readLength - _readPos; if (numBytesAvailable == 0) { // If we're not able to seek, then we're not able to rewind the stream (i.e. flushing // a read buffer), in which case we don't want to use a read buffer. Similarly, if // the user has asked for more data than we can buffer, we also want to skip the buffer. if (!_parent.CanSeek || (count >= _bufferLength)) { // Read directly into the user's buffer int bytesRead = ReadCore(array, offset, count); _readPos = _readLength = 0; // reset after the read just in case read experiences an exception return bytesRead; } else { // Read into our buffer. _readLength = numBytesAvailable = ReadCore(GetBuffer(), 0, _bufferLength); _readPos = 0; if (numBytesAvailable == 0) { return 0; } } } // Now that we know there's data in the buffer, read from it into // the user's buffer. int bytesToRead = Math.Min(numBytesAvailable, count); Buffer.BlockCopy(GetBuffer(), _readPos, array, offset, bytesToRead); _readPos += bytesToRead; return bytesToRead; } /// <summary>Unbuffered, reads a block of bytes from the stream and writes the data in a given buffer.</summary> /// <param name="array"> /// When this method returns, contains the specified byte array with the values between offset and /// (offset + count - 1) replaced by the bytes read from the current source. /// </param> /// <param name="offset">The byte offset in array at which the read bytes will be placed.</param> /// <param name="count">The maximum number of bytes to read. </param> /// <returns> /// The total number of bytes read into the buffer. This might be less than the number of bytes requested /// if that number of bytes are not currently available, or zero if the end of the stream is reached. /// </returns> private unsafe int ReadCore(byte[] array, int offset, int count) { FlushWriteBuffer(); // we're about to read; dump the write buffer VerifyOSHandlePosition(); int bytesRead; fixed (byte* bufPtr = array) { bytesRead = (int)SysCall((fd, ptr, len) => { long result = (long)Interop.libc.read(fd, (byte*)ptr, (IntPtr)len); Debug.Assert(result <= len); return result; }, (IntPtr)(bufPtr + offset), count); } _filePosition += bytesRead; return bytesRead; } /// <summary> /// Asynchronously reads a sequence of bytes from the current stream and advances /// the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">The buffer to write the data into.</param> /// <param name="offset">The byte offset in buffer at which to begin writing data from the stream.</param> /// <param name="count">The maximum number of bytes to read.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous read operation.</returns> public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled<int>(cancellationToken); if (_fileHandle.IsClosed) throw __Error.GetFileNotOpen(); if (_useAsyncIO) { // TODO: Use async I/O instead of sync I/O } return base.ReadAsync(buffer, offset, count, cancellationToken); } /// <summary> /// Reads a byte from the stream and advances the position within the stream /// by one byte, or returns -1 if at the end of the stream. /// </summary> /// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns> public override int ReadByte() { PrepareForReading(); byte[] buffer = GetBuffer(); if (_readPos == _readLength) { _readLength = ReadCore(buffer, 0, _bufferLength); _readPos = 0; if (_readLength == 0) { return -1; } } return buffer[_readPos++]; } /// <summary>Validates that we're ready to read from the stream.</summary> private void PrepareForReading() { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (_readLength == 0 && !_parent.CanRead) { throw __Error.GetReadNotSupported(); } VerifyBufferInvariants(); } /// <summary>Writes a block of bytes to the file stream.</summary> /// <param name="array">The buffer containing data to write to the stream.</param> /// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> public override void Write(byte[] array, int offset, int count) { ValidateReadWriteArgs(array, offset, count); PrepareForWriting(); // If no data is being written, nothing more to do. if (count == 0) { return; } // If there's already data in our write buffer, then we need to go through // our buffer to ensure data isn't corrupted. if (_writePos > 0) { // If there's space remaining in the buffer, then copy as much as // we can from the user's buffer into ours. int spaceRemaining = _bufferLength - _writePos; if (spaceRemaining > 0) { int bytesToCopy = Math.Min(spaceRemaining, count); Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, bytesToCopy); _writePos += bytesToCopy; // If we've successfully copied all of the user's data, we're done. if (count == bytesToCopy) { return; } // Otherwise, keep track of how much more data needs to be handled. offset += bytesToCopy; count -= bytesToCopy; } // At this point, the buffer is full, so flush it out. FlushWriteBuffer(); } // Our buffer is now empty. If using the buffer would slow things down (because // the user's looking to write more data than we can store in the buffer), // skip the buffer. Otherwise, put the remaining data into the buffer. Debug.Assert(_writePos == 0); if (count >= _bufferLength) { WriteCore(array, offset, count); } else { Buffer.BlockCopy(array, offset, GetBuffer(), _writePos, count); _writePos = count; } } /// <summary>Unbuffered, writes a block of bytes to the file stream.</summary> /// <param name="array">The buffer containing data to write to the stream.</param> /// <param name="offset">The zero-based byte offset in array from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> private unsafe void WriteCore(byte[] array, int offset, int count) { VerifyOSHandlePosition(); fixed (byte* bufPtr = array) { while (count > 0) { int bytesWritten = (int)SysCall((fd, ptr, len) => { long result = (long)Interop.libc.write(fd, (byte*)ptr, (IntPtr)len); Debug.Assert(result <= len); return result; }, (IntPtr)(bufPtr + offset), count); _filePosition += bytesWritten; count -= bytesWritten; offset += bytesWritten; } } } /// <summary> /// Asynchronously writes a sequence of bytes to the current stream, advances /// the current position within this stream by the number of bytes written, and /// monitors cancellation requests. /// </summary> /// <param name="buffer">The buffer to write data from.</param> /// <param name="offset">The zero-based byte offset in buffer from which to begin copying bytes to the stream.</param> /// <param name="count">The maximum number of bytes to write.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous write operation.</returns> public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (_fileHandle.IsClosed) throw __Error.GetFileNotOpen(); if (_useAsyncIO) { // TODO: Use async I/O instead of sync I/O } return base.WriteAsync(buffer, offset, count, cancellationToken); } /// <summary> /// Writes a byte to the current position in the stream and advances the position /// within the stream by one byte. /// </summary> /// <param name="value">The byte to write to the stream.</param> public override void WriteByte(byte value) // avoids an array allocation in the base implementation { PrepareForWriting(); // Flush the write buffer if it's full if (_writePos == _bufferLength) { FlushWriteBuffer(); } // We now have space in the buffer. Store the byte. GetBuffer()[_writePos++] = value; } /// <summary> /// Validates that we're ready to write to the stream, /// including flushing a read buffer if necessary. /// </summary> private void PrepareForWriting() { if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } // Make sure we're good to write. We only need to do this if there's nothing already // in our write buffer, since if there is something in the buffer, we've already done // this checking and flushing. if (_writePos == 0) { if (!_parent.CanWrite) throw __Error.GetWriteNotSupported(); FlushReadBuffer(); } } /// <summary>Validates arguments to Read and Write and throws resulting exceptions.</summary> /// <param name="array">The buffer to read from or write to.</param> /// <param name="offset">The zero-based offset into the array.</param> /// <param name="count">The maximum number of bytes to read or write.</param> private void ValidateReadWriteArgs(byte[] array, int offset, int count) { if (array == null) { throw new ArgumentNullException("array", SR.ArgumentNull_Buffer); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset", SR.ArgumentOutOfRange_NeedNonNegNum); } if (count < 0) { throw new ArgumentOutOfRangeException("count", SR.ArgumentOutOfRange_NeedNonNegNum); } if (array.Length - offset < count) { throw new ArgumentException(SR.Argument_InvalidOffLen /*, no good single parameter name to pass*/); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> public override long Seek(long offset, SeekOrigin origin) { if (origin < SeekOrigin.Begin || origin > SeekOrigin.End) { throw new ArgumentException(SR.Argument_InvalidSeekOrigin, "origin"); } if (_fileHandle.IsClosed) { throw __Error.GetFileNotOpen(); } if (!_parent.CanSeek) { throw __Error.GetSeekNotSupported(); } VerifyOSHandlePosition(); // Flush our write/read buffer. FlushWrite will output any write buffer we have and reset _bufferWritePos. // We don't call FlushRead, as that will do an unnecessary seek to rewind the read buffer, and since we're // about to seek and update our position, we can simply update the offset as necessary and reset our read // position and length to 0. (In the future, for some simple cases we could potentially add an optimization // here to just move data around in the buffer for short jumps, to avoid re-reading the data from disk.) FlushWriteBuffer(); if (origin == SeekOrigin.Current) { offset -= (_readLength - _readPos); } _readPos = _readLength = 0; // Keep track of where we were, in case we're in append mode and need to verify long oldPos = 0; if (_appendStart >= 0) { oldPos = SeekCore(0, SeekOrigin.Current); } // Jump to the new location long pos = SeekCore(offset, origin); // Prevent users from overwriting data in a file that was opened in append mode. if (_appendStart != -1 && pos < _appendStart) { SeekCore(oldPos, SeekOrigin.Begin); throw new IOException(SR.IO_SeekAppendOverwrite); } // Return the new position return pos; } /// <summary>Sets the current position of this stream to the given value.</summary> /// <param name="offset">The point relative to origin from which to begin seeking. </param> /// <param name="origin"> /// Specifies the beginning, the end, or the current position as a reference /// point for offset, using a value of type SeekOrigin. /// </param> /// <returns>The new position in the stream.</returns> private long SeekCore(long offset, SeekOrigin origin) { Debug.Assert(!_fileHandle.IsClosed && CanSeek); Debug.Assert(origin >= SeekOrigin.Begin && origin <= SeekOrigin.End); long pos = SysCall((fd, off, or) => Interop.libc.lseek(fd, off, or), offset, (Interop.libc.SeekWhence)(int)origin); // SeekOrigin values are the same as Interop.libc.SeekWhence values _filePosition = pos; return pos; } /// <summary> /// Helper for making system calls that involve the stream's file descriptor. /// System calls are expected to return greather than or equal to zero on success, /// and less than zero on failure. In the case of failure, errno is expected to /// be set to the relevant error code. /// </summary> /// <typeparam name="TArg1">Specifies the type of an argument to the system call.</typeparam> /// <typeparam name="TArg2">Specifies the type of another argument to the system call.</typeparam> /// <param name="sysCall">A delegate that invokes the system call.</param> /// <param name="arg1">The first argument to be passed to the system call, after the file descriptor.</param> /// <param name="arg2">The second argument to be passed to the system call.</param> /// <param name="throwOnError">true to throw an exception if a non-interuption error occurs; otherwise, false.</param> /// <returns>The return value of the system call.</returns> /// <remarks> /// Arguments are expected to be passed via <paramref name="arg1"/> and <paramref name="arg2"/> /// so as to avoid delegate and closure allocations at the call sites. /// </remarks> private long SysCall<TArg1, TArg2>( Func<int, TArg1, TArg2, long> sysCall, TArg1 arg1 = default(TArg1), TArg2 arg2 = default(TArg2), bool throwOnError = true) { SafeFileHandle handle = _fileHandle; Debug.Assert(sysCall != null); Debug.Assert(handle != null); bool gotRefOnHandle = false; try { // Get the file descriptor from the handle. We increment the ref count to help // ensure it's not closed out from under us. handle.DangerousAddRef(ref gotRefOnHandle); Debug.Assert(gotRefOnHandle); int fd = (int)handle.DangerousGetHandle(); Debug.Assert(fd >= 0); // System calls may fail due to EINTR (signal interruption). We need to retry in those cases. while (true) { long result = sysCall(fd, arg1, arg2); if (result < 0) { Interop.ErrorInfo errorInfo = Interop.Sys.GetLastErrorInfo(); if (errorInfo.Error == Interop.Error.EINTR) { continue; } else if (throwOnError) { throw Interop.GetExceptionForIoErrno(errorInfo, _path, isDirectory: false); } } return result; } } finally { if (gotRefOnHandle) { handle.DangerousRelease(); } else { throw new ObjectDisposedException(SR.ObjectDisposed_FileClosed); } } } } }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2011 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit wiki.developer.mindtouch.com; * please review the licensing section. * * 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.Threading; using log4net; using MindTouch.Collections; using MindTouch.Tasking; namespace MindTouch.Threading { /// <summary> /// ElasticPriorityThreadPool provides a thread pool that can have a variable number of threads going from a minimum number of reserved /// threads to a maximum number of parallel threads. /// </summary> /// <remarks> /// The threads are obtained from the DispatchThreadScheduler and shared across all other clients of the DispatchThreadScheduler. /// Obtained threads are released automatically if the thread pool is idle for long enough. Reserved threads are never released. /// </remarks> public class ElasticPriorityThreadPool : IDispatchHost, IDisposable { //--- Constants --- /// <summary> /// Maximum number of threads that can be reserved by a single instance. /// </summary> public const int MAX_RESERVED_THREADS = 1000; //--- Types --- private class PrioritizedThreadPool : IDispatchQueue { //--- Fields --- private readonly int _priority; private readonly ElasticPriorityThreadPool _pool; //--- Constructors --- public PrioritizedThreadPool(int priority, ElasticPriorityThreadPool pool) { _priority = priority; _pool = pool; } //--- Properties --- public int Priority { get { return _priority; } } //--- Methods --- public void QueueWorkItem(Action callback) { if(!TryQueueWorkItem(callback)) { throw new NotSupportedException("TryQueueWorkItem failed"); } } public bool TryQueueWorkItem(Action callback) { return _pool.TryQueueWorkItem(_priority, callback); } } //--- Class Fields --- private static int _instanceCounter; private static readonly ILog _log = LogUtils.CreateLog(); //--- Fields --- private readonly object _syncRoot = new object(); private readonly int _id = Interlocked.Increment(ref _instanceCounter); private readonly IThreadsafePriorityQueue<Action> _inbox; private readonly PrioritizedThreadPool[] _prioritizedInbox; private readonly IThreadsafeStack<KeyValuePair<DispatchThread, Result<DispatchWorkItem>>> _reservedThreads = new LockFreeStack<KeyValuePair<DispatchThread, Result<DispatchWorkItem>>>(); private readonly int _minReservedThreads; private readonly int _maxParallelThreads; private int _threadCount; private int _threadVelocity; private DispatchThread[] _activeThreads; private bool _disposed; //--- Constructors --- /// <summary> /// Creates a new ElasticPriorityThreadPool instance. /// </summary> /// <param name="minReservedThreads">Minium number of threads to reserve for the thread pool.</param> /// <param name="maxParallelThreads">Maximum number of parallel threads used by the thread pool.</param> /// <param name="maxPriority">Maximum priority number (inclusive upper bound).</param> /// <exception cref="InsufficientResourcesException">The ElasticPriorityThreadPool instance was unable to obtain the minimum reserved threads.</exception> public ElasticPriorityThreadPool(int minReservedThreads, int maxParallelThreads, int maxPriority) { _minReservedThreads = Math.Max(0, Math.Min(minReservedThreads, MAX_RESERVED_THREADS)); _maxParallelThreads = Math.Max(Math.Max(1, minReservedThreads), Math.Min(maxParallelThreads, int.MaxValue)); _inbox = new LockFreePriorityQueue<Action>(maxPriority); _prioritizedInbox = new PrioritizedThreadPool[maxPriority]; for(int i = 0; i < maxPriority; ++i) { _prioritizedInbox[i] = new PrioritizedThreadPool(i, this); } // initialize reserved threads _activeThreads = new DispatchThread[Math.Min(_maxParallelThreads, Math.Max(_minReservedThreads, Math.Min(16, _maxParallelThreads)))]; if(_minReservedThreads > 0) { DispatchThreadScheduler.RequestThread(_minReservedThreads, AddThread); } DispatchThreadScheduler.RegisterHost(this); _log.DebugFormat("Create @{0}", this); } //--- Properties --- /// <summary> /// Number of minimum reserved threads. /// </summary> public int MinReservedThreads { get { return _disposed ? 0 : _minReservedThreads; } } /// <summary> /// Number of maxium parallel threads. /// </summary> public int MaxParallelThreads { get { return _maxParallelThreads; } } /// <summary> /// Number of threads currently used. /// </summary> public int ThreadCount { get { return _threadCount; } } /// <summary> /// Number of items pending for execution. /// </summary> public int WorkItemCount { get { int result = _inbox.Count; DispatchThread[] threads = _activeThreads; foreach(DispatchThread thread in threads) { if(thread != null) { result += thread.PendingWorkItemCount; } } return result; } } /// <summary> /// Max priority for work items. /// </summary> public int MaxPriority { get { return _inbox.MaxPriority; } } /// <summary> /// Accessor for prioritized dispatch queue. /// </summary> /// <param name="priority">Dispatch queue priority level (between 0 and MaxPriority).</param> /// <returns>Prioritized dispatch queue.</returns> public IDispatchQueue this[int priority] { get { if(_disposed) { throw new ObjectDisposedException("ElasticPriorityThreadPool has already been disposed"); } return _prioritizedInbox[priority]; } } //--- Methods --- /// <summary> /// Shutdown the ElasticThreadPool instance. This method blocks until all pending items have finished processing. /// </summary> public void Dispose() { if(!_disposed) { _disposed = true; _log.DebugFormat("Dispose @{0}", this); // TODO (steveb): make dispose more reliable // 1) we can't wait indefinitively! // 2) we should progressively sleep longer and longer to avoid unnecessary overhead // 3) this pattern feels useful enough to be captured into a helper method // wait until all threads have been decommissioned while(ThreadCount > 0) { Thread.Sleep(100); } // discard all reserved threads KeyValuePair<DispatchThread, Result<DispatchWorkItem>> reserved; while(_reservedThreads.TryPop(out reserved)) { DispatchThreadScheduler.ReleaseThread(reserved.Key, reserved.Value); } DispatchThreadScheduler.UnregisterHost(this); } } /// <summary> /// Convert the dispatch queue into a string. /// </summary> /// <returns>String.</returns> public override string ToString() { return string.Format("ElasticPriorityThreadPool @{0} (current: {1}, reserve: {5}, velocity: {2}, min: {3}, max: {4}, items: {6}, max-priority: {7})", _id, _threadCount, _threadVelocity, _minReservedThreads, _maxParallelThreads, _reservedThreads.Count, WorkItemCount, _inbox.MaxPriority); } private bool TryQueueWorkItem(int priority, Action callback) { if(_disposed) { throw new ObjectDisposedException("ElasticThreadPool has already been disposed"); } // check if we can enqueue work-item into current dispatch thread IDispatchQueue queue = this[priority]; if(DispatchThread.TryQueueWorkItem(queue, callback)) { return true; } // check if there are available threads to which the work-item can be given to KeyValuePair<DispatchThread, Result<DispatchWorkItem>> entry; if(_reservedThreads.TryPop(out entry)) { lock(_syncRoot) { RegisterThread("new item", entry.Key); } // found an available thread, let's resume it with the work-item entry.Value.Return(new DispatchWorkItem(callback, queue)); return true; } // no threads available, keep work-item for later if(!_inbox.TryEnqueue(priority, callback)) { return false; } // check if we need to request a thread to kick things off if(ThreadCount == 0) { ((IDispatchHost)this).IncreaseThreadCount("request first thread"); } return true; } private void AddThread(KeyValuePair<DispatchThread, Result<DispatchWorkItem>> keyvalue) { DispatchThread thread = keyvalue.Key; Result<DispatchWorkItem> result = keyvalue.Value; if(_threadVelocity >= 0) { lock(_syncRoot) { _threadVelocity = 0; // check if an item is available for dispatch int priority; Action callback; if(TryRequestItem(null, out priority, out callback)) { RegisterThread("new thread", thread); // dispatch work-item result.Return(new DispatchWorkItem(callback, this[priority])); return; } } } // we have no need for this thread RemoveThread("insufficient work for new thread", thread, result); } private void RemoveThread(string reason, DispatchThread thread, Result<DispatchWorkItem> result) { if(thread == null) { throw new ArgumentNullException("thread"); } if(result == null) { throw new ArgumentNullException("result"); } if(thread.PendingWorkItemCount != 0) { throw new ArgumentException(string.Format("thread #{1} still has work-items in queue (items: {0})", thread.PendingWorkItemCount, thread.Id), "thread"); } // remove thread from list of allocated threads lock(_syncRoot) { _threadVelocity = 0; UnregisterThread(reason, thread); } // check if we can put thread into the reserved list if(_reservedThreads.Count < MinReservedThreads) { if(!_reservedThreads.TryPush(new KeyValuePair<DispatchThread, Result<DispatchWorkItem>>(thread, result))) { throw new NotSupportedException("TryPush failed"); } } else { // return thread to resource manager DispatchThreadScheduler.ReleaseThread(thread, result); } } private bool TryRequestItem(DispatchThread thread, out int priority, out Action callback) { // check if we can find a work-item in the shared queue if(_inbox.TryDequeue(out priority, out callback)) { return true; } // try to steal a work-item from another thread; take a snapshot of all allocated threads (needed in case the array is copied for resizing) DispatchThread[] threads = _activeThreads; foreach(DispatchThread entry in threads) { // check if we can steal a work-item from this thread if((entry != null) && !ReferenceEquals(entry, thread) && entry.TryStealWorkItem(out callback)) { priority = ((PrioritizedThreadPool)entry.DispatchQueue).Priority; return true; } } // check again if we can find a work-item in the shared queue since trying to steal may have overlapped with the arrival of a new item if(_inbox.TryDequeue(out priority, out callback)) { return true; } return false; } private void RegisterThread(string reason, DispatchThread thread) { ++_threadCount; thread.Host = this; // find an empty slot in the array of all threads int index; for(index = 0; index < _activeThreads.Length; ++index) { // check if we found an empty slot if(_activeThreads[index] == null) { // assign it to the found slot and stop iterating _activeThreads[index] = thread; break; } } // check if we need to grow the array if(index == _activeThreads.Length) { // make room to add a new thread by doubling the array size and copying over the existing entries DispatchThread[] newArray = new DispatchThread[2 * _activeThreads.Length]; Array.Copy(_activeThreads, newArray, _activeThreads.Length); // assign new thread newArray[index] = thread; // update instance field _activeThreads = newArray; } #if EXTRA_DEBUG _log.DebugFormat("AddThread: {1} - {0}", this, reason); #endif } private void UnregisterThread(string reason, DispatchThread thread) { thread.Host = null; // find thread and remove it for(int i = 0; i < _activeThreads.Length; ++i) { if(ReferenceEquals(_activeThreads[i], thread)) { --_threadCount; _activeThreads[i] = null; #if EXTRA_DEBUG _log.DebugFormat("RemoveThread: {1} - {0}", this, reason); #endif break; } } } //--- IDispatchHost Members --- long IDispatchHost.PendingWorkItemCount { get { return WorkItemCount; } } int IDispatchHost.MinThreadCount { get { return MinReservedThreads; } } int IDispatchHost.MaxThreadCount { get { return _maxParallelThreads; } } void IDispatchHost.RequestWorkItem(DispatchThread thread, Result<DispatchWorkItem> result) { if(thread == null) { throw new ArgumentNullException("thread"); } if(thread.PendingWorkItemCount > 0) { throw new ArgumentException(string.Format("thread #{1} still has work-items in queue (items: {0})", thread.PendingWorkItemCount, thread.Id), "thread"); } if(!ReferenceEquals(thread.Host, this)) { throw new InvalidOperationException(string.Format("thread is allocated to another queue: received {0}, expected: {1}", thread.Host, this)); } if(result == null) { throw new ArgumentNullException("result"); } // check if we need to decommission threads without causing starvation if(_threadVelocity < 0) { RemoveThread("system saturation", thread, result); return; } // check if we found a work-item int priority; Action callback; if(TryRequestItem(thread, out priority, out callback)) { // dispatch work-item result.Return(new DispatchWorkItem(callback, this[priority])); } else { // relinquich thread; it's not required anymore RemoveThread("insufficient work", thread, result); } } void IDispatchHost.IncreaseThreadCount(string reason) { // check if thread pool is already awaiting another thread if(_threadVelocity > 0) { return; } lock(_syncRoot) { _threadVelocity = 1; // check if thread pool has enough threads if(_threadCount >= _maxParallelThreads) { _threadVelocity = 0; return; } #if EXTRA_DEBUG _log.DebugFormat("IncreaseThreadCount: {1} - {0}", this, reason); #endif } // check if there are threads in the reserve KeyValuePair<DispatchThread, Result<DispatchWorkItem>> reservedThread; if(_reservedThreads.TryPop(out reservedThread)) { AddThread(reservedThread); } else { DispatchThreadScheduler.RequestThread(0, AddThread); } } void IDispatchHost.MaintainThreadCount(string reason) { // check if thread pool is already trying to steady if(_threadVelocity == 0) { return; } lock(_syncRoot) { _threadVelocity = 0; #if EXTRA_DEBUG _log.DebugFormat("MaintainThreadCount: {1} - {0}", this, reason); #endif } } void IDispatchHost.DecreaseThreadCount(string reason) { // check if thread pool is already trying to discard thread if(_threadVelocity < 0) { return; } lock(_syncRoot) { _threadVelocity = -1; #if EXTRA_DEBUG _log.DebugFormat("DecreaseThreadCount: {1} - {0}", this, reason); #endif } } } }
using System; using System.Buffers; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; using SuperSocket; using SuperSocket.Client; using SuperSocket.WebSocket; using SuperSocket.WebSocket.Server; using Xunit; using Xunit.Abstractions; namespace WebSocket4Net.Tests { public class MainTest : TestBase { private string _loopbackIP; public MainTest(ITestOutputHelper outputHelper) : base(outputHelper) { _loopbackIP = IPAddress.Loopback.ToString(); } [Theory] [InlineData(typeof(RegularHostConfigurator))] [InlineData(typeof(SecureHostConfigurator))] public async Task TestHandshake(Type hostConfiguratorType) { var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType); var serverSessionPath = string.Empty; var connected = false; using (var server = CreateWebSocketSocketServerBuilder(builder => { builder.UseSessionHandler(async (s) => { serverSessionPath = (s as WebSocketSession).Path; connected = true; await Task.CompletedTask; }, async (s, e) => { connected = false; await Task.CompletedTask; }); return builder; }, hostConfigurator: hostConfigurator) .BuildAsServer()) { Assert.True(await server.StartAsync()); OutputHelper.WriteLine("Server started."); var path = "/app/talk"; var url = $"{hostConfigurator.WebSocketSchema}://{_loopbackIP}:{hostConfigurator.Listener.Port}" + path; var websocket = new WebSocket(url); hostConfigurator.ConfigureClient(websocket); Assert.Equal(WebSocketState.None, websocket.State); Assert.True(await websocket.OpenAsync(), "Failed to connect"); Assert.Equal(WebSocketState.Open, websocket.State); await Task.Delay(1 * 1000); // test path Assert.Equal(path, serverSessionPath); Assert.True(connected); await websocket.CloseAsync(); Assert.NotNull(websocket.CloseStatus); Assert.Equal(CloseReason.NormalClosure, websocket.CloseStatus.Reason); await Task.Delay(1 * 1000); Assert.Equal(WebSocketState.Closed, websocket.State); Assert.False(connected); await server.StopAsync(); } } [Theory] [InlineData(typeof(RegularHostConfigurator), 10)] [InlineData(typeof(SecureHostConfigurator), 10)] public async Task TestEchoMessage(Type hostConfiguratorType, int repeat) { var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType); var serverSessionPath = string.Empty; var connected = false; using (var server = CreateWebSocketSocketServerBuilder(builder => { builder.UseSessionHandler(async (s) => { connected = true; await Task.CompletedTask; }, async (s, e) => { connected = false; await Task.CompletedTask; }); builder.UseWebSocketMessageHandler(async (s, p) => { var session = s as WebSocketSession; await session.SendAsync(p.Message); }); return builder; }, hostConfigurator: hostConfigurator) .BuildAsServer()) { Assert.True(await server.StartAsync()); OutputHelper.WriteLine("Server started."); var websocket = new WebSocket($"{hostConfigurator.WebSocketSchema}://{_loopbackIP}:{hostConfigurator.Listener.Port}"); hostConfigurator.ConfigureClient(websocket); Assert.True(await websocket.OpenAsync(), "Failed to connect"); Assert.Equal(WebSocketState.Open, websocket.State); await Task.Delay(1 * 1000); Assert.True(connected); for (var i = 0; i < repeat; i++) { var text = Guid.NewGuid().ToString(); await websocket.SendAsync(text); var receivedText = (await websocket.ReceiveAsync()).Message; Assert.Equal(text, receivedText); } await websocket.CloseAsync(); Assert.NotNull(websocket.CloseStatus); Assert.Equal(CloseReason.NormalClosure, websocket.CloseStatus.Reason); await Task.Delay(1 * 1000); Assert.Equal(WebSocketState.Closed, websocket.State); Assert.False(connected); await server.StopAsync(); } } /* [Theory] [InlineData(typeof(RegularHostConfigurator))] [InlineData(typeof(SecureHostConfigurator))] */ public async Task TestPingFromServer(Type hostConfiguratorType) { var hostConfigurator = CreateObject<IHostConfigurator>(hostConfiguratorType); WebSocketSession session = null; using (var server = CreateWebSocketSocketServerBuilder(builder => { builder.UseSessionHandler(async (s) => { session = s as WebSocketSession; await Task.CompletedTask; }); return builder; }, hostConfigurator: hostConfigurator) .BuildAsServer()) { Assert.True(await server.StartAsync()); OutputHelper.WriteLine("Server started."); var websocket = new WebSocket($"{hostConfigurator.WebSocketSchema}://{_loopbackIP}:{hostConfigurator.Listener.Port}"); hostConfigurator.ConfigureClient(websocket); Assert.True(await websocket.OpenAsync(), "Failed to connect"); var lastPingReceived = websocket.PingPongStatus.LastPingReceived; Assert.Equal(WebSocketState.Open, websocket.State); await Task.Delay(1 * 1000); Assert.NotNull(session); // send ping from server await session.SendAsync(new WebSocketPackage { OpCode = OpCode.Ping, Data = new ReadOnlySequence<byte>(Utf8Encoding.GetBytes("Hello")) }); await Task.Delay(1 * 1000); var lastPingReceivedNow = websocket.PingPongStatus.LastPingReceived; Assert.NotEqual(lastPingReceived, lastPingReceivedNow); await websocket.CloseAsync(); await server.StopAsync(); } } } }
//----------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace Microsoft.Tools.ServiceModel.ComSvcConfig { using System; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.Diagnostics; using System.Configuration; using System.Collections; using System.Collections.Specialized; using System.Collections.Generic; using System.IO; using System.Globalization; using System.Text; using System.Threading; using System.Reflection; using System.Runtime.InteropServices; using System.Security; using System.ServiceModel; using System.ServiceModel.Configuration; using Microsoft.Tools.ServiceModel; using System.Xml; class EndpointConfig { Guid appid; Guid clsid; Guid iid; string bindingType; string bindingName; Uri address; bool isMexEndpoint; List<string> methods; EndpointConfigContainer container; public static readonly string TempURI = "http://tempuri.org/"; public static readonly string MexEndpointSuffix = "mex"; public Guid Appid { get { return this.appid; } set { this.appid = value; } } public Guid Clsid { get { return this.clsid; } } public Guid Iid { get { return this.iid; } } public string BindingType { get { return this.bindingType; } } public string BindingName { get { return this.bindingName; } } public Uri Address { get { return this.address; } } public bool IsMexEndpoint { get { return isMexEndpoint; } } public EndpointConfigContainer Container { get { return container; } set { container = value; } } public IList<string> Methods { get { return methods; } set { methods = (List<string>)value; } } public string ContractType { get { if (isMexEndpoint) return ServiceMetadataBehavior.MexContractName; else return iid.ToString("B").ToUpperInvariant(); } } public bool MatchServiceType(string serviceType) { string[] serviceParams = serviceType.Split(','); if (serviceParams.Length != 2) { return false; } try { Guid guid = new Guid(serviceParams[0]); if (guid != Appid) return false; guid = new Guid(serviceParams[1]); if (guid != Clsid) return false; return true; } catch (FormatException) { } return false; } public bool MatchContract(string contract) { if (isMexEndpoint) { if (ContractType == contract) return true; else return false; } else { try { Guid guid = new Guid(contract); if (guid == Iid) return true; } catch (FormatException) { } return false; } } public string ServiceType { get { return Appid.ToString("B").ToUpperInvariant() + "," + Clsid.ToString("B").ToUpperInvariant(); } } public string ApplicationName { get { ComAdminAppInfo appInfo = ComAdminWrapper.GetAppInfo(appid.ToString("B")); if (null == appInfo) return null; return appInfo.Name; } } public string ComponentProgID { get { ComAdminAppInfo appInfo = ComAdminWrapper.GetAppInfo(appid.ToString("B")); if (null == appInfo) return null; ComAdminClassInfo classInfo = appInfo.FindClass(clsid.ToString("B")); if (null == classInfo) return null; return classInfo.Name; } } public string InterfaceName { get { if (!isMexEndpoint) { ComAdminAppInfo appInfo = ComAdminWrapper.GetAppInfo(appid.ToString("B")); if (null == appInfo) return null; ComAdminClassInfo classInfo = appInfo.FindClass(clsid.ToString("B")); if (null == classInfo) return null; ComAdminInterfaceInfo interfaceInfo = classInfo.FindInterface(iid.ToString("B")); if (null == interfaceInfo) return null; return interfaceInfo.Name; } else { return ContractType; } } } public EndpointConfig(Guid appid, Guid clsid, Guid iid, string bindingType, string bindingName, Uri address, bool isMexEndpoint, List<string> methods) { this.appid = appid; this.clsid = clsid; this.iid = iid; this.bindingType = bindingType; this.bindingName = bindingName; this.address = address; this.isMexEndpoint = isMexEndpoint; this.methods = methods; this.container = null; } } abstract class EndpointConfigContainer { public abstract List<EndpointConfig> GetEndpointConfigs(); public virtual bool HasEndpointsForApplication(Guid appid) { // This is a default (but kind of inefficient) implementation of this function List<EndpointConfig> endpointConfigs = GetEndpointConfigs(appid); return (endpointConfigs.Count > 0); } public virtual List<EndpointConfig> GetEndpointConfigs(Guid appid) { // A default implementation, kind of inefficient, but subclasses can override if they want.. List<EndpointConfig> endpointConfigs = new List<EndpointConfig>(); foreach (EndpointConfig endpointConfig in GetEndpointConfigs()) { if (endpointConfig.Appid == appid) { endpointConfigs.Add(endpointConfig); } } return endpointConfigs; } public abstract void Add(IList<EndpointConfig> endpointConfigs); public abstract void PrepareChanges(); public abstract void AbortChanges(); // this can be called at any point prior to Commit public abstract void CommitChanges(); public abstract string DefaultEndpointAddress(Guid appId, Guid clsid, Guid iid); public abstract string DefaultMexAddress(Guid appId, Guid clsid); public abstract string DefaultBindingType { get; } public abstract string DefaultBindingName { get; } public abstract string DefaultTransactionalBindingType { get; } public abstract string DefaultTransactionalBindingName { get; } public abstract string DefaultMexBindingType { get; } public abstract string DefaultMexBindingName { get; } public abstract bool WasModified { get; set; } public abstract Configuration GetConfiguration(bool readOnly); public abstract string BaseServiceAddress(Guid appId, Guid clsid, Guid iid); public abstract List<string> GetBaseAddresses(EndpointConfig config); public abstract void Remove(IList<EndpointConfig> endpointConfigs); protected abstract void RemoveBinding(Configuration config); protected abstract void AddBinding(Configuration config); // returns true if added successfully, or false if didnt add due to duplicate. protected bool BaseAddEndpointConfig(Configuration config, EndpointConfig endpointConfig) { ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config); ServiceElementCollection serviceColl = sg.Services.Services; ServiceElement serviceElement = null; // Find serviceElement foreach (ServiceElement el in serviceColl) { if (endpointConfig.MatchServiceType(el.Name)) { serviceElement = el; break; } } if (serviceElement == null) { // Didn't find one, create new element for this clsid serviceElement = new ServiceElement(endpointConfig.ServiceType); string baseServiceAddress = BaseServiceAddress(endpointConfig.Appid, endpointConfig.Clsid, endpointConfig.Iid); if (!String.IsNullOrEmpty(baseServiceAddress)) { BaseAddressElement bae = new BaseAddressElement(); bae.BaseAddress = baseServiceAddress; serviceElement.Host.BaseAddresses.Add(bae); } sg.Services.Services.Add(serviceElement); } if (endpointConfig.IsMexEndpoint) { EnsureComMetaDataExchangeBehaviorAdded(config); serviceElement.BehaviorConfiguration = comServiceBehavior; } bool methodsAdded = false; if (!endpointConfig.IsMexEndpoint) { methodsAdded = AddComContractToConfig(config, endpointConfig.InterfaceName, endpointConfig.Iid.ToString("B"), endpointConfig.Methods); } // Now, check if endpoint already exists.. foreach (ServiceEndpointElement ee in serviceElement.Endpoints) { bool listenerExists = true; if (this is ComplusEndpointConfigContainer) listenerExists = ((ComplusEndpointConfigContainer)this).ListenerComponentExists; if (endpointConfig.MatchContract(ee.Contract)) { if (listenerExists) return methodsAdded; // didn't add due to duplicate else serviceElement.Endpoints.Remove(ee); } } // All right, add the new endpoint now ServiceEndpointElement endpointElement = new ServiceEndpointElement(endpointConfig.Address, endpointConfig.ContractType); endpointElement.Binding = endpointConfig.BindingType; endpointElement.BindingConfiguration = endpointConfig.BindingName; serviceElement.Endpoints.Add(endpointElement); AddBinding(config); return true; } protected bool RemoveComContractMethods(Configuration config, string interfaceID, IList<string> methods) { Guid iidInterface = new Guid(interfaceID); ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config); ComContractElementCollection contractCollection = sg.ComContracts.ComContracts; foreach (ComContractElement contractElement in contractCollection) { try { Guid contract = new Guid(contractElement.Contract); if (contract == iidInterface) { foreach (string methodName in methods) { foreach (ComMethodElement methodElement in contractElement.ExposedMethods) { if (methodElement.ExposedMethod == methodName) { contractElement.ExposedMethods.Remove(methodElement); break; } } } if (contractElement.ExposedMethods.Count == 0) { sg.ComContracts.ComContracts.Remove(contractElement); return true; } } } catch (FormatException) { } } return false; } protected bool RemoveComContractIfNotUsedByAnyService(Configuration config, string interfaceID) { ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config); ServiceElementCollection serviceColl = sg.Services.Services; Guid iidInterface = new Guid(interfaceID); // Find serviceElement foreach (ServiceElement el in serviceColl) { // Now, check if endpoint already exists.. foreach (ServiceEndpointElement ee in el.Endpoints) { try { if (!IsMetaDataEndpoint(ee)) { Guid Iid = new Guid(ee.Contract); if (iidInterface == Iid) return false; } } catch (FormatException) { } } } ComContractElementCollection contractCollection = sg.ComContracts.ComContracts; foreach (ComContractElement element in contractCollection) { try { Guid contract = new Guid(element.Contract); if (contract == iidInterface) { contractCollection.Remove(element); return true; } } catch (FormatException) { } } return false; } protected bool AddComContractToConfig(Configuration config, string name, string contractType, IList<string> methods) { Guid contractIID = new Guid(contractType); ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config); ComContractElementCollection contractCollection = sg.ComContracts.ComContracts; foreach (ComContractElement comContract in contractCollection) { try { Guid contractFound = new Guid(comContract.Contract); if (contractIID == contractFound) { bool methodsAdded = false; bool found = false; foreach (string methodName in methods) { found = false; foreach (ComMethodElement methodElement in comContract.ExposedMethods) { if (methodElement.ExposedMethod == methodName) found = true; } if (!found) { comContract.ExposedMethods.Add(new ComMethodElement(methodName)); methodsAdded = true; } } if (comContract.PersistableTypes.Count == 0 && Tool.Options.AllowReferences && methodsAdded) { comContract.PersistableTypes.EmitClear = true; } return methodsAdded; } } catch (FormatException) { } } // The contract does not exists // so we are going to add it ComContractElement newComContract = new ComContractElement(contractIID.ToString("B").ToUpperInvariant()); newComContract.Name = name; newComContract.Namespace = EndpointConfig.TempURI + contractIID.ToString().ToUpperInvariant(); foreach (string methodName in methods) newComContract.ExposedMethods.Add(new ComMethodElement(methodName)); if (newComContract.PersistableTypes.Count == 0 && Tool.Options.AllowReferences) { newComContract.PersistableTypes.EmitClear = true; } newComContract.RequiresSession = true; contractCollection.Add(newComContract); return true; } protected bool IsMetaDataEndpoint(ServiceEndpointElement ee) { if (ee.Contract == ServiceMetadataBehavior.MexContractName) return true; else return false; } // NOTE that all EndpointConfigs returned by this guy have Guid.Empty as the appid, caller needs to fix that up protected Dictionary<string, List<EndpointConfig>> BaseGetEndpointsFromConfiguration(Configuration config) { Dictionary<string, List<EndpointConfig>> endpointConfigs = new Dictionary<string, List<EndpointConfig>>(); ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config); ServiceElementCollection serviceColl; try { serviceColl = sg.Services.Services; } catch (System.Configuration.ConfigurationErrorsException e) { ToolConsole.WriteWarning(e.Message); ToolConsole.WriteWarning(SR.GetString(SR.ConfigFileSkipped, e.Filename)); return endpointConfigs; } foreach (ServiceElement se in serviceColl) { string serviceType = se.Name; Guid clsid = Guid.Empty; Guid appId = Guid.Empty; string[] serviceParams = serviceType.Split(','); if (serviceParams.Length != 2) { continue; } try { appId = new Guid(serviceParams[0]); clsid = new Guid(serviceParams[1]); } catch (FormatException) { // Only Guid serviceTypes are of interest to us - those are the ones our listener picks up continue; } List<EndpointConfig> list = null; if (endpointConfigs.ContainsKey(serviceType)) { list = endpointConfigs[serviceType]; } else { list = new List<EndpointConfig>(); endpointConfigs[serviceType] = list; } foreach (ServiceEndpointElement ee in se.Endpoints) { EndpointConfig ec = null; if (!IsMetaDataEndpoint(ee)) { Guid contractType; try { contractType = new Guid(ee.Contract); } catch (FormatException) { continue; } ec = new EndpointConfig(Guid.Empty, clsid, contractType, ee.Binding, ee.BindingConfiguration, ee.Address, false, new List<string>()); } else { ec = new EndpointConfig(Guid.Empty, clsid, typeof(IMetadataExchange).GUID, ee.Binding, ee.BindingConfiguration, ee.Address, true, new List<string>()); } list.Add(ec); } } return endpointConfigs; } protected bool RemoveAllServicesForContract(Configuration config, string interfaceID) { ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config); ServiceElementCollection serviceColl = sg.Services.Services; bool removed = false; // Iterate over every serviceElement // in the services collection // and delete the specific interface ServiceElementCollection svcColl = new ServiceElementCollection(); foreach (ServiceElement el in serviceColl) { ServiceEndpointElementCollection endpointCollection = new ServiceEndpointElementCollection(); foreach (ServiceEndpointElement ee in el.Endpoints) { if (interfaceID.ToUpperInvariant() == ee.Contract.ToUpperInvariant()) { // found it ! removed = true; endpointCollection.Add(ee); } } foreach (ServiceEndpointElement elementEndpoint in endpointCollection) { el.Endpoints.Remove(elementEndpoint); if (el.Endpoints.Count == 1) if (el.Endpoints[0].Contract == ServiceMetadataBehavior.MexContractName) el.Endpoints.Remove(el.Endpoints[0]); // if Mex endpoint remove it. if (el.Endpoints.Count == 0) svcColl.Add(el); } } foreach (ServiceElement service in svcColl) { sg.Services.Services.Remove(service); } if (serviceColl.Count == 0) { EnsureComMetaDataExchangeBehaviorRemoved(config); RemoveBinding(config); } return removed; } protected bool RemoveEndpointFromServiceOnly(Configuration config, EndpointConfig endpointConfig) { ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config); ServiceElementCollection serviceColl = sg.Services.Services; ServiceElement serviceElement = null; // Find serviceElement foreach (ServiceElement el in serviceColl) { if (endpointConfig.MatchServiceType(el.Name)) { serviceElement = el; break; } } if (serviceElement == null) { // Didn't find class return false; } // Now, check if endpoint already exists.. foreach (ServiceEndpointElement ee in serviceElement.Endpoints) { if (endpointConfig.MatchContract(ee.Contract) && (ee.Address == endpointConfig.Address)) { // found it ! serviceElement.Endpoints.Remove(ee); if (!endpointConfig.IsMexEndpoint) RemoveComContractIfNotUsedByAnyService(config, ee.Contract); if (serviceElement.Endpoints.Count == 1) if (serviceElement.Endpoints[0].Contract == ServiceMetadataBehavior.MexContractName) serviceElement.Endpoints.Remove(serviceElement.Endpoints[0]); // if Mex endpoint remove it. if (serviceElement.Endpoints.Count == 0) { serviceColl.Remove(serviceElement); if (serviceColl.Count == 0) { EnsureComMetaDataExchangeBehaviorRemoved(config); RemoveBinding(config); } } return true; } } return false; } // returns true if removed successfully, or false if didnt remove due to missing. protected bool BaseRemoveEndpointConfig(Configuration config, EndpointConfig endpointConfig) { if ((endpointConfig.Methods != null) && (!endpointConfig.IsMexEndpoint)) { bool removeContract = RemoveComContractMethods(config, endpointConfig.Iid.ToString("B"), endpointConfig.Methods); if (removeContract) RemoveAllServicesForContract(config, endpointConfig.Iid.ToString("B")); return true; } else return RemoveEndpointFromServiceOnly(config, endpointConfig); } // helper function used by subclasses protected Configuration GetConfigurationFromFile(string fileName) { ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap(); Configuration machineConfig = ConfigurationManager.OpenMachineConfiguration(); fileMap.MachineConfigFilename = machineConfig.FilePath; fileMap.ExeConfigFilename = fileName; if (!IsValidRuntime(fileName)) { string runtimeVersion = Assembly.GetExecutingAssembly().ImageRuntimeVersion; ToolConsole.WriteError(SR.GetString(SR.InvalidRuntime, runtimeVersion), ""); throw Tool.CreateException(SR.GetString(SR.OperationAbortedDuetoClrVersion), null); } return ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None); } const string comServiceBehavior = "ComServiceMexBehavior"; protected void EnsureComMetaDataExchangeBehaviorAdded(Configuration config) { ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config); if (!sg.Behaviors.ServiceBehaviors.ContainsKey(comServiceBehavior)) { ServiceBehaviorElement behavior = new ServiceBehaviorElement(comServiceBehavior); sg.Behaviors.ServiceBehaviors.Add(behavior); ServiceMetadataPublishingElement metadataPublishing = new ServiceMetadataPublishingElement(); if (Tool.Options.Hosting == Hosting.Complus || Tool.Options.Hosting == Hosting.NotSpecified) metadataPublishing.HttpGetEnabled = false; else metadataPublishing.HttpGetEnabled = true; behavior.Add(metadataPublishing); ServiceDebugElement serviceDebug = new ServiceDebugElement(); serviceDebug.IncludeExceptionDetailInFaults = false; behavior.Add(serviceDebug); } } protected void EnsureComMetaDataExchangeBehaviorRemoved(Configuration config) { ServiceModelSectionGroup sg = ServiceModelSectionGroup.GetSectionGroup(config); if (sg.Behaviors.ServiceBehaviors.ContainsKey(comServiceBehavior)) { ServiceBehaviorElement element = sg.Behaviors.ServiceBehaviors[comServiceBehavior]; sg.Behaviors.ServiceBehaviors.Remove(element); } } // we can only run on the clr version that we are built against internal static bool IsValidVersion(string version) { if (String.IsNullOrEmpty(version)) return false; return (version == Assembly.GetExecutingAssembly().ImageRuntimeVersion); } public static bool IsValidRuntime(string fileName) { // this is a negative check - we only want to fail // if incorrect data specifically was set if (String.IsNullOrEmpty(fileName)) return true; // this check is needed since we might get here on temporary files that are gone by now if (!File.Exists(fileName)) return true; XmlNode startupNode = null; XmlNodeList supportedRuntimes = null; XmlNode requiredRuntime = null; XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(fileName); startupNode = xmlDoc.DocumentElement.SelectSingleNode("startup"); bool validRuntimeAvailable = true; if (null != startupNode) { supportedRuntimes = startupNode.SelectNodes("supportedRuntime"); if (null != supportedRuntimes) { if (supportedRuntimes.Count == 0) validRuntimeAvailable = true; else validRuntimeAvailable = false; foreach (XmlNode xmlNodeS in supportedRuntimes) { if (IsValidVersion(xmlNodeS.Attributes.GetNamedItem("version").Value)) validRuntimeAvailable = true; } } requiredRuntime = startupNode.SelectSingleNode("requiredRuntime"); if (null != requiredRuntime) { string requiredVersion = requiredRuntime.Attributes.GetNamedItem("version").Value; if (!IsValidVersion(requiredVersion)) { validRuntimeAvailable = false; } } } return validRuntimeAvailable; } } }
/* * Copyright (C) 2009 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Android.Content; using Android.Graphics; using Android.Util; using Android.Views; using System; using System.Collections.Generic; namespace com.bytewild.imaging.cropping { public class CropImageView : ImageViewTouchBase { #region Private members private List<HighlightView> hightlightViews = new List<HighlightView>(); private HighlightView mMotionHighlightView = null; private float mLastX; private float mLastY; private global::com.bytewild.imaging.cropping.HighlightView.HitPosition motionEdge; private Context context; #endregion #region Constructor public CropImageView(Context context, IAttributeSet attrs) : base(context, attrs) { SetLayerType(Android.Views.LayerType.Software, null); this.context = context; } #endregion #region Public methods public void ClearHighlightViews() { this.hightlightViews.Clear(); } public void AddHighlightView(HighlightView hv) { hightlightViews.Add(hv); Invalidate(); } #endregion #region Overrides protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); for (int i = 0; i < hightlightViews.Count; i++) { hightlightViews[i].Draw(canvas); } } protected override void OnLayout(bool changed, int left, int top, int right, int bottom) { base.OnLayout(changed, left, top, right, bottom); if (bitmapDisplayed.Bitmap != null) { foreach (var hv in hightlightViews) { hv.matrix.Set(ImageMatrix); hv.Invalidate(); if (hv.Focused) { centerBasedOnHighlightView(hv); } } } } protected override void ZoomTo(float scale, float centerX, float centerY) { base.ZoomTo(scale, centerX, centerY); foreach (var hv in hightlightViews) { hv.matrix.Set(ImageMatrix); hv.Invalidate(); } } protected override void ZoomIn() { base.ZoomIn(); foreach (var hv in hightlightViews) { hv.matrix.Set(ImageMatrix); hv.Invalidate(); } } protected override void ZoomOut() { base.ZoomOut(); foreach (var hv in hightlightViews) { hv.matrix.Set(ImageMatrix); hv.Invalidate(); } } protected override void PostTranslate(float deltaX, float deltaY) { base.PostTranslate(deltaX, deltaY); for (int i = 0; i < hightlightViews.Count; i++) { HighlightView hv = hightlightViews[i]; hv.matrix.PostTranslate(deltaX, deltaY); hv.Invalidate(); } } public override bool OnTouchEvent(MotionEvent ev) { CropImageActivity cropImage = (CropImageActivity)context; if (cropImage.Saving) { return false; } switch (ev.Action) { case MotionEventActions.Down: for (int i = 0; i < hightlightViews.Count; i++) { HighlightView hv = hightlightViews[i]; var edge = hv.GetHit(ev.GetX(), ev.GetY()); if (edge != global::com.bytewild.imaging.cropping.HighlightView.HitPosition.None) { motionEdge = edge; mMotionHighlightView = hv; mLastX = ev.GetX(); mLastY = ev.GetY(); mMotionHighlightView.Mode = (edge == global::com.bytewild.imaging.cropping.HighlightView.HitPosition.Move) ? HighlightView.ModifyMode.Move : HighlightView.ModifyMode.Grow; break; } } break; case MotionEventActions.Up: if (mMotionHighlightView != null) { centerBasedOnHighlightView(mMotionHighlightView); mMotionHighlightView.Mode = HighlightView.ModifyMode.None; } mMotionHighlightView = null; break; case MotionEventActions.Move: if (mMotionHighlightView != null) { mMotionHighlightView.HandleMotion(motionEdge, ev.GetX() - mLastX, ev.GetY() - mLastY); mLastX = ev.GetX(); mLastY = ev.GetY(); if (true) { // This section of code is optional. It has some user // benefit in that moving the crop rectangle against // the edge of the screen causes scrolling but it means // that the crop rectangle is no longer fixed under // the user's finger. ensureVisible(mMotionHighlightView); } } break; } switch (ev.Action) { case MotionEventActions.Up: Center(true, true); break; case MotionEventActions.Move: // if we're not zoomed then there's no point in even allowing // the user to move the image around. This call to center puts // it back to the normalized location (with false meaning don't // animate). if (GetScale() == 1F) { Center(true, true); } break; } return true; } #endregion #region Private helpers // Pan the displayed image to make sure the cropping rectangle is visible. private void ensureVisible(HighlightView hv) { Rect r = hv.DrawRect; int panDeltaX1 = Math.Max(0, IvLeft - r.Left); int panDeltaX2 = Math.Min(0, IvRight - r.Right); int panDeltaY1 = Math.Max(0, IvTop - r.Top); int panDeltaY2 = Math.Min(0, IvBottom - r.Bottom); int panDeltaX = panDeltaX1 != 0 ? panDeltaX1 : panDeltaX2; int panDeltaY = panDeltaY1 != 0 ? panDeltaY1 : panDeltaY2; if (panDeltaX != 0 || panDeltaY != 0) { PanBy(panDeltaX, panDeltaY); } } // If the cropping rectangle's size changed significantly, change the // view's center and scale according to the cropping rectangle. private void centerBasedOnHighlightView(HighlightView hv) { Rect drawRect = hv.DrawRect; float width = drawRect.Width(); float height = drawRect.Height(); float thisWidth = Width; float thisHeight = Height; float z1 = thisWidth / width * .6F; float z2 = thisHeight / height * .6F; float zoom = Math.Min(z1, z2); zoom = zoom * this.GetScale(); zoom = Math.Max(1F, zoom); if ((Math.Abs(zoom - GetScale()) / zoom) > .1) { float[] coordinates = new float[] { hv.CropRect.CenterX(), hv.CropRect.CenterY() }; ImageMatrix.MapPoints(coordinates); ZoomTo(zoom, coordinates[0], coordinates[1], 300F); } ensureVisible(hv); } #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.IO; using System.Diagnostics; using System.Data.Common; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Runtime.Serialization; using System.Runtime.CompilerServices; namespace System.Data.SqlTypes { [XmlSchemaProvider("GetXsdType")] public sealed class SqlChars : INullable, IXmlSerializable, ISerializable { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- // SqlChars has five possible states // 1) SqlChars is Null // - m_stream must be null, m_lCuLen must be x_lNull // 2) SqlChars contains a valid buffer, // - m_rgchBuf must not be null, and m_stream must be null // 3) SqlChars contains a valid pointer // - m_rgchBuf could be null or not, // if not null, content is garbage, should never look into it. // - m_stream must be null. // 4) SqlChars contains a SqlStreamChars // - m_stream must not be null // - m_rgchBuf could be null or not. if not null, content is garbage, should never look into it. // - m_lCurLen must be x_lNull. // 5) SqlChars contains a Lazy Materialized Blob (ie, StorageState.Delayed) // internal char[] _rgchBuf; // Data buffer private long _lCurLen; // Current data length internal SqlStreamChars _stream; private SqlBytesCharsState _state; private char[] _rgchWorkBuf; // A 1-char work buffer. // The max data length that we support at this time. private const long x_lMaxLen = int.MaxValue; private const long x_lNull = -1L; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- // Public default constructor used for XML serialization public SqlChars() { SetNull(); } // Create a SqlChars with an in-memory buffer public SqlChars(char[] buffer) { _rgchBuf = buffer; _stream = null; if (_rgchBuf == null) { _state = SqlBytesCharsState.Null; _lCurLen = x_lNull; } else { _state = SqlBytesCharsState.Buffer; _lCurLen = _rgchBuf.Length; } _rgchWorkBuf = null; AssertValid(); } // Create a SqlChars from a SqlString public SqlChars(SqlString value) : this(value.IsNull ? null : value.Value.ToCharArray()) { } // Create a SqlChars from a SqlStreamChars internal SqlChars(SqlStreamChars s) { _rgchBuf = null; _lCurLen = x_lNull; _stream = s; _state = (s == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; _rgchWorkBuf = null; AssertValid(); } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- // INullable public bool IsNull { get { return _state == SqlBytesCharsState.Null; } } // Property: the in-memory buffer of SqlChars // Return Buffer even if SqlChars is Null. public char[] Buffer { get { if (FStream()) { CopyStreamToBuffer(); } return _rgchBuf; } } // Property: the actual length of the data public long Length { get { switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: return _stream.Length; default: return _lCurLen; } } } // Property: the max length of the data // Return MaxLength even if SqlChars is Null. // When the buffer is also null, return -1. // If containing a Stream, return -1. public long MaxLength { get { switch (_state) { case SqlBytesCharsState.Stream: return -1L; default: return (_rgchBuf == null) ? -1L : _rgchBuf.Length; } } } // Property: get a copy of the data in a new char[] array. public char[] Value { get { char[] buffer; switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: if (_stream.Length > x_lMaxLen) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); buffer = new char[_stream.Length]; if (_stream.Position != 0) _stream.Seek(0, SeekOrigin.Begin); _stream.Read(buffer, 0, checked((int)_stream.Length)); break; default: buffer = new char[_lCurLen]; Array.Copy(_rgchBuf, 0, buffer, 0, (int)_lCurLen); break; } return buffer; } } // class indexer public char this[long offset] { get { if (offset < 0 || offset >= Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (_rgchWorkBuf == null) _rgchWorkBuf = new char[1]; Read(offset, _rgchWorkBuf, 0, 1); return _rgchWorkBuf[0]; } set { if (_rgchWorkBuf == null) _rgchWorkBuf = new char[1]; _rgchWorkBuf[0] = value; Write(offset, _rgchWorkBuf, 0, 1); } } internal SqlStreamChars Stream { get { return FStream() ? _stream : new SqlStreamChars(this); } set { _lCurLen = x_lNull; _stream = value; _state = (value == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Stream; AssertValid(); } } public StorageState Storage { get { switch (_state) { case SqlBytesCharsState.Null: throw new SqlNullValueException(); case SqlBytesCharsState.Stream: return StorageState.Stream; case SqlBytesCharsState.Buffer: return StorageState.Buffer; default: return StorageState.UnmanagedBuffer; } } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public void SetNull() { _lCurLen = x_lNull; _stream = null; _state = SqlBytesCharsState.Null; AssertValid(); } // Set the current length of the data // If the SqlChars is Null, setLength will make it non-Null. public void SetLength(long value) { if (value < 0) throw new ArgumentOutOfRangeException(nameof(value)); if (FStream()) { _stream.SetLength(value); } else { // If there is a buffer, even the value of SqlChars is Null, // still allow setting length to zero, which will make it not Null. // If the buffer is null, raise exception // if (null == _rgchBuf) throw new SqlTypeException(SR.SqlMisc_NoBufferMessage); if (value > _rgchBuf.Length) throw new ArgumentOutOfRangeException(nameof(value)); else if (IsNull) // At this point we know that value is small enough // Go back in buffer mode _state = SqlBytesCharsState.Buffer; _lCurLen = value; } AssertValid(); } // Read data of specified length from specified offset into a buffer public long Read(long offset, char[] buffer, int offsetInBuffer, int count) { if (IsNull) throw new SqlNullValueException(); // Validate the arguments if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset > Length || offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (offsetInBuffer > buffer.Length || offsetInBuffer < 0) throw new ArgumentOutOfRangeException(nameof(offsetInBuffer)); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException(nameof(count)); // Adjust count based on data length if (count > Length - offset) count = (int)(Length - offset); if (count != 0) { switch (_state) { case SqlBytesCharsState.Stream: if (_stream.Position != offset) _stream.Seek(offset, SeekOrigin.Begin); _stream.Read(buffer, offsetInBuffer, count); break; default: Array.Copy(_rgchBuf, offset, buffer, offsetInBuffer, count); break; } } return count; } // Write data of specified length into the SqlChars from specified offset public void Write(long offset, char[] buffer, int offsetInBuffer, int count) { if (FStream()) { if (_stream.Position != offset) _stream.Seek(offset, SeekOrigin.Begin); _stream.Write(buffer, offsetInBuffer, count); } else { // Validate the arguments if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (_rgchBuf == null) throw new SqlTypeException(SR.SqlMisc_NoBufferMessage); if (offset < 0) throw new ArgumentOutOfRangeException(nameof(offset)); if (offset > _rgchBuf.Length) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); if (offsetInBuffer < 0 || offsetInBuffer > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offsetInBuffer)); if (count < 0 || count > buffer.Length - offsetInBuffer) throw new ArgumentOutOfRangeException(nameof(count)); if (count > _rgchBuf.Length - offset) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); if (IsNull) { // If NULL and there is buffer inside, we only allow writing from // offset zero. // if (offset != 0) throw new SqlTypeException(SR.SqlMisc_WriteNonZeroOffsetOnNullMessage); // treat as if our current length is zero. // Note this has to be done after all inputs are validated, so that // we won't throw exception after this point. // _lCurLen = 0; _state = SqlBytesCharsState.Buffer; } else if (offset > _lCurLen) { // Don't allow writing from an offset that this larger than current length. // It would leave uninitialized data in the buffer. // throw new SqlTypeException(SR.SqlMisc_WriteOffsetLargerThanLenMessage); } if (count != 0) { Array.Copy(buffer, offsetInBuffer, _rgchBuf, offset, count); // If the last position that has been written is after // the current data length, reset the length if (_lCurLen < offset + count) _lCurLen = offset + count; } } AssertValid(); } public SqlString ToSqlString() { return IsNull ? SqlString.Null : new string(Value); } // -------------------------------------------------------------- // Conversion operators // -------------------------------------------------------------- // Alternative method: ToSqlString() public static explicit operator SqlString(SqlChars value) { return value.ToSqlString(); } // Alternative method: constructor SqlChars(SqlString) public static explicit operator SqlChars(SqlString value) { return new SqlChars(value); } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- [Conditional("DEBUG")] private void AssertValid() { Debug.Assert(_state >= SqlBytesCharsState.Null && _state <= SqlBytesCharsState.Stream); if (IsNull) { } else { Debug.Assert((_lCurLen >= 0 && _lCurLen <= x_lMaxLen) || FStream()); Debug.Assert(FStream() || (_rgchBuf != null && _lCurLen <= _rgchBuf.Length)); Debug.Assert(!FStream() || (_lCurLen == x_lNull)); } Debug.Assert(_rgchWorkBuf == null || _rgchWorkBuf.Length == 1); } // whether the SqlChars contains a Stream internal bool FStream() { return _state == SqlBytesCharsState.Stream; } // Copy the data from the Stream to the array buffer. // If the SqlChars doesn't hold a buffer or the buffer // is not big enough, allocate new char array. private void CopyStreamToBuffer() { Debug.Assert(FStream()); long lStreamLen = _stream.Length; if (lStreamLen >= x_lMaxLen) throw new SqlTypeException(SR.SqlMisc_BufferInsufficientMessage); if (_rgchBuf == null || _rgchBuf.Length < lStreamLen) _rgchBuf = new char[lStreamLen]; if (_stream.Position != 0) _stream.Seek(0, SeekOrigin.Begin); _stream.Read(_rgchBuf, 0, (int)lStreamLen); _stream = null; _lCurLen = lStreamLen; _state = SqlBytesCharsState.Buffer; AssertValid(); } private void SetBuffer(char[] buffer) { _rgchBuf = buffer; _lCurLen = (_rgchBuf == null) ? x_lNull : _rgchBuf.Length; _stream = null; _state = (_rgchBuf == null) ? SqlBytesCharsState.Null : SqlBytesCharsState.Buffer; AssertValid(); } // -------------------------------------------------------------- // XML Serialization // -------------------------------------------------------------- XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader r) { char[] value = null; string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. r.ReadElementString(); SetNull(); } else { value = r.ReadElementString().ToCharArray(); SetBuffer(value); } } void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { char[] value = Buffer; writer.WriteString(new string(value, 0, (int)(Length))); } } public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("string", XmlSchema.Namespace); } // -------------------------------------------------------------- // Serialization using ISerializable // -------------------------------------------------------------- // State information is not saved. The current state is converted to Buffer and only the underlying // array is serialized, except for Null, in which case this state is kept. void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } // -------------------------------------------------------------- // Static fields, properties // -------------------------------------------------------------- // Get a Null instance. // Since SqlChars is mutable, have to be property and create a new one each time. public static SqlChars Null { get { return new SqlChars((char[])null); } } } // class SqlChars // SqlStreamChars is a stream build on top of SqlChars, and // provides the Stream interface. The purpose is to help users // to read/write SqlChars object. internal sealed class SqlStreamChars { // -------------------------------------------------------------- // Data members // -------------------------------------------------------------- private SqlChars _sqlchars; // the SqlChars object private long _lPosition; // -------------------------------------------------------------- // Constructor(s) // -------------------------------------------------------------- internal SqlStreamChars(SqlChars s) { _sqlchars = s; _lPosition = 0; } // -------------------------------------------------------------- // Public properties // -------------------------------------------------------------- public long Length { get { CheckIfStreamClosed("get_Length"); return _sqlchars.Length; } } public long Position { get { CheckIfStreamClosed("get_Position"); return _lPosition; } set { CheckIfStreamClosed("set_Position"); if (value < 0 || value > _sqlchars.Length) throw new ArgumentOutOfRangeException(nameof(value)); else _lPosition = value; } } // -------------------------------------------------------------- // Public methods // -------------------------------------------------------------- public long Seek(long offset, SeekOrigin origin) { CheckIfStreamClosed(); long lPosition = 0; switch (origin) { case SeekOrigin.Begin: if (offset < 0 || offset > _sqlchars.Length) throw ADP.ArgumentOutOfRange(nameof(offset)); _lPosition = offset; break; case SeekOrigin.Current: lPosition = _lPosition + offset; if (lPosition < 0 || lPosition > _sqlchars.Length) throw ADP.ArgumentOutOfRange(nameof(offset)); _lPosition = lPosition; break; case SeekOrigin.End: lPosition = _sqlchars.Length + offset; if (lPosition < 0 || lPosition > _sqlchars.Length) throw ADP.ArgumentOutOfRange(nameof(offset)); _lPosition = lPosition; break; default: throw ADP.ArgumentOutOfRange(nameof(offset)); } return _lPosition; } // The Read/Write/Readchar/Writechar simply delegates to SqlChars public int Read(char[] buffer, int offset, int count) { CheckIfStreamClosed(); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); int icharsRead = (int)_sqlchars.Read(_lPosition, buffer, offset, count); _lPosition += icharsRead; return icharsRead; } public void Write(char[] buffer, int offset, int count) { CheckIfStreamClosed(); if (buffer == null) throw new ArgumentNullException(nameof(buffer)); if (offset < 0 || offset > buffer.Length) throw new ArgumentOutOfRangeException(nameof(offset)); if (count < 0 || count > buffer.Length - offset) throw new ArgumentOutOfRangeException(nameof(count)); _sqlchars.Write(_lPosition, buffer, offset, count); _lPosition += count; } public void SetLength(long value) { CheckIfStreamClosed(); _sqlchars.SetLength(value); if (_lPosition > value) _lPosition = value; } // -------------------------------------------------------------- // Private utility functions // -------------------------------------------------------------- private bool FClosed() { return _sqlchars == null; } private void CheckIfStreamClosed([CallerMemberName] string methodname = "") { if (FClosed()) throw ADP.StreamClosed(methodname); } } // class SqlStreamChars } // namespace System.Data.SqlTypes
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using GuruComponents.Netrix.ComInterop; using GuruComponents.Netrix.Designer; using GuruComponents.Netrix.Events; using GuruComponents.Netrix.PlugIns; using GuruComponents.Netrix.WebEditing.Elements; namespace GuruComponents.Netrix.TableDesigner { /// <summary> /// The TableDesigner Extender Provider. /// </summary> /// <remarks> /// The TableDesigner plug-in provides advanced designer features in interactive as well as programmatic mode. /// To activate the designer add the component from toolbox to your form and view the properties in the /// Property Grid. /// <para> /// In case you want or need set the properties directly, without the VS.NET designer, the following code shows the basic way: /// <code> /// this.tableDesigner1 = new GuruComponents.Netrix.TableDesigner.TableDesigner(this.components); /// TableDesignerProperties tp = new TableDesignerProperties(); /// tp.Active = true; /// tp.ProcessTABKey = true; /// tp.SliderActivated = false; /// tp.SliderAddMode = false; /// tp.TableBackground = Color.Empty; /// tp.StaticBehavior = true; /// tp.WithCellSelection = false; /// tp.TableBorder = new TableDesignerProperties.TableBorderBehavior(Color.Gray, 1, System.Drawing.Drawing2D.DashStyle.Solid); /// tp.CellBorder = new TableDesignerProperties.CellBorderBehavior(Color.Silver, 1, System.Drawing.Drawing2D.DashStyle.Dot); /// this.tableDesigner1.SetTableDesigner(htmlEditor, tp); /// </code> /// To get more information about the properties, watch the <see cref="TableDesignerProperties"/> class. Instead of using the /// property bag at runtime you can also call the several Set-Methods available in this class to set the values. All settings /// have immediate effect on the current table and effect other tables once the screen refresh requires a redraw. /// </para> /// The table designer has two basic features: /// <list type="bullet"> /// <item>Editing tables interactively, by user using the mouse or key.</item> /// <item>Editing tables programmatically, by sending commands to the TableDesigner plugin.</item> /// </list> /// In both usage scenarios it's recommended to add a few basic features to your editor project: /// <example> /// Activating the editor and making tables visible by using build-in functionality: /// <code> /// this.htmlEditor.InvokeCommand(this.tableDesigner1.Commands.Activate); /// this.htmlEditor.InvokeCommand(this.tableDesigner1.Commands.AddBehaviors); /// this.htmlEditor.BordersVisible = false; /// this.tableDesigner1.TableBecomesInactive -= new GuruComponents.Netrix.TableDesigner.TableEventBecomesInactiveHandler(this.tableDesigner1_TableBecomesInactive); /// this.tableDesigner1.TableBecomesActive -= new GuruComponents.Netrix.TableDesigner.TableEventBecomesActiveHandler(this.tableDesigner1_TableBecomesActive); /// this.tableDesigner1.TableBecomesInactive += new GuruComponents.Netrix.TableDesigner.TableEventBecomesInactiveHandler(this.tableDesigner1_TableBecomesInactive); /// this.tableDesigner1.TableBecomesActive += new GuruComponents.Netrix.TableDesigner.TableEventBecomesActiveHandler(this.tableDesigner1_TableBecomesActive); /// </code> /// The commands invokes first activate the designer and the build-in border behavior makes the tables visible, even with no borders. /// Then, the internal (default) table border feature of the NetRix control is switched off. Otherwise both borders will overlap, /// which is usually not very helpful. /// Finally, two events being attached to interact with the table designer. The handler usually activate/deactive tools, menu items /// or dialogs used to invoke table related commands. If the user clicks a menu item or tool, you need to invoke a command to /// perform the required action against a table: /// <code> /// this.htmlEditor.InvokeCommand(this.tableDesigner1.Commands.InsertTableRowAfter); /// </code> /// Invoking commands is done via the NetRix editor, which holds the current table. That way we support multiple editors on a /// form with one instance of the table designer only. The commands collection contains available commands. These are being send /// using the editor's InvokeCommand method. Available commands are described <see cref="TableCommands">here</see>. /// </example> /// Note: More information about user driven designer features are available in the manual. /// </remarks> /// <seealso cref="TableDesignerProperties"/> /// <seealso cref="TableCommands"/> [ToolboxItem(true)] [ToolboxBitmap(typeof(GuruComponents.Netrix.TableDesigner.TableDesigner), "Resources.TableDesigner.ico")] [ProvideProperty("TableDesigner", "GuruComponents.Netrix.IHtmlEditor")] public class TableDesigner : Component, System.ComponentModel.IExtenderProvider, GuruComponents.Netrix.PlugIns.IPlugIn { private Hashtable properties; private Hashtable behaviors; /// <summary> /// Default constructor supports design time behavior. /// </summary> public TableDesigner() { properties = new Hashtable(); behaviors = new Hashtable(); } /// <summary> /// This constructor supports design time behavior. /// </summary> /// <param name="parent"></param> public TableDesigner(IContainer parent) : this() { properties = new Hashtable(); parent.Add(this); } private TableDesignerProperties EnsurePropertiesExists(IHtmlEditor key) { TableDesignerProperties p = (TableDesignerProperties) properties[key]; if (p == null) { p = new TableDesignerProperties(); properties[key] = p; } return p; } private TableEditDesigner EnsureBehaviorExists(IHtmlEditor key) { TableEditDesigner b = (TableEditDesigner) behaviors[key]; if (b == null) { b = new TableEditDesigner(key as IHtmlEditor, EnsurePropertiesExists(key), this); behaviors[key] = b; } return b; } # region Events /// <summary> /// Called if the context menu is up to show. /// </summary> /// <remarks>Fires the <see cref="ShowContextMenu"/> event, if not overriden in derived classes.</remarks> /// <seealso cref="ShowContextMenuEventArgs"/> /// <param name="clientX">X coordinate of mouse.</param> /// <param name="clientY">Y coodinate of mouse.</param> /// <param name="t">Element causing the context menu to show up.</param> /// <param name="key">Reference to HTML editor causes the event within the table designer.</param> protected internal void OnShowContextMenu(int clientX, int clientY, Interop.IHTMLElement t, IHtmlEditor key) { if (ShowContextMenu != null) { ShowContextMenuEventArgs cme = new ShowContextMenuEventArgs( new Point(clientX, clientY), false, (int)MenuIdentifier.Table, key.GenericElementFactory.CreateElement(t)); ShowContextMenu(this, cme); } } /// <summary> /// Called if a table becomes active. /// </summary> /// <param name="e"></param> protected internal void OnTableBecomesActive(TableEventArgs e) { if (TableBecomesActive != null) { TableBecomesActive(e); } } /// <summary> /// Called if a table becomes inactive. /// </summary> /// <param name="e"></param> protected internal void OnTableBecomesInactive(TableEventArgs e) { if (TableBecomesInactive != null) { TableBecomesInactive(e); } } /// <summary> /// Called after cell seletions. /// </summary> /// <param name="e"></param> protected internal void OnTableCellSelection(TableCellSelectionEventArgs e) { if (TableCellSelection != null) { TableCellSelection(e); } } /// <summary> /// Called after cell selection is being removed. /// </summary> /// <param name="e"></param> protected internal void OnTableCellSelectionRemoved(TableCellSelectionEventArgs e) { if (TableCellSelectionRemoved != null) { TableCellSelectionRemoved(e); } } /// <summary> /// Will fire if the user has made a cell selection. /// </summary> /// <remarks> /// This informs the handler that operations based /// on selections are now possible. /// </remarks> [Category("NetRix Events"), Description("Will fire if the user has made a cell selection.")] public event TableCellSelectionEventHandler TableCellSelection; /// <summary> /// Will fire if the selection was removed from the table and the cellstack is cleared. /// </summary> [Category("NetRix Events"), Description("Will fire if the selection was removed from the table and the cellstack is cleared.")] public event TableCellSelectionEventHandler TableCellSelectionRemoved; /// <summary> /// Fired if a table becomes active in table designer mode. /// </summary> /// <remarks> /// This happens by key operations inside the table only. /// The event is fired on time after entering the table with caret. See <see cref="TableBecomesInactive"/> for a related event. /// </remarks> [Category("NetRix Events"), Description("Fired if a table becomes active in table designer mode.")] public event TableEventBecomesActiveHandler TableBecomesActive; /// <summary> /// Fired if the currently active table becomes inactive. /// </summary> /// <remarks> /// The occurence of this events means that the caret is placed outside the table. If the caret /// left the current table and enters another one the event is still fired. /// </remarks> [Category("NetRix Events"), Description("Fired if the currently active table becomes inactive.")] public event TableEventBecomesInactiveHandler TableBecomesInactive; /// <summary> /// Fired if the user tries to show up the context menu above a table. /// </summary> [Category("NetRix Events"), Description("Fired if the user tries to show up the context menu above a table.")] public event ShowContextMenuEventHandler ShowContextMenu; # endregion # region ExtenderProvider Code /// <summary> /// Designer method, returns the properties of the attached editor. /// </summary> /// <param name="htmlEditor">The HtmlEditor to what the table designer belongs to.</param> /// <returns>The property object.</returns> [ExtenderProvidedProperty(), Category("NetRix Component"), Description("HelpLine Properties")] [TypeConverter(typeof(ExpandableObjectConverter))] public TableDesignerProperties GetTableDesigner(IHtmlEditor htmlEditor) { return this.EnsurePropertiesExists(htmlEditor); } /// <summary> /// Designer method, sets the properties for given editor. /// </summary> /// <param name="htmlEditor">The HtmlEditor to what the table designer belongs to.</param> /// <param name="Properties">The Property object.</param> /// <returns>The property object.</returns> public void SetTableDesigner(IHtmlEditor htmlEditor, TableDesignerProperties Properties) { // assutre that only first call sets alls values if (properties[htmlEditor] == null) { EnsurePropertiesExists(htmlEditor).Active = Properties.Active; EnsurePropertiesExists(htmlEditor).FastResizeMode = Properties.FastResizeMode; EnsurePropertiesExists(htmlEditor).ProcessTABKey = Properties.ProcessTABKey; EnsurePropertiesExists(htmlEditor).SliderActivated = Properties.SliderActivated; EnsurePropertiesExists(htmlEditor).SliderAddMode = Properties.SliderAddMode; EnsurePropertiesExists(htmlEditor).SliderLine = Properties.SliderLine; EnsurePropertiesExists(htmlEditor).TableBackground = Properties.TableBackground; EnsurePropertiesExists(htmlEditor).WithCellSelection = Properties.WithCellSelection; EnsurePropertiesExists(htmlEditor).AdvancedParameters = Properties.AdvancedParameters; EnsurePropertiesExists(htmlEditor).TableBorder = Properties.TableBorder; EnsurePropertiesExists(htmlEditor).CellBorder = Properties.CellBorder; EnsurePropertiesExists(htmlEditor).StaticBehavior = Properties.StaticBehavior; EnsurePropertiesExists(htmlEditor).CellSelectionBorderColor = Properties.CellSelectionBorderColor; EnsurePropertiesExists(htmlEditor).CellSelectionColor = Properties.CellSelectionColor; htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.AddBehaviors)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.RemoveBehaviors)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.Activate)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.DeActivate)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.AddCaption)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.RemoveCaption)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.DeleteTableRow)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.DeleteTableColumn)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.InsertTableRow)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.InsertTableRowAfter)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.InsertTableColumn)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.InsertTableColumnAfter)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.MergeLeft)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.MergeRight)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.MergeCells)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.MergeCellsPreserveContent)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.MergeUp)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.MergeDown)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.InsertCell)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.DeleteCell)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.SplitHorizontal)); htmlEditor.AddCommand(new CommandWrapper(new EventHandler(TableOperation), Commands.SplitVertical)); } else { EnsurePropertiesExists(htmlEditor).Active = Properties.Active; EnsurePropertiesExists(htmlEditor).FastResizeMode = Properties.FastResizeMode; EnsurePropertiesExists(htmlEditor).ProcessTABKey = Properties.ProcessTABKey; EnsurePropertiesExists(htmlEditor).SliderActivated = Properties.SliderActivated; EnsurePropertiesExists(htmlEditor).SliderAddMode = Properties.SliderAddMode; EnsurePropertiesExists(htmlEditor).SliderLine = Properties.SliderLine; EnsurePropertiesExists(htmlEditor).TableBackground = Properties.TableBackground; EnsurePropertiesExists(htmlEditor).WithCellSelection = Properties.WithCellSelection; EnsurePropertiesExists(htmlEditor).TableBorder = Properties.TableBorder; EnsurePropertiesExists(htmlEditor).CellBorder = Properties.CellBorder; EnsurePropertiesExists(htmlEditor).StaticBehavior = Properties.StaticBehavior; EnsurePropertiesExists(htmlEditor).CellSelectionBorderColor = Properties.CellSelectionBorderColor; EnsurePropertiesExists(htmlEditor).CellSelectionColor = Properties.CellSelectionColor; } // Register htmlEditor.RegisterPlugIn(this); // Set behaviors is requested htmlEditor.AddEditDesigner(EnsureBehaviorExists(htmlEditor) as Interop.IHTMLEditDesigner); } # region Direct Property Settings During Runtime /// <summary> /// Activates of deactivates the table designer. /// </summary> /// <param name="htmlEditor">The editor this designer instance belongs too.</param> /// <param name="active">The mode to select (<c>true</c> = activated, <c>false</c> = deactivated).</param> public void SetActive(IHtmlEditor htmlEditor, bool active) { EnsurePropertiesExists(htmlEditor).Active = active; EnsureBehaviorExists(htmlEditor).SetProperties(EnsurePropertiesExists(htmlEditor)); } /// <summary> /// Activates of deactivates the table designer's fast resize mode. /// </summary> /// <param name="htmlEditor">The editor this designer instance belongs too.</param> /// <param name="mode">The mode to select (<c>true</c> = activated, <c>false</c> = deactivated).</param> public void SetFastResizeMode(IHtmlEditor htmlEditor, bool mode) { EnsurePropertiesExists(htmlEditor).FastResizeMode = mode; EnsureBehaviorExists(htmlEditor).SetProperties(EnsurePropertiesExists(htmlEditor)); } /// <summary> /// Activates of deactivates the table designer's tab key mode. /// </summary> /// <param name="htmlEditor">The editor this designer instance belongs too.</param> /// <param name="recognizeTAB">The mode to select (<c>true</c> = activated, <c>false</c> = deactivated).</param> public void SetProcessTABKey(IHtmlEditor htmlEditor, bool recognizeTAB) { EnsurePropertiesExists(htmlEditor).ProcessTABKey = recognizeTAB; EnsureBehaviorExists(htmlEditor).SetProperties(EnsurePropertiesExists(htmlEditor)); } /// <summary> /// Activates of deactivates the table designer's slider mode. /// </summary> /// <param name="htmlEditor">The editor this designer instance belongs too.</param> /// <param name="active">The mode to select (<c>true</c> = activated, <c>false</c> = deactivated).</param> public void SetSliderActivated(IHtmlEditor htmlEditor, bool active) { EnsurePropertiesExists(htmlEditor).SliderActivated = active; EnsureBehaviorExists(htmlEditor).SetProperties(EnsurePropertiesExists(htmlEditor)); } /// <summary> /// Activates of deactivates the table designer's add mode. /// </summary> /// <remarks> /// The add mode determines how the resize of the right most column and the right outer border. /// Usually the table is not being resized if the last column width is being changed. If the add mode /// is activated, the right most column will grow and the table width is growing accordingly. /// </remarks> /// <param name="htmlEditor">The editor this designer instance belongs too.</param> /// <param name="addMode">The mode to select (<c>true</c> = activated, <c>false</c> = deactivated).</param> public void SetAddMode(IHtmlEditor htmlEditor, bool addMode) { EnsurePropertiesExists(htmlEditor).SliderAddMode = addMode; EnsureBehaviorExists(htmlEditor).SetProperties(EnsurePropertiesExists(htmlEditor)); } /// <summary> /// Activates of deactivates the table designer's advanced mode. /// </summary> /// <remarks> /// The advanced mode shows additional properties concerning the current cell properties as well as /// rulers and other information about table dimensions. This option requires higher performance (we /// recommend at least 2 GHz). /// </remarks> /// <param name="htmlEditor">The editor this designer instance belongs too.</param> /// <param name="advModeOn">The mode to select (<c>true</c> = activated, <c>false</c> = deactivated).</param> public void SetAdvancedMode(IHtmlEditor htmlEditor, bool advModeOn) { EnsurePropertiesExists(htmlEditor).AdvancedParameters = advModeOn; EnsureBehaviorExists(htmlEditor).SetProperties(EnsurePropertiesExists(htmlEditor)); } /// <summary> /// Activates of deactivates the table designer's slider line properties. /// </summary> /// <param name="htmlEditor">The editor this designer instance belongs too.</param> /// <param name="sliderLine">The mode to select (<c>true</c> = activated, <c>false</c> = deactivated).</param> public void SetSliderLine(IHtmlEditor htmlEditor, GuruComponents.Netrix.TableDesigner.TableDesignerProperties.SliderLineProperty sliderLine) { EnsurePropertiesExists(htmlEditor).SliderLine = sliderLine; EnsureBehaviorExists(htmlEditor).SetProperties(EnsurePropertiesExists(htmlEditor)); } /// <summary> /// Activates of deactivates the table designer's background properties. /// </summary> /// <param name="htmlEditor">The editor this designer instance belongs too.</param> /// <param name="backGround">The mode to select (<c>true</c> = activated, <c>false</c> = deactivated).</param> public void SetTableBackGround(IHtmlEditor htmlEditor, Color backGround) { EnsurePropertiesExists(htmlEditor).TableBackground = backGround; EnsureBehaviorExists(htmlEditor).SetProperties(EnsurePropertiesExists(htmlEditor)); } /// <summary> /// Activates of deactivates the table designer's cell selection properties. /// </summary> /// <param name="htmlEditor">The editor this designer instance belongs too.</param> /// <param name="withSelection">The mode to select (<c>true</c> = activated, <c>false</c> = deactivated).</param> public void SetWithCellSelection(IHtmlEditor htmlEditor, bool withSelection) { EnsurePropertiesExists(htmlEditor).WithCellSelection = withSelection; EnsureBehaviorExists(htmlEditor).SetProperties(EnsurePropertiesExists(htmlEditor)); } /// <summary> /// Activates of deactivates the table designer's border properties. /// </summary> /// <param name="htmlEditor">The editor this designer instance belongs too.</param> /// <param name="tableBorder">The mode to select (<c>true</c> = activated, <c>false</c> = deactivated).</param> public void SetTableBorder(IHtmlEditor htmlEditor, GuruComponents.Netrix.TableDesigner.TableDesignerProperties.TableBorderBehavior tableBorder) { EnsurePropertiesExists(htmlEditor).TableBorder = tableBorder; EnsureBehaviorExists(htmlEditor).SetProperties(EnsurePropertiesExists(htmlEditor)); } /// <summary> /// Activates of deactivates the table designer's cell properties. /// </summary> /// <remarks> /// This belongs to cell in non selected mode. /// </remarks> /// <param name="htmlEditor">The editor this designer instance belongs too.</param> /// <param name="cellBorder">The .</param> public void SetCellBorder(IHtmlEditor htmlEditor, GuruComponents.Netrix.TableDesigner.TableDesignerProperties.CellBorderBehavior cellBorder) { EnsurePropertiesExists(htmlEditor).CellBorder = cellBorder; EnsureBehaviorExists(htmlEditor).SetProperties(EnsurePropertiesExists(htmlEditor)); } /// <summary> /// Activates of deactivates the table designer's static mode. /// </summary> /// <param name="htmlEditor">The editor this designer instance belongs too.</param> /// <param name="staticBehavior">The mode to select (<c>true</c> = activated, <c>false</c> = deactivated).</param> public void SetStaticBehavior(IHtmlEditor htmlEditor, bool staticBehavior) { EnsurePropertiesExists(htmlEditor).StaticBehavior = staticBehavior; EnsureBehaviorExists(htmlEditor).SetProperties(EnsurePropertiesExists(htmlEditor)); } /// <summary> /// Activates of deactivates the table designer's cell selection border color. /// </summary> /// <param name="htmlEditor">The editor this designer instance belongs too.</param> /// <param name="cellBorder">The cell border color for selected mode.</param> public void SetCellSelectionBorderColor(IHtmlEditor htmlEditor, Color cellBorder) { EnsurePropertiesExists(htmlEditor).CellSelectionBorderColor = cellBorder; EnsureBehaviorExists(htmlEditor).SetProperties(EnsurePropertiesExists(htmlEditor)); } /// <summary> /// Activates of deactivates the table designer's cell selection color. /// </summary> /// <param name="htmlEditor">The editor this designer instance belongs too.</param> /// <param name="cellSelection">The cell color in selected mode.</param> public void SetCellSelectionColor(IHtmlEditor htmlEditor, Color cellSelection) { EnsurePropertiesExists(htmlEditor).CellSelectionColor = cellSelection; EnsureBehaviorExists(htmlEditor).SetProperties(EnsurePropertiesExists(htmlEditor)); } # endregion private TableCommands commands; /// <summary> /// Gives access to the commands the table designer accepts via the Invoke call. /// </summary> [Browsable(false)] public TableCommands Commands { get { if (commands == null) { commands = new TableCommands(); } return commands; } } /// <summary> /// Sets the current table and cell explicitly. /// </summary> /// <remarks> /// The host can use this method to force setting the current table and cell to allow /// any table formatting operation issued by the table designer working with that table, /// instead of the user selected one. /// <para> /// Setting the cell is necessary, because many commands use the current cell as a starting /// point for there operation. /// </para> /// <para> /// Calling this method will not fire the <see cref="TableBecomesActive"/> event. Additionally, /// the designer and the formatter stay no longer in sync regarding the used table. /// </para> /// </remarks> /// <param name="editor">The editor instance, from which the table element comes.</param> /// <param name="table">The table, which has to be set.</param> /// <param name="cell">The cell within the table.</param> public void SetFormatter(IHtmlEditor editor, TableElement table, TableCellElement cell) { EnsureBehaviorExists(editor).TableFormatter.TableInfo = null; ((TableFormatter)EnsureBehaviorExists(editor).TableFormatter).CurrentTable = (Interop.IHTMLTable) table.GetBaseElement(); ((TableFormatter)EnsureBehaviorExists(editor).TableFormatter).CurrentCell = cell; } /// <summary> /// Detects whether the editor has a current table. /// </summary> /// <remarks> /// This information is useful to update related menu items or toolbars. /// </remarks> /// <param name="editor">The editor this operation refers to.</param> /// <returns>Returns <c>true</c>, if the table designer has a current table.</returns> public bool IsInTable(IHtmlEditor editor) { return (EnsureBehaviorExists(editor).CurrentTable != null) ? true : false; } /// <summary> /// Put the formatter back into automatic detection mode. /// </summary> /// <remarks> /// Any caller of the <see cref="TableFormatter.CurrentTable"/> or <see cref="TableFormatter.CurrentCell"/> is supposed to call this method to /// put the formatter back into detection mode. This means, that the current table follows the /// mouse and as soon as a mouse move appears on top of a table the current table changes. /// </remarks> /// <param name="editor"></param> public void ResetFormatter(IHtmlEditor editor) { EnsureBehaviorExists(editor).TableFormatter.TableInfo = null; } /// <summary> /// Gets direct access to the formatter. /// </summary> /// <param name="editor"></param> /// <returns></returns> public ITableFormatter GetFormatter(IHtmlEditor editor) { return EnsureBehaviorExists(editor).TableFormatter; } private void TableOperation(object sender, EventArgs e) { CommandWrapper cw = (CommandWrapper) sender; if (cw.CommandID.Guid.Equals(Commands.CommandGroup)) { switch ((TableCommand)cw.ID) { case TableCommand.Activate: EnsureBehaviorExists(cw.TargetEditor).Activate(true); break; case TableCommand.DeActivate: EnsureBehaviorExists(cw.TargetEditor).Activate(false); break; case TableCommand.AddBehaviors: EnsureBehaviorExists(cw.TargetEditor).AddBehaviors(); break; case TableCommand.RemoveBehaviors: EnsureBehaviorExists(cw.TargetEditor).RemoveBehaviors(); break; case TableCommand.AddCaption: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.AddCaption(); break; case TableCommand.RemoveCaption: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.RemoveCaption(); break; case TableCommand.DeleteTableRow: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.DeleteTableRow(); break; case TableCommand.DeleteTableColumn: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.DeleteTableColumn(); break; case TableCommand.InsertTableRow: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.InsertTableRow(false); break; case TableCommand.InsertTableRowAfter: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.InsertTableRow(true); break; case TableCommand.InsertTableColumn: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.InsertTableColumn(false); break; case TableCommand.InsertTableColumnAfter: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.InsertTableColumn(true); break; case TableCommand.MergeLeft: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.MergeLeft(); break; case TableCommand.MergeRight: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.MergeRight(); break; case TableCommand.MergeCells: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.MergeCells(); break; case TableCommand.MergeCellsPreserveContent: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.MergeCells(true); break; case TableCommand.MergeUp: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.MergeUp(); break; case TableCommand.MergeDown: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.MergeDown(); break; case TableCommand.InsertCell: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.InsertCell(); break; case TableCommand.DeleteCell: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.DeleteCell(); break; case TableCommand.SplitHorizontal: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.SplitHorizontal(); break; case TableCommand.SplitVertical: EnsureBehaviorExists(cw.TargetEditor).TableFormatter.SplitVertical(); break; } } } /// <summary> /// Called by the main control to inform the plug-in that the content is now ready. /// </summary> /// <remarks>THIS METHOD MUST NOT BE CALLED FROM USER CODE.</remarks> /// <param name="editor"></param> public void NotifyReadyStateCompleted(IHtmlEditor editor) { if (EnsureBehaviorExists(editor).IsActivated && EnsurePropertiesExists(editor).StaticBehavior) { EnsureBehaviorExists(editor).AddBehaviors(); } if (NotifySubReadyStateCompleted != null) { NotifySubReadyStateCompleted(editor, EventArgs.Empty); } } internal event EventHandler NotifySubReadyStateCompleted; /// <summary> /// Version of Plug-in Assembly. /// </summary> [Browsable(true), ReadOnly(true), Description("Version of Plug-in Assembly.")] public string Version { get { return this.GetType().Assembly.GetName().Version.ToString(); } } /// <summary> /// Indicated whether the designer should serialize the property object. /// </summary> /// <param name="htmlEditor">Reference to editor the designer belongs to.</param> /// <returns>True in any case (constant value).</returns> public bool ShouldSerializeTableDesigner(IHtmlEditor htmlEditor) { return true; } # endregion #region IExtenderProvider Member /// <summary> /// Indicates that the plugin can extend the NetRix HTML editor component. /// </summary> /// <param name="extendee"></param> /// <returns></returns> public bool CanExtend(object extendee) { if (extendee is IHtmlEditor) { return true; } else { return false; } } #endregion /// <summary> /// Designer support. /// </summary> /// <returns>String visible in PropertyGrid.</returns> public override string ToString() { return "Click plus sign for details"; } /// <summary> /// Name of the Plugin, constant "TableDesigner". /// </summary> #region IPlugIn Member [Browsable(true)] public string Name { get { return "TableDesigner"; } } /// <summary> /// Informs that this is an ExtenderProvider. Always true. /// </summary> [Browsable(false)] public bool IsExtenderProvider { get { return true; } } /// <summary> /// Type of component. /// </summary> [Browsable(false)] public Type Type { get { return this.GetType(); } } /// <summary> /// List of element types, which the extender plugin extends. /// </summary> /// <remarks> /// See <see cref="GuruComponents.Netrix.PlugIns.IPlugIn.GetElementExtenders"/> for background information. /// </remarks> public List<CommandExtender> GetElementExtenders(IElement component) { List<CommandExtender> extenderVerbs = new List<CommandExtender>(); switch (component.GetType().Name) { case "TableElement": extenderVerbs.AddRange(GetTblCommands()); break; case "TableCellElement": extenderVerbs.AddRange(GetCellCommands()); break; } return extenderVerbs; } private IEnumerable<CommandExtender> GetCellCommands() { List<CommandExtender> lc = new List<CommandExtender>(); CommandExtender cdel = new CommandExtender(Commands.DeleteCell); cdel.Text = "Remove Cell"; cdel.Description = "Removes the cell from table"; lc.Add(cdel); CommandExtender cadd = new CommandExtender(Commands.InsertCell); cadd.Text = "Add Cell"; cadd.Description = "Add the cell from table"; lc.Add(cadd); return lc; } private IEnumerable<CommandExtender> GetTblCommands() { List<CommandExtender> lc = new List<CommandExtender>(); CommandExtender c1 = new CommandExtender(Commands.InsertTableRow); c1.Text = "Insert Row Before"; c1.Description = "Insert Row Before"; lc.Add(c1); CommandExtender c2 = new CommandExtender(Commands.InsertTableRowAfter); c2.Text = "Insert Row After"; c2.Description = "Insert Row After"; lc.Add(c2); CommandExtender c3 = new CommandExtender(Commands.InsertTableColumn); c3.Text = "Insert Column Before"; c3.Description = "Insert Column Before"; lc.Add(c3); CommandExtender c4 = new CommandExtender(Commands.InsertTableColumnAfter); c4.Text = "Insert Column After"; c4.Description = "Insert Column After"; lc.Add(c4); return lc; } /// <summary> /// Returns element specific features this plug-in supports. /// </summary> public Feature Features { get { return Feature.EditDesigner; } } /// <summary> /// Returns supported namespaces. /// </summary> /// <returns>Returns null, the table designer does not support namespaces.</returns> IDictionary GuruComponents.Netrix.PlugIns.IPlugIn.GetSupportedNamespaces(IHtmlEditor editor) { return null; } /// <summary> /// Creates an element. /// </summary> /// <remarks> /// Throws always a <see cref="NotSupportedException"/>. /// </remarks> /// <exception cref="NotSupportedException">The table designer cannot create elements that way.</exception> /// <param name="tagName"></param> /// <param name="editor"></param> /// <returns></returns> System.Web.UI.Control IPlugIn.CreateElement(string tagName, IHtmlEditor editor) { throw new NotSupportedException("The method or operation is not available. Use commands instead"); } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using osu.Framework.Allocation; using osu.Framework.Extensions.EnumExtensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Primitives; using osu.Framework.Graphics.UserInterface; using osu.Framework.Utils; using osu.Game.Extensions; using osu.Game.Graphics.UserInterface; using osu.Game.Rulesets.Edit; using osu.Game.Screens.Edit.Compose.Components; using osuTK; namespace osu.Game.Skinning.Editor { public class SkinSelectionHandler : SelectionHandler<ISkinnableDrawable> { [Resolved] private SkinEditor skinEditor { get; set; } public override bool HandleRotation(float angle) { if (SelectedBlueprints.Count == 1) { // for single items, rotate around the origin rather than the selection centre. ((Drawable)SelectedBlueprints.First().Item).Rotation += angle; } else { var selectionQuad = getSelectionQuad(); foreach (var b in SelectedBlueprints) { var drawableItem = (Drawable)b.Item; var rotatedPosition = RotatePointAroundOrigin(b.ScreenSpaceSelectionPoint, selectionQuad.Centre, angle); updateDrawablePosition(drawableItem, rotatedPosition); drawableItem.Rotation += angle; } } // this isn't always the case but let's be lenient for now. return true; } public override bool HandleScale(Vector2 scale, Anchor anchor) { // convert scale to screen space scale = ToScreenSpace(scale) - ToScreenSpace(Vector2.Zero); adjustScaleFromAnchor(ref scale, anchor); // the selection quad is always upright, so use an AABB rect to make mutating the values easier. var selectionRect = getSelectionQuad().AABBFloat; // If the selection has no area we cannot scale it if (selectionRect.Area == 0) return false; // copy to mutate, as we will need to compare to the original later on. var adjustedRect = selectionRect; // first, remove any scale axis we are not interested in. if (anchor.HasFlagFast(Anchor.x1)) scale.X = 0; if (anchor.HasFlagFast(Anchor.y1)) scale.Y = 0; bool shouldAspectLock = // for now aspect lock scale adjustments that occur at corners.. (!anchor.HasFlagFast(Anchor.x1) && !anchor.HasFlagFast(Anchor.y1)) // ..or if any of the selection have been rotated. // this is to avoid requiring skew logic (which would likely not be the user's expected transform anyway). || SelectedBlueprints.Any(b => !Precision.AlmostEquals(((Drawable)b.Item).Rotation, 0)); if (shouldAspectLock) { if (anchor.HasFlagFast(Anchor.x1)) // if dragging from the horizontal centre, only a vertical component is available. scale.X = scale.Y / selectionRect.Height * selectionRect.Width; else // in all other cases (arbitrarily) use the horizontal component for aspect lock. scale.Y = scale.X / selectionRect.Width * selectionRect.Height; } if (anchor.HasFlagFast(Anchor.x0)) adjustedRect.X -= scale.X; if (anchor.HasFlagFast(Anchor.y0)) adjustedRect.Y -= scale.Y; adjustedRect.Width += scale.X; adjustedRect.Height += scale.Y; // scale adjust applied to each individual item should match that of the quad itself. var scaledDelta = new Vector2( adjustedRect.Width / selectionRect.Width, adjustedRect.Height / selectionRect.Height ); foreach (var b in SelectedBlueprints) { var drawableItem = (Drawable)b.Item; // each drawable's relative position should be maintained in the scaled quad. var screenPosition = b.ScreenSpaceSelectionPoint; var relativePositionInOriginal = new Vector2( (screenPosition.X - selectionRect.TopLeft.X) / selectionRect.Width, (screenPosition.Y - selectionRect.TopLeft.Y) / selectionRect.Height ); var newPositionInAdjusted = new Vector2( adjustedRect.TopLeft.X + adjustedRect.Width * relativePositionInOriginal.X, adjustedRect.TopLeft.Y + adjustedRect.Height * relativePositionInOriginal.Y ); updateDrawablePosition(drawableItem, newPositionInAdjusted); drawableItem.Scale *= scaledDelta; } return true; } public override bool HandleFlip(Direction direction) { var selectionQuad = getSelectionQuad(); foreach (var b in SelectedBlueprints) { var drawableItem = (Drawable)b.Item; var flippedPosition = GetFlippedPosition(direction, selectionQuad, b.ScreenSpaceSelectionPoint); updateDrawablePosition(drawableItem, flippedPosition); drawableItem.Scale *= new Vector2( direction == Direction.Horizontal ? -1 : 1, direction == Direction.Vertical ? -1 : 1 ); } return true; } public override bool HandleMovement(MoveSelectionEvent<ISkinnableDrawable> moveEvent) { foreach (var c in SelectedBlueprints) { var item = c.Item; Drawable drawable = (Drawable)item; drawable.Position += drawable.ScreenSpaceDeltaToParentSpace(moveEvent.ScreenSpaceDelta); if (item.UsesFixedAnchor) continue; applyClosestAnchor(drawable); } return true; } private static void applyClosestAnchor(Drawable drawable) => applyAnchor(drawable, getClosestAnchor(drawable)); protected override void OnSelectionChanged() { base.OnSelectionChanged(); SelectionBox.CanRotate = true; SelectionBox.CanScaleX = true; SelectionBox.CanScaleY = true; SelectionBox.CanReverse = false; } protected override void DeleteItems(IEnumerable<ISkinnableDrawable> items) => skinEditor.DeleteItems(items.ToArray()); protected override IEnumerable<MenuItem> GetContextMenuItemsForSelection(IEnumerable<SelectionBlueprint<ISkinnableDrawable>> selection) { var closestItem = new TernaryStateRadioMenuItem("Closest", MenuItemType.Standard, _ => applyClosestAnchors()) { State = { Value = GetStateFromSelection(selection, c => !c.Item.UsesFixedAnchor) } }; yield return new OsuMenuItem("Anchor") { Items = createAnchorItems((d, a) => d.UsesFixedAnchor && ((Drawable)d).Anchor == a, applyFixedAnchors) .Prepend(closestItem) .ToArray() }; yield return new OsuMenuItem("Origin") { Items = createAnchorItems((d, o) => ((Drawable)d).Origin == o, applyOrigins).ToArray() }; foreach (var item in base.GetContextMenuItemsForSelection(selection)) yield return item; IEnumerable<TernaryStateMenuItem> createAnchorItems(Func<ISkinnableDrawable, Anchor, bool> checkFunction, Action<Anchor> applyFunction) { var displayableAnchors = new[] { Anchor.TopLeft, Anchor.TopCentre, Anchor.TopRight, Anchor.CentreLeft, Anchor.Centre, Anchor.CentreRight, Anchor.BottomLeft, Anchor.BottomCentre, Anchor.BottomRight, }; return displayableAnchors.Select(a => { return new TernaryStateRadioMenuItem(a.ToString(), MenuItemType.Standard, _ => applyFunction(a)) { State = { Value = GetStateFromSelection(selection, c => checkFunction(c.Item, a)) } }; }); } } private static void updateDrawablePosition(Drawable drawable, Vector2 screenSpacePosition) { drawable.Position = drawable.Parent.ToLocalSpace(screenSpacePosition) - drawable.AnchorPosition; } private void applyOrigins(Anchor origin) { foreach (var item in SelectedItems) { var drawable = (Drawable)item; if (origin == drawable.Origin) continue; var previousOrigin = drawable.OriginPosition; drawable.Origin = origin; drawable.Position += drawable.OriginPosition - previousOrigin; if (item.UsesFixedAnchor) continue; applyClosestAnchor(drawable); } } /// <summary> /// A screen-space quad surrounding all selected drawables, accounting for their full displayed size. /// </summary> /// <returns></returns> private Quad getSelectionQuad() => GetSurroundingQuad(SelectedBlueprints.SelectMany(b => b.Item.ScreenSpaceDrawQuad.GetVertices().ToArray())); private void applyFixedAnchors(Anchor anchor) { foreach (var item in SelectedItems) { var drawable = (Drawable)item; item.UsesFixedAnchor = true; applyAnchor(drawable, anchor); } } private void applyClosestAnchors() { foreach (var item in SelectedItems) { item.UsesFixedAnchor = false; applyClosestAnchor((Drawable)item); } } private static Anchor getClosestAnchor(Drawable drawable) { var parent = drawable.Parent; if (parent == null) return drawable.Anchor; var screenPosition = getScreenPosition(); var absolutePosition = parent.ToLocalSpace(screenPosition); var factor = parent.RelativeToAbsoluteFactor; var result = default(Anchor); static Anchor getAnchorFromPosition(float xOrY, Anchor anchor0, Anchor anchor1, Anchor anchor2) { if (xOrY >= 2 / 3f) return anchor2; if (xOrY >= 1 / 3f) return anchor1; return anchor0; } result |= getAnchorFromPosition(absolutePosition.X / factor.X, Anchor.x0, Anchor.x1, Anchor.x2); result |= getAnchorFromPosition(absolutePosition.Y / factor.Y, Anchor.y0, Anchor.y1, Anchor.y2); return result; Vector2 getScreenPosition() { var quad = drawable.ScreenSpaceDrawQuad; var origin = drawable.Origin; var pos = quad.TopLeft; if (origin.HasFlagFast(Anchor.x2)) pos.X += quad.Width; else if (origin.HasFlagFast(Anchor.x1)) pos.X += quad.Width / 2f; if (origin.HasFlagFast(Anchor.y2)) pos.Y += quad.Height; else if (origin.HasFlagFast(Anchor.y1)) pos.Y += quad.Height / 2f; return pos; } } private static void applyAnchor(Drawable drawable, Anchor anchor) { if (anchor == drawable.Anchor) return; var previousAnchor = drawable.AnchorPosition; drawable.Anchor = anchor; drawable.Position -= drawable.AnchorPosition - previousAnchor; } private static void adjustScaleFromAnchor(ref Vector2 scale, Anchor reference) { // cancel out scale in axes we don't care about (based on which drag handle was used). if ((reference & Anchor.x1) > 0) scale.X = 0; if ((reference & Anchor.y1) > 0) scale.Y = 0; // reverse the scale direction if dragging from top or left. if ((reference & Anchor.x0) > 0) scale.X = -scale.X; if ((reference & Anchor.y0) > 0) scale.Y = -scale.Y; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osuTK.Graphics; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.Sprites; using osuTK; namespace osu.Game.Graphics.UserInterface { public class OsuDropdown<T> : Dropdown<T>, IHasAccentColour { private Color4 accentColour; public Color4 AccentColour { get => accentColour; set { accentColour = value; updateAccentColour(); } } [BackgroundDependencyLoader] private void load(OsuColour colours) { if (accentColour == default) accentColour = colours.PinkDarker; updateAccentColour(); } private void updateAccentColour() { if (Header is IHasAccentColour header) header.AccentColour = accentColour; if (Menu is IHasAccentColour menu) menu.AccentColour = accentColour; } protected override DropdownHeader CreateHeader() => new OsuDropdownHeader(); protected override DropdownMenu CreateMenu() => new OsuDropdownMenu(); #region OsuDropdownMenu protected class OsuDropdownMenu : DropdownMenu, IHasAccentColour { public override bool HandleNonPositionalInput => State == MenuState.Open; // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring public OsuDropdownMenu() { CornerRadius = 4; BackgroundColour = Color4.Black.Opacity(0.5f); // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring ItemsContainer.Padding = new MarginPadding(5); } // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring protected override void AnimateOpen() => this.FadeIn(300, Easing.OutQuint); protected override void AnimateClose() => this.FadeOut(300, Easing.OutQuint); // todo: this uses the same styling as OsuMenu. hopefully we can just use OsuMenu in the future with some refactoring protected override void UpdateSize(Vector2 newSize) { if (Direction == Direction.Vertical) { Width = newSize.X; this.ResizeHeightTo(newSize.Y, 300, Easing.OutQuint); } else { Height = newSize.Y; this.ResizeWidthTo(newSize.X, 300, Easing.OutQuint); } } private Color4 accentColour; public Color4 AccentColour { get => accentColour; set { accentColour = value; foreach (var c in Children.OfType<IHasAccentColour>()) c.AccentColour = value; } } protected override DrawableMenuItem CreateDrawableMenuItem(MenuItem item) => new DrawableOsuDropdownMenuItem(item) { AccentColour = accentColour }; #region DrawableOsuDropdownMenuItem public class DrawableOsuDropdownMenuItem : DrawableDropdownMenuItem, IHasAccentColour { // IsHovered is used public override bool HandlePositionalInput => true; private Color4? accentColour; public Color4 AccentColour { get => accentColour ?? nonAccentSelectedColour; set { accentColour = value; updateColours(); } } private void updateColours() { BackgroundColourHover = accentColour ?? nonAccentHoverColour; BackgroundColourSelected = accentColour ?? nonAccentSelectedColour; UpdateBackgroundColour(); UpdateForegroundColour(); } private Color4 nonAccentHoverColour; private Color4 nonAccentSelectedColour; public DrawableOsuDropdownMenuItem(MenuItem item) : base(item) { Foreground.Padding = new MarginPadding(2); Masking = true; CornerRadius = 6; } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = Color4.Transparent; nonAccentHoverColour = colours.PinkDarker; nonAccentSelectedColour = Color4.Black.Opacity(0.5f); updateColours(); AddInternal(new HoverClickSounds(HoverSampleSet.Soft)); } protected override void UpdateForegroundColour() { base.UpdateForegroundColour(); if (Foreground.Children.FirstOrDefault() is Content content) content.Chevron.Alpha = IsHovered ? 1 : 0; } protected override Drawable CreateContent() => new Content(); protected new class Content : FillFlowContainer, IHasText { public string Text { get => Label.Text; set => Label.Text = value; } public readonly OsuSpriteText Label; public readonly SpriteIcon Chevron; public Content() { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Direction = FillDirection.Horizontal; Children = new Drawable[] { Chevron = new SpriteIcon { AlwaysPresent = true, Icon = FontAwesome.fa_chevron_right, Colour = Color4.Black, Alpha = 0.5f, Size = new Vector2(8), Margin = new MarginPadding { Left = 3, Right = 3 }, Origin = Anchor.CentreLeft, Anchor = Anchor.CentreLeft, }, Label = new OsuSpriteText { Origin = Anchor.CentreLeft, Anchor = Anchor.CentreLeft, }, }; } } } #endregion } #endregion public class OsuDropdownHeader : DropdownHeader, IHasAccentColour { protected readonly SpriteText Text; protected override string Label { get => Text.Text; set => Text.Text = value; } protected readonly SpriteIcon Icon; private Color4 accentColour; public virtual Color4 AccentColour { get => accentColour; set { accentColour = value; BackgroundColourHover = accentColour; } } public OsuDropdownHeader() { Foreground.Padding = new MarginPadding(4); AutoSizeAxes = Axes.None; Margin = new MarginPadding { Bottom = 4 }; CornerRadius = 4; Height = 40; Foreground.Children = new Drawable[] { Text = new OsuSpriteText { Anchor = Anchor.CentreLeft, Origin = Anchor.CentreLeft, }, Icon = new SpriteIcon { Icon = FontAwesome.fa_chevron_down, Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, Margin = new MarginPadding { Right = 4 }, Size = new Vector2(20), }, }; AddInternal(new HoverClickSounds()); } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = Color4.Black.Opacity(0.5f); BackgroundColourHover = colours.PinkDarker; } } } }
using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.Rdbms; using Umbraco.Tests.TestHelpers; using Umbraco.Tests.TestHelpers.Entities; namespace Umbraco.Tests.Services { [DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)] [TestFixture, RequiresSTA] public class ContentTypeServiceTests : BaseServiceTest { [SetUp] public override void Initialize() { base.Initialize(); } [TearDown] public override void TearDown() { base.TearDown(); } [Test] public void Deleting_PropertyType_Removes_The_Property_From_Content() { IContentType contentType1 = MockedContentTypes.CreateTextpageContentType("test1", "Test1"); ServiceContext.ContentTypeService.Save(contentType1); IContent contentItem = MockedContent.CreateTextpageContent(contentType1, "Testing", -1); ServiceContext.ContentService.SaveAndPublish(contentItem); var initProps = contentItem.Properties.Count; var initPropTypes = contentItem.PropertyTypes.Count(); //remove a property contentType1.RemovePropertyType(contentType1.PropertyTypes.First().Alias); ServiceContext.ContentTypeService.Save(contentType1); //re-load it from the db contentItem = ServiceContext.ContentService.GetById(contentItem.Id); Assert.AreEqual(initPropTypes - 1, contentItem.PropertyTypes.Count()); Assert.AreEqual(initProps -1, contentItem.Properties.Count); } [Test] public void Rebuild_Content_Xml_On_Alias_Change() { var contentType1 = MockedContentTypes.CreateTextpageContentType("test1", "Test1"); var contentType2 = MockedContentTypes.CreateTextpageContentType("test2", "Test2"); ServiceContext.ContentTypeService.Save(contentType1); ServiceContext.ContentTypeService.Save(contentType2); var contentItems1 = MockedContent.CreateTextpageContent(contentType1, -1, 10).ToArray(); contentItems1.ForEach(x => ServiceContext.ContentService.SaveAndPublish(x)); var contentItems2 = MockedContent.CreateTextpageContent(contentType2, -1, 5).ToArray(); contentItems2.ForEach(x => ServiceContext.ContentService.SaveAndPublish(x)); //only update the contentType1 alias which will force an xml rebuild for all content of that type contentType1.Alias = "newAlias"; ServiceContext.ContentTypeService.Save(contentType1); foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.StartsWith("<newAlias")); } foreach (var c in contentItems2) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.StartsWith("<test2")); //should remain the same } } [Test] public void Rebuild_Content_Xml_On_Property_Removal() { var contentType1 = MockedContentTypes.CreateTextpageContentType("test1", "Test1"); ServiceContext.ContentTypeService.Save(contentType1); var contentItems1 = MockedContent.CreateTextpageContent(contentType1, -1, 10).ToArray(); contentItems1.ForEach(x => ServiceContext.ContentService.SaveAndPublish(x)); var alias = contentType1.PropertyTypes.First().Alias; var elementToMatch = "<" + alias + ">"; foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsTrue(xml.Xml.Contains(elementToMatch)); //verify that it is there before we remove the property } //remove a property contentType1.RemovePropertyType(contentType1.PropertyTypes.First().Alias); ServiceContext.ContentTypeService.Save(contentType1); var reQueried = ServiceContext.ContentTypeService.GetContentType(contentType1.Id); var reContent = ServiceContext.ContentService.GetById(contentItems1.First().Id); foreach (var c in contentItems1) { var xml = DatabaseContext.Database.FirstOrDefault<ContentXmlDto>("WHERE nodeId = @Id", new { Id = c.Id }); Assert.IsNotNull(xml); Assert.IsFalse(xml.Xml.Contains(elementToMatch)); //verify that it is no longer there } } [Test] public void Get_Descendants() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; var hierarchy = CreateContentTypeHierarchy(); contentTypeService.Save(hierarchy, 0); //ensure they are saved! var master = hierarchy.First(); //Act var descendants = master.Descendants(); //Assert Assert.AreEqual(10, descendants.Count()); } [Test] public void Get_Descendants_And_Self() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; var hierarchy = CreateContentTypeHierarchy(); contentTypeService.Save(hierarchy, 0); //ensure they are saved! var master = hierarchy.First(); //Act var descendants = master.DescendantsAndSelf(); //Assert Assert.AreEqual(11, descendants.Count()); } [Test] public void Can_Bulk_Save_New_Hierarchy_Content_Types() { // Arrange var contentTypeService = ServiceContext.ContentTypeService; var hierarchy = CreateContentTypeHierarchy(); // Act contentTypeService.Save(hierarchy, 0); Assert.That(hierarchy.Any(), Is.True); Assert.That(hierarchy.Any(x => x.HasIdentity == false), Is.False); //all parent id's should be ok, they are lazy and if they equal zero an exception will be thrown Assert.DoesNotThrow(() => hierarchy.Any(x => x.ParentId != 0)); for (var i = 0; i < hierarchy.Count(); i++) { if (i == 0) continue; Assert.AreEqual(hierarchy.ElementAt(i).ParentId, hierarchy.ElementAt(i - 1).Id); } } [Test] public void Can_Save_ContentType_Structure_And_Create_Content_Based_On_It() { // Arrange var cs = ServiceContext.ContentService; var cts = ServiceContext.ContentTypeService; var dtdYesNo = ServiceContext.DataTypeService.GetDataTypeDefinitionById(-49); var ctBase = new ContentType(-1) {Name = "Base", Alias = "Base", Icon = "folder.gif", Thumbnail = "folder.png"}; ctBase.AddPropertyType(new PropertyType(dtdYesNo) { Name = "Hide From Navigation", Alias = Constants.Conventions.Content.NaviHide } /*,"Navigation"*/); cts.Save(ctBase); var ctHomePage = new ContentType(ctBase) { Name = "Home Page", Alias = "HomePage", Icon = "settingDomain.gif", Thumbnail = "folder.png", AllowedAsRoot = true }; ctHomePage.AddPropertyType(new PropertyType(dtdYesNo) {Name = "Some property", Alias = "someProperty"} /*,"Navigation"*/); cts.Save(ctHomePage); // Act var homeDoc = cs.CreateContent("Home Page", -1, "HomePage"); cs.SaveAndPublish(homeDoc); // Assert Assert.That(ctBase.HasIdentity, Is.True); Assert.That(ctHomePage.HasIdentity, Is.True); Assert.That(homeDoc.HasIdentity, Is.True); Assert.That(homeDoc.ContentTypeId, Is.EqualTo(ctHomePage.Id)); } [Test] public void Can_Create_And_Save_ContentType_Composition() { /* * Global * - Components * - Category */ var service = ServiceContext.ContentTypeService; var global = MockedContentTypes.CreateSimpleContentType("global", "Global"); service.Save(global); var components = MockedContentTypes.CreateSimpleContentType("components", "Components", global); service.Save(components); var component = MockedContentTypes.CreateSimpleContentType("component", "Component", components); service.Save(component); var category = MockedContentTypes.CreateSimpleContentType("category", "Category", global); service.Save(category); var success = category.AddContentType(component); Assert.That(success, Is.False); } [Test] public void Can_Remove_ContentType_Composition_From_ContentType() { //Test for U4-2234 var cts = ServiceContext.ContentTypeService; //Arrange var component = CreateComponent(); cts.Save(component); var banner = CreateBannerComponent(component); cts.Save(banner); var site = CreateSite(); cts.Save(site); var homepage = CreateHomepage(site); cts.Save(homepage); //Add banner to homepage var added = homepage.AddContentType(banner); cts.Save(homepage); //Assert composition var bannerExists = homepage.ContentTypeCompositionExists(banner.Alias); var bannerPropertyExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); Assert.That(added, Is.True); Assert.That(bannerExists, Is.True); Assert.That(bannerPropertyExists, Is.True); Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(6)); //Remove banner from homepage var removed = homepage.RemoveContentType(banner.Alias); cts.Save(homepage); //Assert composition var bannerStillExists = homepage.ContentTypeCompositionExists(banner.Alias); var bannerPropertyStillExists = homepage.CompositionPropertyTypes.Any(x => x.Alias.Equals("bannerName")); Assert.That(removed, Is.True); Assert.That(bannerStillExists, Is.False); Assert.That(bannerPropertyStillExists, Is.False); Assert.That(homepage.CompositionPropertyTypes.Count(), Is.EqualTo(4)); } [Test] public void Can_Copy_ContentType_By_Performing_Clone() { // Arrange var service = ServiceContext.ContentTypeService; var metaContentType = MockedContentTypes.CreateMetaContentType(); service.Save(metaContentType); var simpleContentType = MockedContentTypes.CreateSimpleContentType("category", "Category", metaContentType); service.Save(simpleContentType); var categoryId = simpleContentType.Id; // Act var sut = simpleContentType.Clone("newcategory"); service.Save(sut); // Assert Assert.That(sut.HasIdentity, Is.True); var contentType = service.GetContentType(sut.Id); var category = service.GetContentType(categoryId); Assert.That(contentType.CompositionAliases().Any(x => x.Equals("meta")), Is.True); Assert.AreEqual(contentType.ParentId, category.ParentId); Assert.AreEqual(contentType.Level, category.Level); Assert.AreEqual(contentType.PropertyTypes.Count(), category.PropertyTypes.Count()); Assert.AreNotEqual(contentType.Id, category.Id); Assert.AreNotEqual(contentType.Key, category.Key); Assert.AreNotEqual(contentType.Path, category.Path); Assert.AreNotEqual(contentType.SortOrder, category.SortOrder); Assert.AreNotEqual(contentType.PropertyTypes.First(x => x.Alias.Equals("title")).Id, category.PropertyTypes.First(x => x.Alias.Equals("title")).Id); Assert.AreNotEqual(contentType.PropertyGroups.First(x => x.Name.Equals("Content")).Id, category.PropertyGroups.First(x => x.Name.Equals("Content")).Id); } private ContentType CreateComponent() { var component = new ContentType(-1) { Alias = "component", Name = "Component", Description = "ContentType used for Component grouping", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 1, CreatorId = 0, Trashed = false }; var contentCollection = new PropertyTypeCollection(); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "componentGroup", Name = "Component Group", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); component.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Component", SortOrder = 1 }); return component; } private ContentType CreateBannerComponent(ContentType parent) { var banner = new ContentType(parent) { Alias = "banner", Name = "Banner Component", Description = "ContentType used for Banner Component", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 1, CreatorId = 0, Trashed = false }; var propertyType = new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "bannerName", Name = "Banner Name", Description = "", HelpText = "", Mandatory = false, SortOrder = 2, DataTypeDefinitionId = -88 }; banner.AddPropertyType(propertyType, "Component"); return banner; } private ContentType CreateSite() { var site = new ContentType(-1) { Alias = "site", Name = "Site", Description = "ContentType used for Site inheritence", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 2, CreatorId = 0, Trashed = false }; var contentCollection = new PropertyTypeCollection(); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "hostname", Name = "Hostname", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); site.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Site Settings", SortOrder = 1 }); return site; } private ContentType CreateHomepage(ContentType parent) { var contentType = new ContentType(parent) { Alias = "homepage", Name = "Homepage", Description = "ContentType used for the Homepage", Icon = ".sprTreeDoc3", Thumbnail = "doc.png", SortOrder = 1, CreatorId = 0, Trashed = false }; var contentCollection = new PropertyTypeCollection(); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "title", Name = "Title", Description = "", HelpText = "", Mandatory = false, SortOrder = 1, DataTypeDefinitionId = -88 }); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "bodyText", Name = "Body Text", Description = "", HelpText = "", Mandatory = false, SortOrder = 2, DataTypeDefinitionId = -87 }); contentCollection.Add(new PropertyType("test", DataTypeDatabaseType.Ntext) { Alias = "author", Name = "Author", Description = "Name of the author", HelpText = "", Mandatory = false, SortOrder = 3, DataTypeDefinitionId = -88 }); contentType.PropertyGroups.Add(new PropertyGroup(contentCollection) { Name = "Content", SortOrder = 1 }); return contentType; } private IContentType[] CreateContentTypeHierarchy() { //create the master type var masterContentType = MockedContentTypes.CreateSimpleContentType("masterContentType", "MasterContentType"); masterContentType.Key = new Guid("C00CA18E-5A9D-483B-A371-EECE0D89B4AE"); ServiceContext.ContentTypeService.Save(masterContentType); //add the one we just created var list = new List<IContentType> {masterContentType}; for (var i = 0; i < 10; i++) { var contentType = MockedContentTypes.CreateSimpleContentType("childType" + i, "ChildType" + i, //make the last entry in the list, this one's parent list.Last()); list.Add(contentType); } return list.ToArray(); } } }
using System; using System.Numerics; using System.Collections.Generic; using Xunit; using ipaddress; namespace address_test //namespace ipaddress.test { class IPv6Test { public Dictionary<String, String> compress_addr = new Dictionary<String, String>(); public Dictionary<String, BigInteger> valid_ipv6 = new Dictionary<String, BigInteger>(); public List<String> invalid_ipv6; public Dictionary<String, String> networks = new Dictionary<String, String>(); public List<uint> arr; public IPAddress ip; public IPAddress network; public String hex; public IPv6Test(List<String> invalid_ipv6, IPAddress ip, IPAddress net, String hex, List<uint> arr) { this.invalid_ipv6 = invalid_ipv6; this.ip = ip; this.network = net; this.hex = hex; this.arr = arr; } } public class TestIpv6 { IPv6Test setup() { var ip6t = new IPv6Test(new List<string> { ":1:2:3:4:5:6:7", ":1:2:3:4:5:6:7", "2002:516:2:200", "dd" }, IPAddress.parse("2001:db8::8:800:200c:417a/64").unwrap(), IPAddress.parse("2001:db8:8:800::/64").unwrap(), "20010db80000000000080800200c417a", new List<uint> { 8193, 3512, 0, 0, 8, 2048, 8204, 16762 }); ip6t.compress_addr.Add("2001:db8:0000:0000:0008:0800:200c:417a", "2001:db8::8:800:200c:417a"); ip6t.compress_addr.Add("2001:db8:0:0:8:800:200c:417a", "2001:db8::8:800:200c:417a"); ip6t.compress_addr.Add("ff01:0:0:0:0:0:0:101", "ff01::101"); ip6t.compress_addr.Add("0:0:0:0:0:0:0:1", "::1"); ip6t.compress_addr.Add("0:0:0:0:0:0:0:0", "::"); ip6t.valid_ipv6.Add("FEDC:BA98:7654:3210:FEDC:BA98:7654:3210", BigInteger.Parse("338770000845734292534325025077361652240")); ip6t.valid_ipv6.Add("1080:0000:0000:0000:0008:0800:200C:417A", BigInteger.Parse("21932261930451111902915077091070067066")); ip6t.valid_ipv6.Add("1080:0::8:800:200C:417A", BigInteger.Parse("21932261930451111902915077091070067066")); ip6t.valid_ipv6.Add("1080::8:800:200C:417A", BigInteger.Parse("21932261930451111902915077091070067066")); ip6t.valid_ipv6.Add("FF01:0:0:0:0:0:0:43", BigInteger.Parse("338958331222012082418099330867817087043")); ip6t.valid_ipv6.Add("FF01:0:0::0:0:43", BigInteger.Parse("338958331222012082418099330867817087043")); ip6t.valid_ipv6.Add("FF01::43", BigInteger.Parse("338958331222012082418099330867817087043")); ip6t.valid_ipv6.Add("0:0:0:0:0:0:0:1", BigInteger.Parse("1")); ip6t.valid_ipv6.Add("0:0:0::0:0:1", BigInteger.Parse("1")); ip6t.valid_ipv6.Add("::1", BigInteger.Parse("1")); ip6t.valid_ipv6.Add("0:0:0:0:0:0:0:0", BigInteger.Parse("0")); ip6t.valid_ipv6.Add("0:0:0::0:0:0", BigInteger.Parse("0")); ip6t.valid_ipv6.Add("::", BigInteger.Parse("0")); ip6t.valid_ipv6.Add("::/0", BigInteger.Parse("0")); ip6t.valid_ipv6.Add("1080:0:0:0:8:800:200C:417A", BigInteger.Parse("21932261930451111902915077091070067066")); ip6t.networks.Add("2001:db8:1:1:1:1:1:1/32", "2001:db8::/32"); ip6t.networks.Add("2001:db8:1:1:1:1:1::/32", "2001:db8::/32"); ip6t.networks.Add("2001:db8::1/64", "2001:db8::/64"); return ip6t; } [Fact] void test_attribute_address() { var addr = "2001:0db8:0000:0000:0008:0800:200c:417a"; Assert.Equal(addr, setup().ip.to_s_uncompressed()); } [Fact] void test_initialize() { Assert.Equal(false, setup().ip.is_ipv4()); foreach (var kp in setup().valid_ipv6) { var ip = kp.Key; Assert.Equal(true, IPAddress.parse(ip).isOk()); } foreach (var ip in setup().invalid_ipv6) { Assert.Equal(true, IPAddress.parse(ip).isErr()); } Assert.Equal(64u, setup().ip.prefix.num); Assert.Equal(false, IPAddress.parse("::10.1.1.1").isErr()); } [Fact] void test_attribute_groups() { Assert.Equal(setup().arr, setup().ip.parts()); } [Fact] public void test_method_hexs() { Assert.Equal(setup().ip.parts_hex_str(), new List<String> { "2001", "0db8", "0000", "0000", "0008", "0800", "200c", "417a" }); } [Fact] public void test_method_to_i() { foreach (var kp in setup().valid_ipv6) { var ip = kp.Key; var num = kp.Value; Assert.Equal(num, IPAddress.parse(ip).unwrap().host_address); } } // [Fact] // public void test_method_bits() { // var bits = "0010000000000001000011011011100000000000000000000" + // "000000000000000000000000000100000001000000000000010000" + // "0000011000100000101111010"; // Assert.Equal(bits, setup().ip.host_address.to_str_radix(2)); // } [Fact] public void test_method_set_prefix() { var ip = IPAddress.parse("2001:db8::8:800:200c:417a").unwrap(); Assert.Equal(128u, ip.prefix.num); Assert.Equal("2001:db8::8:800:200c:417a/128", ip.to_string()); var nip = ip.change_prefix(64).unwrap(); Assert.Equal(64u, nip.prefix.num); Assert.Equal("2001:db8::8:800:200c:417a/64", nip.to_string()); } [Fact] public void test_method_mapped() { Assert.Equal(false, setup().ip.is_mapped()); var ip6 = IPAddress.parse("::ffff:1234:5678").unwrap(); Assert.Equal(true, ip6.is_mapped()); } // [Fact] // public void test_method_literal() { // var str = "2001-0db8-0000-0000-0008-0800-200c-417a.ipv6-literal.net"; // Assert.Equal(str, setup().ip.literal()); // } [Fact] public void test_method_group() { var s = setup(); Assert.Equal(s.ip.parts(), s.arr); } [Fact] public void test_method_ipv4() { Assert.Equal(false, setup().ip.is_ipv4()); } [Fact] public void test_method_ipv6() { Assert.Equal(true, setup().ip.is_ipv6()); } [Fact] public void test_method_network_known() { Assert.Equal(true, setup().network.is_network()); Assert.Equal(false, setup().ip.is_network()); } [Fact] public void test_method_network_u128() { Assert.Equal(IpV6.from_int(BigInteger.Parse("42540766411282592856903984951653826560"), 64).unwrap(), setup().ip.network()); } [Fact] public void test_method_broadcast_u128() { Assert.Equal(IpV6.from_int(BigInteger.Parse("42540766411282592875350729025363378175"), 64).unwrap(), setup().ip.broadcast()); } [Fact] public void test_method_size() { var ip = IPAddress.parse("2001:db8::8:800:200c:417a/64").unwrap(); Assert.Equal(new BigInteger(1) <<(64), ip.size()); ip = IPAddress.parse("2001:db8::8:800:200c:417a/32").unwrap(); Assert.Equal(new BigInteger(1) <<(96), ip.size()); ip = IPAddress.parse("2001:db8::8:800:200c:417a/120").unwrap(); Assert.Equal(new BigInteger(1) <<(8), ip.size()); ip = IPAddress.parse("2001:db8::8:800:200c:417a/124").unwrap(); Assert.Equal(new BigInteger(1) <<(4), ip.size()); } [Fact] public void test_method_includes() { var ip = setup().ip; Assert.Equal(true, ip.includes(ip)); // test prefix on same address var included = IPAddress.parse("2001:db8::8:800:200c:417a/128").unwrap(); var not_included = IPAddress.parse("2001:db8::8:800:200c:417a/46").unwrap(); Assert.Equal(true, ip.includes(included)); Assert.Equal(false, ip.includes(not_included)); // test address on same prefix included = IPAddress.parse("2001:db8::8:800:200c:0/64").unwrap(); not_included = IPAddress.parse("2001:db8:1::8:800:200c:417a/64").unwrap(); Assert.Equal(true, ip.includes(included)); Assert.Equal(false, ip.includes(not_included)); // general test included = IPAddress.parse("2001:db8::8:800:200c:1/128").unwrap(); not_included = IPAddress.parse("2001:db8:1::8:800:200c:417a/76").unwrap(); Assert.Equal(true, ip.includes(included)); Assert.Equal(false, ip.includes(not_included)); } [Fact] public void test_method_to_hex() { Assert.Equal(setup().hex, setup().ip.to_hex()); } [Fact] public void test_method_to_s() { Assert.Equal("2001:db8::8:800:200c:417a", setup().ip.to_s()); } [Fact] public void test_method_to_string() { Assert.Equal("2001:db8::8:800:200c:417a/64", setup().ip.to_string()); } [Fact] public void test_method_to_string_uncompressed() { var str = "2001:0db8:0000:0000:0008:0800:200c:417a/64"; Assert.Equal(str, setup().ip.to_string_uncompressed()); } [Fact] public void test_method_reverse() { var str = "f.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.2.0.0.0.5.0.5.0.e.f.f.3.ip6.arpa"; Assert.Equal(str, IPAddress.parse("3ffe:505:2::f").unwrap().dns_reverse()); } [Fact] public void test_method_dns_rev_domains() { Assert.Equal(IPAddress.parse("f000:f100::/3").unwrap().dns_rev_domains(), new List<String> { "e.ip6.arpa", "f.ip6.arpa" }); Assert.Equal(IPAddress.parse("fea3:f120::/15").unwrap().dns_rev_domains(), new List<String> { "2.a.e.f.ip6.arpa", "3.a.e.f.ip6.arpa" }); Assert.Equal(IPAddress.parse("3a03:2f80:f::/48").unwrap().dns_rev_domains(), new List<String> { "f.0.0.0.0.8.f.2.3.0.a.3.ip6.arpa" }); Assert.Equal(IPAddress.parse("f000:f100::1234/125").unwrap().dns_rev_domains(), new List<String> { "0.3.2.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.f.0.0.0.f.ip6.arpa", "1.3.2.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.f.0.0.0.f.ip6.arpa", "2.3.2.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.f.0.0.0.f.ip6.arpa", "3.3.2.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.f.0.0.0.f.ip6.arpa", "4.3.2.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.f.0.0.0.f.ip6.arpa", "5.3.2.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.f.0.0.0.f.ip6.arpa", "6.3.2.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.f.0.0.0.f.ip6.arpa", "7.3.2.1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.1.f.0.0.0.f.ip6.arpa" }); } [Fact] public void test_method_compressed() { Assert.Equal("1:1:1::1", IPAddress.parse("1:1:1:0:0:0:0:1").unwrap().to_s()); Assert.Equal("1:0:1::1", IPAddress.parse("1:0:1:0:0:0:0:1").unwrap().to_s()); Assert.Equal("1::1:1:1:2:3:1", IPAddress.parse("1:0:1:1:1:2:3:1").unwrap().to_s()); Assert.Equal("1::1:1:0:2:3:1", IPAddress.parse("1:0:1:1::2:3:1").unwrap().to_s()); Assert.Equal("1:0:0:1::1", IPAddress.parse("1:0:0:1:0:0:0:1").unwrap().to_s()); Assert.Equal("1::1:0:0:1", IPAddress.parse("1:0:0:0:1:0:0:1").unwrap().to_s()); Assert.Equal("1::1", IPAddress.parse("1:0:0:0:0:0:0:1").unwrap().to_s()); // Assert.Equal("1:1::1:2:0:0:1", IPAddress.parse("1:1:0:1:2::1").unwrap().to_s } [Fact] public void test_method_unspecified() { Assert.Equal(true, IPAddress.parse("::").unwrap().is_unspecified()); Assert.Equal(false, setup().ip.is_unspecified()); } [Fact] public void test_method_loopback() { Assert.Equal(true, IPAddress.parse("::1").unwrap().is_loopback()); Assert.Equal(false, setup().ip.is_loopback()); } [Fact] public void test_method_network() { foreach (var kp in setup().networks) { var addr = kp.Key; var net = kp.Value; var ip = IPAddress.parse(addr).unwrap(); Assert.Equal(net, ip.network().to_string()); } } [Fact] public void test_method_each() { var ip = IPAddress.parse("2001:db8::4/125").unwrap(); var arr = new List<String>(); ip.each(i => arr.Add(i.to_s()) ) ; Assert.Equal(arr, new List<String> {"2001:db8::", "2001:db8::1", "2001:db8::2", "2001:db8::3", "2001:db8::4", "2001:db8::5", "2001:db8::6", "2001:db8::7"}); } [Fact] public void test_method_each_net() { var test_addrs = new List<String> {"0000:0000:0000:0000:0000:0000:0000:0000", "1111:1111:1111:1111:1111:1111:1111:1111", "2222:2222:2222:2222:2222:2222:2222:2222", "3333:3333:3333:3333:3333:3333:3333:3333", "4444:4444:4444:4444:4444:4444:4444:4444", "5555:5555:5555:5555:5555:5555:5555:5555", "6666:6666:6666:6666:6666:6666:6666:6666", "7777:7777:7777:7777:7777:7777:7777:7777", "8888:8888:8888:8888:8888:8888:8888:8888", "9999:9999:9999:9999:9999:9999:9999:9999", "aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa:aaaa", "bbbb:bbbb:bbbb:bbbb:bbbb:bbbb:bbbb:bbbb", "cccc:cccc:cccc:cccc:cccc:cccc:cccc:cccc", "dddd:dddd:dddd:dddd:dddd:dddd:dddd:dddd", "eeee:eeee:eeee:eeee:eeee:eeee:eeee:eeee", "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff"}; for (var prefix = 0; prefix < 128; prefix++) { var nr_networks = 1 << ((128 - prefix) % 4); foreach (var adr in test_addrs) { var net_adr = IPAddress.parse(string.Format("{0}/{1}", adr, prefix)).unwrap(); var ret = net_adr.dns_networks(); Assert.Equal(ret[0].prefix.num % 4, 0u); Assert.Equal(ret.Count, nr_networks); Assert.Equal(net_adr.network().to_s(), ret[0].network().to_s()); Assert.Equal(net_adr.broadcast().to_s(), ret[ret.Count - 1].broadcast().to_s()); // puts "//{adr}///{prefix} //{nr_networks} //{ret}" } } var ret0 = IPAddress.to_string_vec(IPAddress.parse("fd01:db8::4/3").unwrap().dns_networks()); Assert.Equal(ret0, new List<String> {"e000::/4", "f000::/4" }); var ret1 = IPAddress.to_string_vec(IPAddress.parse("3a03:2f80:f::/48").unwrap().dns_networks()); Assert.Equal(ret1, new List<String> {"3a03:2f80:f::/48" }); } [Fact] public void test_method_compare() { var ip1 = IPAddress.parse("2001:db8:1::1/64").unwrap(); var ip2 = IPAddress.parse("2001:db8:2::1/64").unwrap(); var ip3 = IPAddress.parse("2001:db8:1::2/64").unwrap(); var ip4 = IPAddress.parse("2001:db8:1::1/65").unwrap(); // ip2 should be greater than ip1 Assert.Equal(true, ip2.gt(ip1)); Assert.Equal(false, ip1.gt(ip2)); Assert.Equal(false, ip2.lt(ip1)); // ip3 should be less than ip2 Assert.Equal(true, ip2.gt(ip3)); Assert.Equal(false, ip2.lt(ip3)); // ip1 should be less than ip3 Assert.Equal(true, ip1.lt(ip3)); Assert.Equal(false, ip1.gt(ip3)); Assert.Equal(false, ip3.lt(ip1)); // ip1 should be equal to itself Assert.Equal(true, ip1.equal(ip1)); // ip4 should be greater than ip1 Assert.Equal(true, ip1.lt(ip4)); Assert.Equal(false, ip1.gt(ip4)); // test sorting var r = IPAddress.to_string_vec(IPAddress.sort(new List<IPAddress> { ip1, ip2, ip3, ip4 })); Assert.Equal(r, new List<String> { "2001:db8:1::1/64", "2001:db8:1::1/65", "2001:db8:1::2/64", "2001:db8:2::1/64" }); } // public void test_classmethod_expand() { // var compressed = "2001:db8:0:cd30::"; // var expanded = "2001:0db8:0000:cd30:0000:0000:0000:0000"; // Assert.Equal(expanded, @klass.expand(compressed)); // Assert.Equal(expanded, @klass.expand("2001:0db8:0::cd3")); // Assert.Equal(expanded, @klass.expand("2001:0db8::cd30")); // Assert.Equal(expanded, @klass.expand("2001:0db8::cd3")); // } [Fact] public void test_classmethod_compress() { var compressed = "2001:db8:0:cd30::"; var expanded = "2001:0db8:0000:cd30:0000:0000:0000:0000"; Assert.Equal(compressed, IPAddress.parse(expanded).unwrap().to_s()); Assert.Equal("2001:db8::cd3", IPAddress.parse("2001:0db8:0::cd3").unwrap().to_s()); Assert.Equal("2001:db8::cd30", IPAddress.parse("2001:0db8::cd30").unwrap().to_s()); Assert.Equal("2001:db8::cd3", IPAddress.parse("2001:0db8::cd3").unwrap().to_s()); } [Fact] public void test_classhmethod_parse_u128() { foreach (var kp in setup().valid_ipv6) { var ip = kp.Key; var num = kp.Value; // println!(">>>{}==={}", ip, num); Assert.Equal(IPAddress.parse(ip).unwrap().to_s(), IpV6.from_int(num, 128).unwrap().to_s()); } } [Fact] public void test_classmethod_parse_hex() { Assert.Equal(setup().ip.to_string(), IpV6.from_str(setup().hex, 16, 64).unwrap().to_string()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftLeftLogicalUInt641() { var test = new SimpleUnaryOpTest__ShiftLeftLogicalUInt641(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ShiftLeftLogicalUInt641 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(UInt64); private const int RetElementCount = VectorSize / sizeof(UInt64); private static UInt64[] _data = new UInt64[Op1ElementCount]; private static Vector128<UInt64> _clsVar; private Vector128<UInt64> _fld; private SimpleUnaryOpTest__DataTable<UInt64, UInt64> _dataTable; static SimpleUnaryOpTest__ShiftLeftLogicalUInt641() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _clsVar), ref Unsafe.As<UInt64, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftLeftLogicalUInt641() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)(random.Next(0, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt64>, byte>(ref _fld), ref Unsafe.As<UInt64, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ulong)(random.Next(0, int.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<UInt64, UInt64>(_data, new UInt64[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.ShiftLeftLogical( Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.ShiftLeftLogical( Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.ShiftLeftLogical( Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical), new Type[] { typeof(Vector128<UInt64>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.ShiftLeftLogical( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<UInt64>>(_dataTable.inArrayPtr); var result = Sse2.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((UInt64*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((UInt64*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftLeftLogicalUInt641(); var result = Sse2.ShiftLeftLogical(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.ShiftLeftLogical(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt64> firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt64[] inArray = new UInt64[Op1ElementCount]; UInt64[] outArray = new UInt64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt64[] firstOp, UInt64[] result, [CallerMemberName] string method = "") { if ((ulong)(firstOp[0] << 1) != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if ((ulong)(firstOp[i] << 1) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftLeftLogical)}<UInt64>(Vector128<UInt64><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// Copyright (c) Bohdan Shtepan. All rights reserved. // http://modern-dev.com/ // // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using static System.Convert; using static ModernDev.IronBabylon.Util; namespace ModernDev.IronBabylon { public partial class Tokenizer { #region Class constructors protected Tokenizer(ParserOptions options, string input ) { State = new State(options, input); } #endregion #region Class properties public State State { get; protected set; } private bool IsLookahead { get; set; } public string Input { get; protected set; } protected bool InModule { get; set; } public TokenContext CurrentContext => State.Context.Last(); protected static Dictionary<string, TokenType> TT => TokenType.Types; #endregion #region Class methods private static string CodePointToString(int code) => code <= 0xffff ? ToChar(code).ToString() : $"{ToChar(((code - 0x10000) >> 10) + 0xD800)}{ToChar(((code - 0x10000) & 1023) + 0xDC00)}"; /// <summary> /// Move to the next token /// </summary> protected void Next() { if (!IsLookahead) { State.Tokens.Add(new Token(State)); } State.LastTokenEnd = State.End; State.LastTokenStart = State.Start; State.LastTokenEndLoc = State.EndLoc; State.LastTokenStartLoc = State.StartLoc; NextToken(); } protected bool Eat(TokenType type) { if (Match(type)) { Next(); return true; } return false; } protected bool Match(TokenType type) => State.Type == type; protected virtual bool IsKeyword(string word) => Util.IsKeyword(word); protected State Lookahead() { var old = State; State = old.Clone(true); IsLookahead = true; Next(); IsLookahead = false; var curr = State.Clone(true); State = old; return curr; } /// <summary> /// Toggle strict mode. Re-reads the next number or string to please /// pedantic tests (`"use strict"; 010;` should fail). /// </summary> /// <param name="strict"></param> protected void SetStrict(bool strict) { State.Strict = strict; if (!Match(TT["num"]) && !Match(TT["string"])) { return; } State.Position = State.Start; while (State.Position < State.LineStart) { State.LineStart = Input.LastIndexOf("\n", State.LineStart - 2, StringComparison.Ordinal) + 1; --State.CurLine; } NextToken(); } /// <summary> /// Read a single token, updating the parser object's token-related properties. /// </summary> /// <returns></returns> protected TokenType NextToken() { var curContext = CurrentContext; if (curContext == null || !curContext.PreserveSpace) { SkipSpace(); } State.ContainsOctal = false; State.OctalPosition = null; State.Start = State.Position; State.StartLoc = State.CurrentPosition; if (State.Position >= Input.Length) { return FinishToken(TT["eof"]); } return curContext?.Override != null ? curContext.Override(this) : ReadToken(FullCharCodeAtPos()); } protected virtual TokenType ReadToken(int code) => IsIdentifierStart(code) || code == 92 ? ReadWord() : GetTokenFromCode(code); private int FullCharCodeAtPos() { var code = Input.CharCodeAt(State.Position); if (code <= 0xd7ff || code >= 0xe000) { return code; } var next = Input.CharCodeAt(State.Position + 1); return (code << 10) + next - 0x35fdc00; } private void PushComment(bool block, string text, int start, int end, Position startLoc, Position endLoc) { var comment = new Node(start, startLoc) { Type = block ? "CommentBlock" : "CommentLine", Value = text, End = end, Loc = new SourceLocation(startLoc, endLoc) }; if (!IsLookahead) { State.Tokens.Add(comment); State.Comments.Add(comment); } AddComment(comment); } private void SkipBlockComment() { var startLoc = State.CurrentPosition; var start = State.Position; var end = Input.IndexOf("*/", State.Position += 2, StringComparison.Ordinal); if (end == -1) { Raise(State.Position - 2, "Unterminated comment"); } State.Position = end + 2; foreach(var match in LineBreak.Matches(Input, start).Cast<Match>().TakeWhile(m => m.Index < State.Position)) { ++State.CurLine; State.LineStart = match.Index + match.Length; } PushComment(true, Input.Slice(start + 2, end), start, State.Position, startLoc, State.CurrentPosition); } protected void SkipLineComment(int startSkip) { var start = State.Position; var startLoc = State.CurrentPosition; var ch = Input.CharCodeAt(State.Position += startSkip); while (State.Position < Input.Length && ch != 10 && ch != 13 && ch != 8232 && ch != 8233) { ++State.Position; ch = Input.CharCodeAt(State.Position); } PushComment(false, Input.Slice(start + startSkip, State.Position), start, State.Position, startLoc, State.CurrentPosition); } /// <summary> /// Called at the start of the parse and after every token. Skips whitespace and comments, and. /// </summary> private void SkipSpace() { var done = false; while (State.Position < Input.Length) { if (done) { break; } int ch = Input.CharCodeAt(State.Position); switch (ch) { case 32: case 160: { ++State.Position; } break; case 13: case 10: case 8232: case 8233: { if (ch == 13 && Input.CharCodeAt(State.Position + 1) == 10) { ++State.Position; } ++State.Position; ++State.CurLine; State.LineStart = State.Position; } break; case 47: { switch (Input.CharCodeAt(State.Position + 1)) { case 42: SkipBlockComment(); break; case 47: SkipLineComment(2); break; default: done = true; break; } } break; default: { if (ch > 8 && ch < 14 || ch >= 5760 && NonASCIIWhitespace.IsMatch(ToChar(ch).ToString())) { ++State.Position; } else { done = true; } } break; } } } /// <summary> /// Called at the end of every token. Sets `end`, `val`, and /// maintains `context` and `exprAllowed`, and skips the space after /// the token, so that the next one's `start` will point at the /// right position. /// </summary> protected TokenType FinishToken(TokenType type, object val = null) { State.End = State.Position; State.EndLoc = State.CurrentPosition; var prevType = State.Type; State.Type = type; State.Value = val; UpdateContext(prevType); return null; } private TokenType ReadTokenDot() { var next = Input.CharCodeAt(State.Position + 1); if (next >= 48 && next <= 57) { return ReadNumber(true); } var next2 = Input.CharCodeAt(State.Position + 2); if (next == 46 && next2 == 46) { State.Position += 3; return FinishToken(TT["ellipsis"]); } ++State.Position; return FinishToken(TT["dot"]); } private TokenType ReadTokenSlash() { if (State.ExprAllowed) { ++State.Position; return ReadRegexp(); } var next = Input.CharCodeAt(State.Position + 1); return next == 61 ? FinishOp(TT["assign"], 2) : FinishOp(TT["slash"], 1); } private TokenType ReadTokenMultModulo(int code) { var type = TT[code == 42 ? "star" : "modulo"]; var width = 1; var next = Input.CharCodeAt(State.Position + 1); if (next == 42) { width++; next = Input.CharCodeAt(State.Position + 2); type = TT["exponent"]; } if (next == 61) { width++; type = TT["assign"]; } return FinishOp(type, width); } private TokenType ReadTokenPipeAmp(int code) { var next = Input.CharCodeAt(State.Position + 1); if (next == code) { return FinishOp(TT[code == 124 ? "logicalOR" : "logicalAND"], 2); } return next == 61 ? FinishOp(TT["assign"], 2) : FinishOp(TT[code == 124 ? "bitwiseOR" : "bitwiseAND"], 1); } private TokenType ReadTokenCaret() { var next = Input.CharCodeAt(State.Position + 1); return next == 61 ? FinishOp(TT["assign"], 2) : FinishOp(TT["bitwiseXOR"], 1); } private TokenType ReadTokenPlusMin(int code) { var next = Input.CharCodeAt(State.Position + 1); if (next == code) { if (next == 45 && Input.CharCodeAt(State.Position + 2) == 62 && LineBreak.IsMatch(Input.Slice(State.LastTokenEnd, State.Position))) { SkipLineComment(3); SkipSpace(); return NextToken(); } return FinishOp(TT["incDec"], 2); } return next == 61 ? FinishOp(TT["assign"], 2) : FinishOp(TT["plusMin"], 1); } private TokenType ReadTokenLtGt(int code) { var next = Input.CharCodeAt(State.Position + 1); var size = 1; if (next == code) { size = code == 62 && Input.CharCodeAt(State.Position + 2) == 62 ? 3 : 2; return Input.CharCodeAt(State.Position + size) == 61 ? FinishOp(TT["assign"], size + 1) : FinishOp(TT["bitShift"], size); } if (next == 33 && code == 60 && Input.CharCodeAt(State.Position + 2) == 45 && Input.CharCodeAt(State.Position + 3) == 45) { if (InModule) { Unexpected(); } SkipLineComment(4); SkipSpace(); return NextToken(); } if (next == 61) { size = Input.CharCodeAt(State.Position + 2) == 61 ? 3 : 2; } return FinishOp(TT["relational"], size); } private TokenType ReadTokenEqExcl(int code) { var next = Input.CharCodeAt(State.Position + 1); if (next == 61) { return FinishOp(TT["equality"], Input.CharCodeAt(State.Position + 2) == 61 ? 3 : 2); } if (code == 61 && next == 62) { State.Position += 2; return FinishToken(TT["arrow"]); } return FinishOp(TT[code == 61 ? "eq" : "prefix"], 1); } protected TokenType GetTokenFromCode(int code) { switch (code) { case 46: return ReadTokenDot(); case 40: ++State.Position; return FinishToken(TT["parenL"]); case 41: ++State.Position; return FinishToken(TT["parenR"]); case 59: ++State.Position; return FinishToken(TT["semi"]); case 44: ++State.Position; return FinishToken(TT["comma"]); case 91: ++State.Position; return FinishToken(TT["bracketL"]); case 93: ++State.Position; return FinishToken(TT["bracketR"]); case 123: ++State.Position; return FinishToken(TT["braceL"]); case 125: ++State.Position; return FinishToken(TT["braceR"]); case 58: if (Input.CharCodeAt(State.Position + 1) == 58) { return FinishOp(TT["doubleColon"], 2); } ++State.Position; return FinishToken(TT["colon"]); case 63: ++State.Position; return FinishToken(TT["question"]); case 64: ++State.Position; return FinishToken(TT["at"]); case 96: ++State.Position; return FinishToken(TT["backQuote"]); case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: if (code == 48) { var next = State.Position + 1 >= Input.Length ? int.MaxValue : Input.CharCodeAt(State.Position + 1); switch (next) { case 120: case 98: return ReadRadixNumber(16); case 111: case 79: return ReadRadixNumber(8); } if (next == 98 || next == 66) { return ReadRadixNumber(2); } } return ReadNumber(false); case 34: case 39: return ReadString(code); case 47: return ReadTokenSlash(); case 37: case 42: return ReadTokenMultModulo(code); case 124: case 38: return ReadTokenPipeAmp(code); case 94: return ReadTokenCaret(); case 43: case 45: return ReadTokenPlusMin(code); case 60: case 62: return ReadTokenLtGt(code); case 61: case 33: return ReadTokenEqExcl(code); case 126: return FinishOp(TT["prefix"], 1); } Raise(State.Position, $"Unexpected character {CodePointToString(code)}"); return null; } protected TokenType FinishOp(TokenType type, int size) { var str = Input.Slice(State.Position, State.Position + size); State.Position += size; return FinishToken(type, str); } private TokenType ReadRegexp() { var start = State.Position; var escaped = false; var inClass = false; for (;;) { if (State.Position >= Input.Length) { Raise(start, "Unterminated regular expression"); } var ch = Input.CharCodeAt(State.Position); if (LineBreak.IsMatch(ch.ToString())) { Raise(start, "Unterminated regular expression"); } if (escaped) { escaped = false; } else { if (ch == '[') { inClass = true; } else if (ch == ']' && inClass) { inClass = false; } else if (ch == '/' && !inClass) { break; } escaped = ch == '\\'; } ++State.Position; } var content = Input.Slice(start, State.Position); ++State.Position; var mods = ReadWord1(); if (!string.IsNullOrEmpty(mods)) { var validFlags = new Regex("^[gmsiyu]*$"); if (!validFlags.IsMatch(mods)) { Raise(start, "Invalid regular expression flag"); } } return FinishToken(TT["regexp"], new Node {Pattern = content, Flags = mods}); } /// <summary> /// Read an integer in the given radix. Return null if zero digits /// were read, the integer value otherwise. When `len` is given, this /// will return `null` unless the integer has exactly `len` digits. /// </summary> private int? ReadInt(int radix, int? len = null) { var start = State.Position; var total = 0; for (int i = 0, e = len ?? int.MaxValue; i < e; ++i) { var code = Input.CharCodeAt(State.Position); int val; if (code >= 97) { val = code - 97 + 10; } else if (code >= 65) { val = code - 65 + 10; } else if (code >= 48 && code <= 57) { val = code - 48; } else { val = int.MaxValue; } if (val >= radix) { break; } ++State.Position; total = total*radix + val; } if (State.Position == start || len != null && State.Position - start != len) { return null; } return total; } private TokenType ReadRadixNumber(int radix) { State.Position += 2; var val = ReadInt(radix); if (val == null) { Raise(State.Start + 2, "Expected number in radix " + radix); } if (IsIdentifierStart(FullCharCodeAtPos())) { Raise(State.Position, "Identifier directly after number"); } return FinishToken(TT["num"], val); } /// <summary> /// Read an integer, octal integer, or floating-point number. /// </summary> private TokenType ReadNumber(bool startsWithDot) { var start = State.Position; var isFloat = false; var octal = Input.CharCodeAt(State.Position) == 48; if (!startsWithDot && ReadInt(10) == null) { Raise(start, "Invalid number"); } int? next = null; if (State.Position < Input.Length) { next = Input.CharCodeAt(State.Position); } if (next == 46) { ++State.Position; ReadInt(10); isFloat = true; if (State.Position < Input.Length) { next = Input.CharCodeAt(State.Position); } else { next = null; } } if (next == 69 || next == 101) { next = Input.CharCodeAt(++State.Position); if (next == 43 || next == 45) { ++State.Position; } if (ReadInt(10) == null) { Raise(start, "Invalid number"); } isFloat = true; } if (IsIdentifierStart(FullCharCodeAtPos())) { Raise(State.Position, "Identifier directly after number"); } var str = Input.Slice(start, State.Position); object val = null; if (isFloat) { val = float.Parse(str, NumberStyles.Any, CultureInfo.InvariantCulture); } else if (!octal || str.Length == 1) { val = ToInt32(str, 10); } else if (new Regex("[89]").IsMatch(str) || State.Strict) { Raise(start, "Invalid number"); } else { val = ToInt32(str, 8); } return FinishToken(TT["num"], val); } /// <summary> /// Read a string value, interpreting backslash-escapes. /// </summary> private int ReadCodePoint() { var ch = Input.CharCodeAt(State.Position); int code; if (ch == 123) { var codePos = ++State.Position; code = ReadHexChar(Input.IndexOf("}", State.Position, StringComparison.Ordinal) - State.Position); ++State.Position; if (code > 0x10FFFF) { Raise(codePos, "Code point out of bounds"); } } else { code = ReadHexChar(4); } return code; } private TokenType ReadString(int quote) { var outt = ""; var chunkStart = ++State.Position; for (;;) { if (State.Position >= Input.Length) { Raise(State.Start, "Unterminated string constant"); } var ch = Input.CharCodeAt(State.Position); if (ch == quote) { break; } if (ch == 92) { outt += Input.Slice(chunkStart, State.Position); outt += ReadEscapedChar(false); chunkStart = State.Position; } else { if (IsNewLine(ch)) { Raise(State.Start, "Unterminated string constant"); } ++State.Position; } } outt += Input.Slice(chunkStart, State.Position++); return FinishToken(TT["string"], outt); } // Reads template string tokens. public TokenType ReadTmplToken() { var outt = ""; var chunkStart = State.Position; for (;;) { if (State.Position >= Input.Length) { Raise(State.Start, "Unterminated template"); } int ch = Input.CharCodeAt(State.Position); if (ch == 96 || ch == 36 && Input.CharCodeAt(State.Position + 1) == 123) { if (State.Position == State.Start && Match(TT["template"])) { if (ch == 36) { State.Position += 2; return FinishToken(TT["dollarBraceL"]); } ++State.Position; return FinishToken(TT["backQuote"]); } outt += Input.Slice(chunkStart, State.Position); return FinishToken(TT["template"], outt); } if (ch == 92) { outt += Input.Slice(chunkStart, State.Position); outt += ReadEscapedChar(true); chunkStart = State.Position; } else if (IsNewLine(ch)) { outt += Input.Slice(chunkStart, State.Position); ++State.Position; switch (ch) { case 10: case 13: if (ch == 13 && Input.CharCodeAt(State.Position) == 10) { ++State.Position; } outt += '\n'; break; default: outt += ToChar(ch).ToString(); break; } ++State.CurLine; State.LineStart = State.Position; chunkStart = State.Position; } else { ++State.Position; } } } /// <summary> /// Used to read escaped characters /// </summary> private string ReadEscapedChar(bool inTemplate ) { var ch = Input.CharCodeAt(++State.Position); ++State.Position; switch (ch) { case 110: return "\n"; case 114: return "\r"; case 120: return ToChar(ReadHexChar(2)).ToString(); case 117: return CodePointToString(ReadCodePoint()); case 116: return "\t"; case 98: return "\b"; case 118: return "\u000b"; case 102: return "\f"; case 10: case 13: if (ch == 13 && Input.CharCodeAt(State.Position) == 10) { ++State.Position; } State.LineStart = State.Position; ++State.CurLine; return ""; default: if (ch >= 48 && ch <= 55) { var octalStr = new Regex("^[0-7]+").Match(Input.Substr(State.Position - 1, 3)).Value; var octal = ToInt32(octalStr, 8); if (octal > 255) { octalStr = octalStr.Slice(0, -1); octal = ToInt32(octalStr, 8); } if (octal > 0) { if (!State.ContainsOctal) { State.ContainsOctal = true; State.OctalPosition = State.Position - 2; } if (State.Strict || inTemplate) { Raise(State.Position - 2, "Octal literal in strict mode"); } } State.Position += octalStr.Length - 1; return octal.FromCharCodeToString(); } return ch.FromCharCodeToString(); } } /// <summary> /// Used to read character escape sequences ('\x', '\u', '\U'). /// </summary> private int ReadHexChar(int len) { var codePos = State.Position; var n = ReadInt(16, len); if (n == null) { Raise(codePos, "Bad character escape sequence"); return 0; } return (int) n; } /// <summary> /// Read an identifier, and return it as a string. Sets `this.state.containsEsc` /// to whether the word contained a '\u' escape. /// /// Incrementally adds only escaped chars, adding other chunks as-is /// as a micro-optimization. /// </summary> private string ReadWord1() { State.ContainsEsc = false; var word = ""; var first = true; var chunkStart = State.Position; while (State.Position < Input.Length) { var ch = FullCharCodeAtPos(); if (IsIdentifierChar(ch)) { State.Position += ch <= 0xffff ? 1 : 2; } else if (ch == 92) { State.ContainsEsc = true; word += Input.Slice(chunkStart, State.Position); var escStart = State.Position; if (Input.CharCodeAt(++State.Position) != 117) { Raise(State.Position, "Expecting Unicode escape sequence \\uXXXX"); } ++State.Position; var esc = ReadCodePoint(); if (!(first ? IsIdentifierStart(esc) : IsIdentifierChar(esc))) { Raise(escStart, "Invalid Unicode escape"); } word += CodePointToString(esc); chunkStart = State.Position; } else { break; } first = false; } return word + Input.Slice(chunkStart, State.Position); } /// <summary> /// Read an identifier or keyword token. Will check for reserved words when necessary. /// </summary> /// <returns></returns> private TokenType ReadWord() { var word = ReadWord1(); var type = TT["name"]; if (!State.ContainsEsc && IsKeyword(word)) { type = TokenType.Keywords[word]; } return FinishToken(type, word); } public bool BraceIsBlock(TokenType prevType) { if (prevType == TT["colon"]) { var parent = CurrentContext; if (parent == TokenContext.Types["b_stat"] || parent == TokenContext.Types["b_expr"]) { return !parent.IsExpr; } } if (prevType == TT["_return"]) { return LineBreak.IsMatch(Input.Slice(State.LastTokenEnd, State.Start)); } if (prevType == TT["_else"] || prevType == TT["semi"] || prevType == TT["eof"] || prevType == TT["parenR"]) { return true; } if (prevType == TT["braceL"]) { return CurrentContext == TokenContext.Types["b_stat"]; } return !State.ExprAllowed; } protected virtual void UpdateContext(TokenType prevType) { var type = State.Type; var update = type.UpdateContext; if (!string.IsNullOrEmpty(type.Keyword) && prevType == TT["dot"]) { State.ExprAllowed = false; } else if (update != null) { update(this, prevType); } else { State.ExprAllowed = type.BeforeExpr; } } /// <summary> /// Raise an unexpected token error. /// </summary> protected bool Unexpected(int? pos = null) { Raise(pos ?? State.Start, "Unexpected token"); return false; } /// <summary> /// This function is used to raise exceptions on parse errors. It /// takes an offset integer (into the current `input`) to indicate /// the location of the error, attaches the position to the end /// of the error message, and then raises a `SyntaxError` with that /// message. /// </summary> protected void Raise(int pos, string msg) { var loc = GetLineInfo(Input, pos); msg += $" ({loc.Line}:{loc.Column})"; throw new SyntaxErrorException(msg, loc, pos); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using ReactNative.Accessibility; using ReactNative.Reflection; using ReactNative.UIManager; using ReactNative.UIManager.Annotations; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Documents; using Windows.UI.Xaml.Media; namespace ReactNative.Views.Text { /// <summary> /// The view manager for text views. /// </summary> public class ReactSimpleTextViewManager : BaseViewManager<TextBlock, ReactSimpleTextShadowNode> { private readonly ViewKeyedDictionary<TextBlock, TextBlockData> _textBlockData = new ViewKeyedDictionary<TextBlock, TextBlockData>(); /// <summary> /// The name of the view manager. /// </summary> public override string Name { get { return "RCTSimpleText"; } } /// <summary> /// Creates the shadow node instance. /// </summary> /// <returns>The shadow node instance.</returns> public override ReactSimpleTextShadowNode CreateShadowNodeInstance() { return new ReactSimpleTextShadowNode(); } /// <summary> /// Sets the font color for the node. /// </summary> /// <param name="view">The view.</param> /// <param name="color">The masked color value.</param> [ReactProp(ViewProps.Color, CustomType = "Color")] public void SetColor(TextBlock view, uint? color) { view.Foreground = color.HasValue ? new SolidColorBrush(ColorHelpers.Parse(color.Value)) : null; } /// <summary> /// Sets whether or not the text is selectable. /// </summary> /// <param name="view">The view.</param> /// <param name="selectable">A flag indicating whether or not the text is selectable.</param> [ReactProp("selectable")] public void SetSelectable(TextBlock view, bool selectable) { view.IsTextSelectionEnabled = selectable; } ///<summary> /// Sets <see cref="ImportantForAccessibility"/> for the TextBlock. /// </summary> /// <param name="view">The view.</param> /// <param name="importantForAccessibilityValue">The string to be parsed as <see cref="ImportantForAccessibility"/>.</param> [ReactProp(ViewProps.ImportantForAccessibility)] public void SetImportantForAccessibility(TextBlock view, string importantForAccessibilityValue) { var importantForAccessibility = EnumHelpers.ParseNullable<ImportantForAccessibility>(importantForAccessibilityValue) ?? ImportantForAccessibility.Auto; AccessibilityHelper.SetImportantForAccessibility(view, importantForAccessibility); } /// <summary> /// Sets whether or not the default context menu should be shown. /// </summary> /// <param name="view">The view.</param> /// <param name="disabled">A flag indicating whether or not the default context menu should be shown.</param> [ReactProp("disableContextMenu")] public void SetDisableContextMenu(TextBlock view, bool disabled) { if (disabled) { var found = _textBlockData.TryGetValue(view, out var data); if (!found) { data = new TextBlockData() { IsDefaultContextMenuDisabled = false }; _textBlockData.AddOrUpdate(view, data); } if (!data.IsDefaultContextMenuDisabled) { view.ContextMenuOpening += OnContextMenuOpening; data.IsDefaultContextMenuDisabled = true; } } else { _textBlockData.Remove(view); view.ContextMenuOpening -= OnContextMenuOpening; } } /// <summary> /// Receive extra updates from the shadow node. /// </summary> /// <param name="root">The root view.</param> /// <param name="extraData">The extra data.</param> public override void UpdateExtraData(TextBlock root, object extraData) { var textNode = extraData as ReactSimpleTextShadowNode; if (textNode != null) { textNode.UpdateTextBlock(root); } } /// <summary> /// Creates the view instance. /// </summary> /// <param name="reactContext">The React context.</param> /// <returns>The view instance.</returns> protected override TextBlock CreateViewInstance(ThemedReactContext reactContext) { var textBlock = new TextBlock { IsTextSelectionEnabled = false, TextAlignment = TextAlignment.DetectFromContent, TextTrimming = TextTrimming.CharacterEllipsis, TextWrapping = TextWrapping.Wrap, }; return textBlock; } /// <summary> /// Installing the event emitters for the TextBlock control. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="view">The TextBlock view instance.</param> protected override void AddEventEmitters(ThemedReactContext reactContext, TextBlock view) { base.AddEventEmitters(reactContext, view); view.SelectionChanged += OnSelectionChanged; } /// <summary> /// Called when view is detached from view hierarchy and allows for /// additional cleanup by the <see cref="ReactSimpleTextViewManager"/>. /// </summary> /// <param name="reactContext">The React context.</param> /// <param name="view">The view.</param> public override void OnDropViewInstance(ThemedReactContext reactContext, TextBlock view) { base.OnDropViewInstance(reactContext, view); view.SelectionChanged -= OnSelectionChanged; _textBlockData.Remove(view); view.ContextMenuOpening -= OnContextMenuOpening; } private void OnSelectionChanged(object sender, RoutedEventArgs e) { TextBlock view = sender as TextBlock; string selection; TextPointer selectionStart = view.SelectionStart; TextPointer selectionEnd = view.SelectionEnd; if (selectionStart == null || selectionEnd == null || selectionStart == selectionEnd) { selection = null; } else { selection = view.SelectedText; } // Fire the event. view.GetReactContext() .GetNativeModule<UIManagerModule>() .EventDispatcher .DispatchEvent( new ReactTextBlockSelectionEvent( view.GetTag(), selection)); } private void OnContextMenuOpening(object sender, ContextMenuEventArgs e) { // Prevent the opening of the context menu e.Handled = true; } private class TextBlockData { public bool IsDefaultContextMenuDisabled; } } }
using System; using System.Drawing; using System.Drawing.Imaging; namespace NBarCodes { /// <summary> /// Base class for barcodes. Defines common functionality. /// </summary> /// <remarks> /// This is the base class for creating barcodes, it defines common functionality like /// bar measures, text position and colors. /// </remarks> [Serializable] abstract class BarCode { private float barHeight = Defaults.BarHeight; private float offsetWidth = Defaults.OffsetWidth; private float offsetHeight = Defaults.OffsetHeight; private TextPosition textPosition = Defaults.TextPos; [NonSerialized] private IChecksum checksum = null; private Color barColor = Defaults.BarColor; private Color backColor = Defaults.BackColor; private Color fontColor = Defaults.FontColor; private Font font = Defaults.Font; private BarCodeUnit unit = Defaults.Unit; private int dpi = Defaults.Dpi; public virtual void ImportSettings(BarCode barCode) { barHeight = barCode.barHeight; offsetWidth = barCode.offsetWidth; offsetHeight = barCode.offsetHeight; textPosition = barCode.textPosition; barColor = barCode.barColor; backColor = barCode.backColor; fontColor = barCode.fontColor; font = barCode.font; if (this is IOptionalChecksum && barCode is IOptionalChecksum) { ((IOptionalChecksum)this).UseChecksum = ((IOptionalChecksum)barCode).UseChecksum; } } public float BarHeight { get { return barHeight; } set { barHeight = value; } } /// <summary> /// Gets or sets the margin offset width. /// </summary> /// <remarks> /// Gets or sets the margin offset width of the barcode. /// The side of the barcode (left or right) for which the margin offset width affects depends on the particular /// barcode implementation. /// </remarks> public float OffsetWidth { get { return offsetWidth; } set { offsetWidth = value; } } /// <summary> /// Gets or sets the margin offset height. /// </summary> /// <remarks> /// Gets or sets the margin offset height of the barcode. /// The side of the barcode (top or bottom) for which the margin offset height affects depends on the particular /// barcode implementation. /// </remarks> public float OffsetHeight { get { return offsetHeight; } set { offsetHeight = value; } } protected float TotalHeight { get { return OffsetHeight * 2 + BarHeight + ExtraHeight; } } protected virtual float ExtraHeight { get { if (TextPosition == TextPosition.All) return TextHeight * 2; return TextHeight; } } protected virtual float ExtraTopHeight { get { if ((TextPosition & TextPosition.Top) != 0) return TextHeight; return 0; } } public virtual TextPosition TextPosition { get { return textPosition; } set { textPosition = value; } } public virtual IChecksum Checksum { get { return checksum; } set { checksum = value; } } public abstract float QuietZone { get; } public Color BackColor { get { return backColor; } set { backColor = value; } } public Color BarColor { get { return barColor; } set { barColor = value; } } public Color FontColor { get { return fontColor; } set { fontColor = value; } } public Color ForeColor { get { return barColor; } set { barColor = fontColor = value; } } public Font Font { get { return font; } set { font = value; } } protected internal float TextHeight { get { if (textPosition != TextPosition.None) { return UnitConverter.Convert( font.GetHeight(Dpi), BarCodeUnit.Pixel, unit, Dpi); } return 0; } } protected float TextWidth { get { if (textPosition != TextPosition.None) { return UnitConverter.Convert( font.SizeInPoints / 72f, // a point is 1/72 inch BarCodeUnit.Inch, unit, Dpi); } return 0; } } public BarCodeUnit Unit { get { return unit; } set { unit = value; } } public int Dpi { get { return dpi; } set { dpi = value; } } public virtual void Build(IBarCodeBuilder builder, string data) { builder.Dpi = Dpi; builder.Unit = Unit; Draw(builder, data); } protected abstract void Draw(IBarCodeBuilder builder, string data); protected void DrawText(IBarCodeBuilder builder, float[] x, float y, params string[] data) { DrawText(builder, false, x, y, data); } protected void DrawText(IBarCodeBuilder builder, bool centered, float[] x, float y, params string[] data) { if ((TextPosition & TextPosition.Top) != 0) { for (int i = 0; i < x.Length; ++i) { builder.DrawString(Font, FontColor, centered, data[i], x[i], y); } } if ((TextPosition & TextPosition.Bottom) != 0) { for (int i = 0; i < x.Length; ++i) { builder.DrawString(Font, FontColor, centered, data[i], x[i], y + TextHeight + BarHeight); } } } public Image DrawImage(string data) { if (string.IsNullOrEmpty(data)) throw new BarCodeFormatException("No data to render."); var builder = new ImageBuilder(); Build(builder, data); return builder.GetImage(); } // TODO: Extra permissions!! public void SaveImage(string data, string fileName, ImageFormat format) { if (string.IsNullOrEmpty(data)) throw new BarCodeFormatException("No data to render."); using (var barCode = DrawImage(data)) { barCode.Save(fileName, format); } } public bool TestRender(string data, out string errorMessage) { if (string.IsNullOrEmpty(data)) { errorMessage = "No data to render."; return false; } try { NullBuilder builder = new NullBuilder(); Build(builder, data); errorMessage = null; return true; } catch (BarCodeFormatException ex) { errorMessage = ex.Message; return false; } } // TODO: SaveGif, DrawSvg, DrawHtml, etc ... } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmSetItem { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmSetItem() : base() { Load += frmSetItem_Load; KeyPress += frmSetItem_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; public System.Windows.Forms.Button _cmdClick_1; public System.Windows.Forms.Button _cmdClick_2; public System.Windows.Forms.Button _cmdClick_3; private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } private System.Windows.Forms.CheckedListBox withEventsField_lstStockItem; public System.Windows.Forms.CheckedListBox lstStockItem { get { return withEventsField_lstStockItem; } set { if (withEventsField_lstStockItem != null) { withEventsField_lstStockItem.SelectedIndexChanged -= lstStockItem_SelectedIndexChanged; } withEventsField_lstStockItem = value; if (withEventsField_lstStockItem != null) { withEventsField_lstStockItem.SelectedIndexChanged += lstStockItem_SelectedIndexChanged; } } } private System.Windows.Forms.TextBox withEventsField_txtSearch; public System.Windows.Forms.TextBox txtSearch { get { return withEventsField_txtSearch; } set { if (withEventsField_txtSearch != null) { withEventsField_txtSearch.KeyDown -= txtSearch_KeyDown; withEventsField_txtSearch.KeyPress -= txtSearch_KeyPress; } withEventsField_txtSearch = value; if (withEventsField_txtSearch != null) { withEventsField_txtSearch.KeyDown += txtSearch_KeyDown; withEventsField_txtSearch.KeyPress += txtSearch_KeyPress; } } } private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button1; public System.Windows.Forms.ToolStripButton _tbStockItem_Button1 { get { return withEventsField__tbStockItem_Button1; } set { if (withEventsField__tbStockItem_Button1 != null) { withEventsField__tbStockItem_Button1.Click -= tbStockItem_ButtonClick; } withEventsField__tbStockItem_Button1 = value; if (withEventsField__tbStockItem_Button1 != null) { withEventsField__tbStockItem_Button1.Click += tbStockItem_ButtonClick; } } } private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button2; public System.Windows.Forms.ToolStripButton _tbStockItem_Button2 { get { return withEventsField__tbStockItem_Button2; } set { if (withEventsField__tbStockItem_Button2 != null) { withEventsField__tbStockItem_Button2.Click -= tbStockItem_ButtonClick; } withEventsField__tbStockItem_Button2 = value; if (withEventsField__tbStockItem_Button2 != null) { withEventsField__tbStockItem_Button2.Click += tbStockItem_ButtonClick; } } } private System.Windows.Forms.ToolStripButton withEventsField__tbStockItem_Button3; public System.Windows.Forms.ToolStripButton _tbStockItem_Button3 { get { return withEventsField__tbStockItem_Button3; } set { if (withEventsField__tbStockItem_Button3 != null) { withEventsField__tbStockItem_Button3.Click -= tbStockItem_ButtonClick; } withEventsField__tbStockItem_Button3 = value; if (withEventsField__tbStockItem_Button3 != null) { withEventsField__tbStockItem_Button3.Click += tbStockItem_ButtonClick; } } } public System.Windows.Forms.ToolStrip tbStockItem; public System.Windows.Forms.ImageList ilSelect; public System.Windows.Forms.Label lblHeading; public System.Windows.Forms.Label _lbl_2; //Public WithEvents cmdClick As Microsoft.VisualBasic.Compatibility.VB6.ButtonArray //Public WithEvents lbl As Microsoft.VisualBasic.Compatibility.VB6.LabelArray //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(frmSetItem)); this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(components); this._cmdClick_1 = new System.Windows.Forms.Button(); this._cmdClick_2 = new System.Windows.Forms.Button(); this._cmdClick_3 = new System.Windows.Forms.Button(); this.cmdExit = new System.Windows.Forms.Button(); this.lstStockItem = new System.Windows.Forms.CheckedListBox(); this.txtSearch = new System.Windows.Forms.TextBox(); this.tbStockItem = new System.Windows.Forms.ToolStrip(); this._tbStockItem_Button1 = new System.Windows.Forms.ToolStripButton(); this._tbStockItem_Button2 = new System.Windows.Forms.ToolStripButton(); this._tbStockItem_Button3 = new System.Windows.Forms.ToolStripButton(); this.ilSelect = new System.Windows.Forms.ImageList(); this.lblHeading = new System.Windows.Forms.Label(); this._lbl_2 = new System.Windows.Forms.Label(); //Me.cmdClick = New Microsoft.VisualBasic.Compatibility.VB6.ButtonArray(components) //Me.lbl = New Microsoft.VisualBasic.Compatibility.VB6.LabelArray(components) this.tbStockItem.SuspendLayout(); this.SuspendLayout(); this.ToolTip1.Active = true; //CType(Me.cmdClick, System.ComponentModel.ISupportInitialize).BeginInit() //CType(Me.lbl, System.ComponentModel.ISupportInitialize).BeginInit() this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Text = "Allocate Stock Items to Set"; this.ClientSize = new System.Drawing.Size(232, 458); this.Location = new System.Drawing.Point(3, 22); this.ControlBox = false; this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.Enabled = true; this.Cursor = System.Windows.Forms.Cursors.Default; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.HelpButton = false; this.WindowState = System.Windows.Forms.FormWindowState.Normal; this.Name = "frmSetItem"; this._cmdClick_1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this._cmdClick_1.Text = "&A"; this._cmdClick_1.Size = new System.Drawing.Size(103, 34); this._cmdClick_1.Location = new System.Drawing.Point(303, 162); this._cmdClick_1.TabIndex = 8; this._cmdClick_1.TabStop = false; this._cmdClick_1.BackColor = System.Drawing.SystemColors.Control; this._cmdClick_1.CausesValidation = true; this._cmdClick_1.Enabled = true; this._cmdClick_1.ForeColor = System.Drawing.SystemColors.ControlText; this._cmdClick_1.Cursor = System.Windows.Forms.Cursors.Default; this._cmdClick_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._cmdClick_1.Name = "_cmdClick_1"; this._cmdClick_2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this._cmdClick_2.Text = "&S"; this._cmdClick_2.Size = new System.Drawing.Size(103, 34); this._cmdClick_2.Location = new System.Drawing.Point(306, 210); this._cmdClick_2.TabIndex = 7; this._cmdClick_2.TabStop = false; this._cmdClick_2.BackColor = System.Drawing.SystemColors.Control; this._cmdClick_2.CausesValidation = true; this._cmdClick_2.Enabled = true; this._cmdClick_2.ForeColor = System.Drawing.SystemColors.ControlText; this._cmdClick_2.Cursor = System.Windows.Forms.Cursors.Default; this._cmdClick_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._cmdClick_2.Name = "_cmdClick_2"; this._cmdClick_3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this._cmdClick_3.Text = "&U"; this._cmdClick_3.Size = new System.Drawing.Size(103, 34); this._cmdClick_3.Location = new System.Drawing.Point(297, 261); this._cmdClick_3.TabIndex = 6; this._cmdClick_3.TabStop = false; this._cmdClick_3.BackColor = System.Drawing.SystemColors.Control; this._cmdClick_3.CausesValidation = true; this._cmdClick_3.Enabled = true; this._cmdClick_3.ForeColor = System.Drawing.SystemColors.ControlText; this._cmdClick_3.Cursor = System.Windows.Forms.Cursors.Default; this._cmdClick_3.RightToLeft = System.Windows.Forms.RightToLeft.No; this._cmdClick_3.Name = "_cmdClick_3"; this.cmdExit.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.cmdExit.Text = "E&xit"; this.cmdExit.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.cmdExit.Size = new System.Drawing.Size(97, 52); this.cmdExit.Location = new System.Drawing.Point(126, 393); this.cmdExit.TabIndex = 4; this.cmdExit.TabStop = false; this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.CausesValidation = true; this.cmdExit.Enabled = true; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Name = "cmdExit"; this.lstStockItem.Size = new System.Drawing.Size(214, 304); this.lstStockItem.Location = new System.Drawing.Point(9, 81); this.lstStockItem.Sorted = true; this.lstStockItem.TabIndex = 1; this.lstStockItem.Tag = "0"; this.lstStockItem.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lstStockItem.BackColor = System.Drawing.SystemColors.Window; this.lstStockItem.CausesValidation = true; this.lstStockItem.Enabled = true; this.lstStockItem.ForeColor = System.Drawing.SystemColors.WindowText; this.lstStockItem.IntegralHeight = true; this.lstStockItem.Cursor = System.Windows.Forms.Cursors.Default; this.lstStockItem.SelectionMode = System.Windows.Forms.SelectionMode.One; this.lstStockItem.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lstStockItem.TabStop = true; this.lstStockItem.Visible = true; this.lstStockItem.MultiColumn = false; this.lstStockItem.Name = "lstStockItem"; this.txtSearch.AutoSize = false; this.txtSearch.Size = new System.Drawing.Size(175, 19); this.txtSearch.Location = new System.Drawing.Point(48, 57); this.txtSearch.TabIndex = 0; this.txtSearch.AcceptsReturn = true; this.txtSearch.TextAlign = System.Windows.Forms.HorizontalAlignment.Left; this.txtSearch.BackColor = System.Drawing.SystemColors.Window; this.txtSearch.CausesValidation = true; this.txtSearch.Enabled = true; this.txtSearch.ForeColor = System.Drawing.SystemColors.WindowText; this.txtSearch.HideSelection = true; this.txtSearch.ReadOnly = false; this.txtSearch.MaxLength = 0; this.txtSearch.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtSearch.Multiline = false; this.txtSearch.RightToLeft = System.Windows.Forms.RightToLeft.No; this.txtSearch.ScrollBars = System.Windows.Forms.ScrollBars.None; this.txtSearch.TabStop = true; this.txtSearch.Visible = true; this.txtSearch.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtSearch.Name = "txtSearch"; this.tbStockItem.ShowItemToolTips = true; this.tbStockItem.Size = new System.Drawing.Size(224, 40); this.tbStockItem.Location = new System.Drawing.Point(0, 18); this.tbStockItem.TabIndex = 2; this.tbStockItem.ImageList = ilSelect; this.tbStockItem.Name = "tbStockItem"; this._tbStockItem_Button1.Size = new System.Drawing.Size(68, 41); this._tbStockItem_Button1.AutoSize = false; this._tbStockItem_Button1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText; this._tbStockItem_Button1.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this._tbStockItem_Button1.Text = "&All"; this._tbStockItem_Button1.Name = "All"; this._tbStockItem_Button1.ImageIndex = 0; this._tbStockItem_Button1.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this._tbStockItem_Button2.Size = new System.Drawing.Size(68, 41); this._tbStockItem_Button2.AutoSize = false; this._tbStockItem_Button2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText; this._tbStockItem_Button2.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this._tbStockItem_Button2.Text = "&Selected"; this._tbStockItem_Button2.Name = "Selected"; this._tbStockItem_Button2.ImageIndex = 1; this._tbStockItem_Button2.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this._tbStockItem_Button3.Size = new System.Drawing.Size(68, 41); this._tbStockItem_Button3.AutoSize = false; this._tbStockItem_Button3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.ImageAndText; this._tbStockItem_Button3.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None; this._tbStockItem_Button3.Text = "&Unselected"; this._tbStockItem_Button3.Name = "Unselected"; this._tbStockItem_Button3.ImageIndex = 2; this._tbStockItem_Button3.TextImageRelation = System.Windows.Forms.TextImageRelation.ImageAboveText; this.ilSelect.ImageSize = new System.Drawing.Size(20, 20); this.ilSelect.TransparentColor = System.Drawing.Color.FromArgb(255, 0, 255); this.ilSelect.ImageStream = (System.Windows.Forms.ImageListStreamer)resources.GetObject("ilSelect.ImageStream"); this.ilSelect.Images.SetKeyName(0, ""); this.ilSelect.Images.SetKeyName(1, ""); this.ilSelect.Images.SetKeyName(2, ""); this.lblHeading.Text = "Label1"; this.lblHeading.Font = new System.Drawing.Font("Arial", 8.25f, System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, Convert.ToByte(178)); this.lblHeading.Size = new System.Drawing.Size(226, 19); this.lblHeading.Location = new System.Drawing.Point(0, 0); this.lblHeading.TabIndex = 5; this.lblHeading.TextAlign = System.Drawing.ContentAlignment.TopLeft; this.lblHeading.BackColor = System.Drawing.SystemColors.Control; this.lblHeading.Enabled = true; this.lblHeading.ForeColor = System.Drawing.SystemColors.ControlText; this.lblHeading.Cursor = System.Windows.Forms.Cursors.Default; this.lblHeading.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lblHeading.UseMnemonic = true; this.lblHeading.Visible = true; this.lblHeading.AutoSize = false; this.lblHeading.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.lblHeading.Name = "lblHeading"; this._lbl_2.Text = "Search:"; this._lbl_2.Size = new System.Drawing.Size(40, 13); this._lbl_2.Location = new System.Drawing.Point(6, 60); this._lbl_2.TabIndex = 3; this._lbl_2.TextAlign = System.Drawing.ContentAlignment.TopLeft; this._lbl_2.BackColor = System.Drawing.Color.Transparent; this._lbl_2.Enabled = true; this._lbl_2.ForeColor = System.Drawing.SystemColors.ControlText; this._lbl_2.Cursor = System.Windows.Forms.Cursors.Default; this._lbl_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._lbl_2.UseMnemonic = true; this._lbl_2.Visible = true; this._lbl_2.AutoSize = false; this._lbl_2.BorderStyle = System.Windows.Forms.BorderStyle.None; this._lbl_2.Name = "_lbl_2"; this.Controls.Add(_cmdClick_1); this.Controls.Add(_cmdClick_2); this.Controls.Add(_cmdClick_3); this.Controls.Add(cmdExit); this.Controls.Add(lstStockItem); this.Controls.Add(txtSearch); this.Controls.Add(tbStockItem); this.Controls.Add(lblHeading); this.Controls.Add(_lbl_2); this.tbStockItem.Items.Add(_tbStockItem_Button1); this.tbStockItem.Items.Add(_tbStockItem_Button2); this.tbStockItem.Items.Add(_tbStockItem_Button3); //Me.cmdClick.SetIndex(_cmdClick_1, CType(1, Short)) //Me.cmdClick.SetIndex(_cmdClick_2, CType(2, Short)) //Me.cmdClick.SetIndex(_cmdClick_3, CType(3, Short)) //Me.lbl.SetIndex(_lbl_2, CType(2, Short)) //CType(Me.lbl, System.ComponentModel.ISupportInitialize).EndInit() //CType(Me.cmdClick, System.ComponentModel.ISupportInitialize).EndInit() this.tbStockItem.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
using System; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Security; namespace AutoFixture.Idioms { /// <summary> /// Represents a verification error when testing whether a read-only property is correctly /// implemented. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "This exception's invariants require the propertyInfo to be present. Thus, constructors without the propertyInfo would violate the invarient. However, constructors matching the standard Exception constructors have been implemented.")] [Serializable] public class ConstructorInitializedMemberException : Exception { [NonSerialized] private readonly MemberInfo memberInfo; [NonSerialized] private readonly ParameterInfo missingParameter; /// <summary> /// Initializes a new instance of the <see cref="ConstructorInitializedMemberException"/> class. /// </summary> /// <param name="constructorInfo">The Constructor.</param> /// <param name="missingParameter">The parameter that was not exposed as a field or property.</param> public ConstructorInitializedMemberException(ConstructorInfo constructorInfo, ParameterInfo missingParameter) : this(constructorInfo, missingParameter, FormatDefaultMessage(constructorInfo, missingParameter)) { } /// <summary> /// Initializes a new instance of the <see cref="ConstructorInitializedMemberException"/> class. /// </summary> /// <param name="constructorInfo">The Constructor.</param> /// <param name="missingParameter">The parameter that was not exposed as a field or property.</param> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> public ConstructorInitializedMemberException(ConstructorInfo constructorInfo, ParameterInfo missingParameter, string message) : base(message) { this.memberInfo = constructorInfo; this.missingParameter = missingParameter; } /// <summary> /// Initializes a new instance of the <see cref="ConstructorInitializedMemberException"/> class. /// </summary> /// <param name="constructorInfo">The Constructor.</param> /// <param name="missingParameter">The parameter that was not exposed as a field or property.</param> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> /// <param name="innerException"> /// The exception that is the cause of the current exception. /// </param> public ConstructorInitializedMemberException( ConstructorInfo constructorInfo, ParameterInfo missingParameter, string message, Exception innerException) : base(message, innerException) { this.memberInfo = constructorInfo; this.missingParameter = missingParameter; } /// <summary> /// Initializes a new instance of the <see cref="ConstructorInitializedMemberException"/> class. /// </summary> /// <param name="fieldInfo">The field.</param> public ConstructorInitializedMemberException(FieldInfo fieldInfo) : this(fieldInfo, FormatDefaultMessage(fieldInfo)) { } /// <summary> /// Initializes a new instance of the <see cref="ConstructorInitializedMemberException"/> class. /// </summary> /// <param name="fieldInfo">The field.</param> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> public ConstructorInitializedMemberException(FieldInfo fieldInfo, string message) : base(message) { this.memberInfo = fieldInfo; } /// <summary> /// Initializes a new instance of the <see cref="ConstructorInitializedMemberException"/> class. /// </summary> /// <param name="fieldInfo">The field.</param> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> /// <param name="innerException"> /// The exception that is the cause of the current exception. /// </param> public ConstructorInitializedMemberException(FieldInfo fieldInfo, string message, Exception innerException) : base(message, innerException) { this.memberInfo = fieldInfo; } /// <summary> /// Initializes a new instance of the <see cref="ConstructorInitializedMemberException"/> class. /// </summary> /// <param name="propertyInfo">The property.</param> public ConstructorInitializedMemberException(PropertyInfo propertyInfo) : this(propertyInfo, ConstructorInitializedMemberException.FormatDefaultMessage(propertyInfo)) { } /// <summary> /// Initializes a new instance of the <see cref="ConstructorInitializedMemberException"/> class. /// </summary> /// <param name="propertyInfo">The property.</param> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> public ConstructorInitializedMemberException(PropertyInfo propertyInfo, string message) : base(message) { this.memberInfo = propertyInfo; } /// <summary> /// Initializes a new instance of the <see cref="ConstructorInitializedMemberException"/> class. /// </summary> /// <param name="propertyInfo">The property.</param> /// <param name="message"> /// The error message that explains the reason for the exception. /// </param> /// <param name="innerException"> /// The exception that is the cause of the current exception. /// </param> public ConstructorInitializedMemberException(PropertyInfo propertyInfo, string message, Exception innerException) : base(message, innerException) { this.memberInfo = propertyInfo; } /// <summary> /// Initializes a new instance of the <see cref="ConstructorInitializedMemberException"/> class with /// serialized data. /// </summary> /// <param name="info"> /// The <see cref="System.Runtime.Serialization.SerializationInfo"/> that holds the /// serialized object data about the exception being thrown. /// </param> /// <param name="context"> /// The <see cref="System.Runtime.Serialization.StreamingContext"/> that contains /// contextual information about the source or destination. /// </param> protected ConstructorInitializedMemberException(SerializationInfo info, StreamingContext context) : base(info, context) { this.memberInfo = (PropertyInfo)info.GetValue("memberInfo", typeof(MemberInfo)); } /// <summary> /// Gets the property or field supplied via the constructor. /// </summary> public MemberInfo MemberInfo => this.memberInfo; /// <summary> /// Gets the property supplied via the constructor. /// </summary> public PropertyInfo PropertyInfo => this.memberInfo as PropertyInfo; /// <summary> /// Gets the property supplied via the constructor. /// </summary> public FieldInfo FieldInfo => this.memberInfo as FieldInfo; /// <summary> /// Gets the constructor which has a <see cref="MissingParameter"/>. /// </summary> public ConstructorInfo ConstructorInfo => this.memberInfo as ConstructorInfo; /// <summary> /// Gets the parameter that was not exposed as a field or property. /// </summary> public ParameterInfo MissingParameter => this.missingParameter; /// <summary> /// Adds <see cref="PropertyInfo" /> to a /// <see cref="System.Runtime.Serialization.SerializationInfo"/>. /// </summary> /// <param name="info"> /// The <see cref="System.Runtime.Serialization.SerializationInfo"/> that holds the /// serialized object data about the exception being thrown. /// </param> /// <param name="context"> /// The <see cref="System.Runtime.Serialization.StreamingContext"/> that contains /// contextual information about the source or destination. /// </param> [SecurityCritical] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("memberInfo", this.memberInfo); } private static string FormatDefaultMessage(ConstructorInfo constructorInfo, ParameterInfo missingParameter) { return string.Format(CultureInfo.CurrentCulture, "The constructor {0} failed a test for having each parameter be exposed as a well-behaved read-only property or field. " + "The field {1} was not exposed publicly.{4}Declaring type: {2}{4}Reflected type: {3}{4}", constructorInfo, missingParameter.Name, constructorInfo.DeclaringType.AssemblyQualifiedName, constructorInfo.ReflectedType.AssemblyQualifiedName, Environment.NewLine); } private static string FormatDefaultMessage(PropertyInfo propertyInfo) { return string.Format( CultureInfo.CurrentCulture, "The property {0} failed a test for being well-behaved read-only property. " + "The getter does not return the value assigned to the constructor.{3}" + "Declaring type: {1}{3}Reflected type: {2}{3}", propertyInfo, propertyInfo.DeclaringType.AssemblyQualifiedName, propertyInfo.ReflectedType.AssemblyQualifiedName, Environment.NewLine); } private static string FormatDefaultMessage(FieldInfo fieldInfo) { return string.Format( CultureInfo.CurrentCulture, "The property {0} failed a test for being well-behaved read-only field. " + "The field does not return the value assigned to the constructor.{3}" + "Declaring type: {1}{3}Reflected type: {2}{3}", fieldInfo, fieldInfo.DeclaringType.AssemblyQualifiedName, fieldInfo.ReflectedType.AssemblyQualifiedName, Environment.NewLine); } } }
#nullable disable namespace AngleSharp.Html.Forms.Submitters.Json { using AngleSharp.Text; using System; using System.Collections.Generic; abstract class JsonStep { public Boolean Append { get; set; } public JsonStep Next { get; set; } public static IEnumerable<JsonStep> Parse(String path) { var steps = new List<JsonStep>(); var index = 0; while (index < path.Length && path[index] != Symbols.SquareBracketOpen) { index++; } if (index == 0) { return FailedJsonSteps(path); } steps.Add(new ObjectStep(path.Substring(0, index))); while (index < path.Length) { if (index + 1 >= path.Length || path[index] != Symbols.SquareBracketOpen) { return FailedJsonSteps(path); } else if (path[index + 1] == Symbols.SquareBracketClose) { steps[steps.Count - 1].Append = true; index += 2; if (index < path.Length) { return FailedJsonSteps(path); } } else if (path[index + 1].IsDigit()) { var start = ++index; while (index < path.Length && path[index] != Symbols.SquareBracketClose) { if (!path[index].IsDigit()) { return FailedJsonSteps(path); } index++; } if (index == path.Length) { return FailedJsonSteps(path); } steps.Add(new ArrayStep(path.Substring(start, index - start).ToInteger(0))); index++; } else { var start = ++index; while (index < path.Length && path[index] != Symbols.SquareBracketClose) { index++; } if (index == path.Length) { return FailedJsonSteps(path); } steps.Add(new ObjectStep(path.Substring(start, index - start))); index++; } } var n = steps.Count - 1; for (var i = 0; i < n; i++) { steps[i].Next = steps[i + 1]; } return steps; } static IEnumerable<JsonStep> FailedJsonSteps(String original) => new[] { new ObjectStep(original) }; protected abstract JsonElement CreateElement(); protected abstract JsonElement SetValue(JsonElement context, JsonElement value); protected abstract JsonElement GetValue(JsonElement context); protected abstract JsonElement ConvertArray(JsonArray value); public JsonElement Run(JsonElement context, JsonElement value, Boolean file = false) { if (Next is null) { return JsonEncodeLastValue(context, value, file); } else { return JsonEncodeValue(context, value, file); } } private JsonElement JsonEncodeValue(JsonElement context, JsonElement value, Boolean file) { var currentValue = GetValue(context); if (currentValue is null) { var newValue = Next.CreateElement(); return SetValue(context, newValue); } else if (currentValue is JsonObject) { return currentValue; } else if (currentValue is JsonArray) { return SetValue(context, Next.ConvertArray((JsonArray)currentValue)); } else { var obj = new JsonObject { [String.Empty] = currentValue }; return SetValue(context, obj); } } private JsonElement JsonEncodeLastValue(JsonElement context, JsonElement value, Boolean file) { var currentValue = GetValue(context); //undefined if (currentValue is null) { if (Append) { var arr = new JsonArray(1) { value }; value = arr; } SetValue(context, value); } else if (currentValue is JsonArray jsonArray) { jsonArray.Push(value); } else if (currentValue is JsonObject && !file) { var step = new ObjectStep(String.Empty); return step.JsonEncodeLastValue(currentValue, value, file: true); } else { var arr = new JsonArray(2) { currentValue, value }; SetValue(context, arr); } return context; } private sealed class ObjectStep : JsonStep { public ObjectStep(String key) { Key = key; } public String Key { get; } protected override JsonElement GetValue(JsonElement context) => context[Key]; protected override JsonElement SetValue(JsonElement context, JsonElement value) { context[Key] = value; return value; } protected override JsonElement CreateElement() => new JsonObject(); protected override JsonElement ConvertArray(JsonArray values) { var obj = new JsonObject(); for (var i = 0; i < values.Length; i++) { var item = values[i]; if (item != null) { obj[i.ToString()] = item; } } return obj; } } private sealed class ArrayStep : JsonStep { public ArrayStep(Int32 key) { Key = key; } public Int32 Key { get; } protected override JsonElement GetValue(JsonElement context) { if (context is JsonArray array) { return array[Key]; } return context[Key.ToString()]; } protected override JsonElement SetValue(JsonElement context, JsonElement value) { if (context is JsonArray array) { array[Key] = value; } else { context[Key.ToString()] = value; } return value; } protected override JsonElement CreateElement() => new JsonArray(); protected override JsonElement ConvertArray(JsonArray value) => value; } } }
// 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.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; //using Microsoft.Build.Execution; //using Microsoft.Build.Framework; //using Microsoft.Build.Logging; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Roslyn.Utilities; using MSB = Microsoft.Build; namespace Microsoft.CodeAnalysis.MSBuild { internal abstract class ProjectFile : IProjectFile { private readonly ProjectFileLoader _loader; private readonly MSB.Evaluation.Project _loadedProject; private readonly string _errorMessage; public ProjectFile(ProjectFileLoader loader, MSB.Evaluation.Project loadedProject, string errorMessage) { _loader = loader; _loadedProject = loadedProject; _errorMessage = errorMessage; } ~ProjectFile() { try { // unload project so collection will release global strings _loadedProject.ProjectCollection.UnloadAllProjects(); } catch { } } public virtual string FilePath { get { return _loadedProject.FullPath; } } public string ErrorMessage { get { return _errorMessage; } } public string GetPropertyValue(string name) { return _loadedProject.GetPropertyValue(name); } public abstract SourceCodeKind GetSourceCodeKind(string documentFileName); public abstract string GetDocumentExtension(SourceCodeKind kind); public abstract Task<ProjectFileInfo> GetProjectFileInfoAsync(CancellationToken cancellationToken); async Task<IProjectFileInfo> IProjectFile.GetProjectFileInfoAsync(CancellationToken cancellationToken) { var t = this.GetProjectFileInfoAsync(cancellationToken); await t.ConfigureAwait(false); return t.Result as IProjectFileInfo; } public struct BuildInfo { public readonly ProjectInstance Project; public readonly string ErrorMessage; public BuildInfo(ProjectInstance project, string errorMessage) { this.Project = project; this.ErrorMessage = errorMessage; } } protected async Task<BuildInfo> BuildAsync(string taskName, MSB.Framework.ITaskHost taskHost, CancellationToken cancellationToken) { // create a project instance to be executed by build engine. // The executed project will hold the final model of the project after execution via msbuild. var executedProject = _loadedProject.CreateProjectInstance(); if (!executedProject.Targets.ContainsKey("Compile")) { return new BuildInfo(executedProject, null); } var hostServices = new Microsoft.Build.Execution.HostServices(); // connect the host "callback" object with the host services, so we get called back with the exact inputs to the compiler task. hostServices.RegisterHostObject(_loadedProject.FullPath, "CoreCompile", taskName, taskHost); var buildParameters = new BuildParameters(_loadedProject.ProjectCollection); // capture errors that are output in the build log var errorBuilder = new StringWriter(); var errorLogger = new ErrorLogger(errorBuilder) { Verbosity = LoggerVerbosity.Normal }; buildParameters.Loggers = new ILogger[] { errorLogger }; var buildRequestData = new BuildRequestData(executedProject, new string[] { "Compile" }, hostServices); BuildResult result = await this.BuildAsync(buildParameters, buildRequestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); if (result.OverallResult == BuildResultCode.Failure) { if (result.Exception != null) { return new BuildInfo(executedProject, result.Exception.Message); } else { return new BuildInfo(executedProject, errorBuilder.ToString()); } } else { return new BuildInfo(executedProject, null); } } private class ErrorLogger : ILogger { private readonly TextWriter _writer; private bool _hasError; private IEventSource _eventSource; public string Parameters { get; set; } public LoggerVerbosity Verbosity { get; set; } public ErrorLogger(TextWriter writer) { _writer = writer; } public void Initialize(IEventSource eventSource) { _eventSource = eventSource; _eventSource.ErrorRaised += OnErrorRaised; } private void OnErrorRaised(object sender, BuildErrorEventArgs e) { if (_hasError) { _writer.WriteLine(); } _writer.Write($"{e.File}: ({e.LineNumber}, {e.ColumnNumber}): {e.Message}"); _hasError = true; } public void Shutdown() { if (_eventSource != null) { _eventSource.ErrorRaised -= OnErrorRaised; } } } // this lock is static because we are using the default build manager, and there is only one per process private static readonly SemaphoreSlim s_buildManagerLock = new SemaphoreSlim(initialCount: 1); private async Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildParameters parameters, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken) { // only allow one build to use the default build manager at a time using (await s_buildManagerLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(continueOnCapturedContext: false)) { return await BuildAsync(MSB.Execution.BuildManager.DefaultBuildManager, parameters, requestData, cancellationToken).ConfigureAwait(continueOnCapturedContext: false); } } private static Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildManager buildManager, MSB.Execution.BuildParameters parameters, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken) { var taskSource = new TaskCompletionSource<MSB.Execution.BuildResult>(); buildManager.BeginBuild(parameters); // enable cancellation of build CancellationTokenRegistration registration = default(CancellationTokenRegistration); if (cancellationToken.CanBeCanceled) { registration = cancellationToken.Register(() => { try { buildManager.CancelAllSubmissions(); buildManager.EndBuild(); registration.Dispose(); } finally { taskSource.TrySetCanceled(); } }); } // execute build async try { buildManager.PendBuildRequest(requestData).ExecuteAsync(sub => { // when finished try { var result = sub.BuildResult; buildManager.EndBuild(); registration.Dispose(); taskSource.TrySetResult(result); } catch (Exception e) { taskSource.TrySetException(e); } }, null); } catch (Exception e) { taskSource.SetException(e); } return taskSource.Task; } protected virtual string GetOutputDirectory() { var targetPath = _loadedProject.GetPropertyValue("TargetPath"); if (string.IsNullOrEmpty(targetPath)) { targetPath = _loadedProject.DirectoryPath; } return Path.GetDirectoryName(this.GetAbsolutePath(targetPath)); } protected virtual string GetAssemblyName() { var assemblyName = _loadedProject.GetPropertyValue("AssemblyName"); if (string.IsNullOrEmpty(assemblyName)) { assemblyName = Path.GetFileNameWithoutExtension(_loadedProject.FullPath); } return PathUtilities.GetFileName(assemblyName); } protected bool IsProjectReferenceOutputAssembly(MSB.Framework.ITaskItem item) { return item.GetMetadata("ReferenceOutputAssembly") == "true"; } protected IEnumerable<ProjectFileReference> GetProjectReferences(ProjectInstance executedProject) { return executedProject .GetItems("ProjectReference") .Where(i => !string.Equals( i.GetMetadataValue("ReferenceOutputAssembly"), bool.FalseString, StringComparison.OrdinalIgnoreCase)) .Select(CreateProjectFileReference); } /// <summary> /// Create a <see cref="ProjectFileReference"/> from a ProjectReference node in the MSBuild file. /// </summary> protected virtual ProjectFileReference CreateProjectFileReference(ProjectItemInstance reference) { return new ProjectFileReference( path: reference.EvaluatedInclude, aliases: ImmutableArray<string>.Empty); } protected virtual IEnumerable<MSB.Framework.ITaskItem> GetDocumentsFromModel(MSB.Execution.ProjectInstance executedProject) { return executedProject.GetItems("Compile"); } protected virtual IEnumerable<MSB.Framework.ITaskItem> GetMetadataReferencesFromModel(MSB.Execution.ProjectInstance executedProject) { return executedProject.GetItems("ReferencePath"); } protected virtual IEnumerable<MSB.Framework.ITaskItem> GetAnalyzerReferencesFromModel(MSB.Execution.ProjectInstance executedProject) { return executedProject.GetItems("Analyzer"); } protected virtual IEnumerable<MSB.Framework.ITaskItem> GetAdditionalFilesFromModel(MSB.Execution.ProjectInstance executedProject) { return executedProject.GetItems("AdditionalFiles"); } public MSB.Evaluation.ProjectProperty GetProperty(string name) { return _loadedProject.GetProperty(name); } protected IEnumerable<MSB.Framework.ITaskItem> GetTaskItems(MSB.Execution.ProjectInstance executedProject, string itemType) { return executedProject.GetItems(itemType); } protected string GetItemString(MSB.Execution.ProjectInstance executedProject, string itemType) { string text = ""; foreach (var item in executedProject.GetItems(itemType)) { if (text.Length > 0) { text = text + " "; } text = text + item.EvaluatedInclude; } return text; } protected string ReadPropertyString(MSB.Execution.ProjectInstance executedProject, string propertyName) { return this.ReadPropertyString(executedProject, propertyName, propertyName); } protected string ReadPropertyString(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName) { var executedProperty = executedProject.GetProperty(executedPropertyName); if (executedProperty != null) { return executedProperty.EvaluatedValue; } var evaluatedProperty = _loadedProject.GetProperty(evaluatedPropertyName); if (evaluatedProperty != null) { return evaluatedProperty.EvaluatedValue; } return null; } protected bool ReadPropertyBool(MSB.Execution.ProjectInstance executedProject, string propertyName) { return ConvertToBool(ReadPropertyString(executedProject, propertyName)); } protected bool ReadPropertyBool(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName) { return ConvertToBool(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName)); } private static bool ConvertToBool(string value) { return value != null && (string.Equals("true", value, StringComparison.OrdinalIgnoreCase) || string.Equals("On", value, StringComparison.OrdinalIgnoreCase)); } protected int ReadPropertyInt(MSB.Execution.ProjectInstance executedProject, string propertyName) { return ConvertToInt(ReadPropertyString(executedProject, propertyName)); } protected int ReadPropertyInt(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName) { return ConvertToInt(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName)); } private static int ConvertToInt(string value) { if (value == null) { return 0; } else { int.TryParse(value, out var result); return result; } } protected ulong ReadPropertyULong(MSB.Execution.ProjectInstance executedProject, string propertyName) { return ConvertToULong(ReadPropertyString(executedProject, propertyName)); } protected ulong ReadPropertyULong(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName) { return ConvertToULong(this.ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName)); } private static ulong ConvertToULong(string value) { if (value == null) { return 0; } else { ulong.TryParse(value, out var result); return result; } } protected TEnum? ReadPropertyEnum<TEnum>(MSB.Execution.ProjectInstance executedProject, string propertyName) where TEnum : struct { return ConvertToEnum<TEnum>(ReadPropertyString(executedProject, propertyName)); } protected TEnum? ReadPropertyEnum<TEnum>(MSB.Execution.ProjectInstance executedProject, string executedPropertyName, string evaluatedPropertyName) where TEnum : struct { return ConvertToEnum<TEnum>(ReadPropertyString(executedProject, executedPropertyName, evaluatedPropertyName)); } private static TEnum? ConvertToEnum<TEnum>(string value) where TEnum : struct { if (value == null) { return null; } else { if (Enum.TryParse<TEnum>(value, out var result)) { return result; } else { return null; } } } /// <summary> /// Resolves the given path that is possibly relative to the project directory. /// </summary> /// <remarks> /// The resulting path is absolute but might not be normalized. /// </remarks> protected string GetAbsolutePath(string path) { // TODO (tomat): should we report an error when drive-relative path (e.g. "C:foo.cs") is encountered? return Path.GetFullPath(FileUtilities.ResolveRelativePath(path, _loadedProject.DirectoryPath) ?? path); } protected string GetDocumentFilePath(MSB.Framework.ITaskItem documentItem) { return GetAbsolutePath(documentItem.ItemSpec); } protected static bool IsDocumentLinked(MSB.Framework.ITaskItem documentItem) { return !string.IsNullOrEmpty(documentItem.GetMetadata("Link")); } private IDictionary<string, MSB.Evaluation.ProjectItem> _documents; protected bool IsDocumentGenerated(MSB.Framework.ITaskItem documentItem) { if (_documents == null) { _documents = new Dictionary<string, MSB.Evaluation.ProjectItem>(); foreach (var item in _loadedProject.GetItems("compile")) { _documents[GetAbsolutePath(item.EvaluatedInclude)] = item; } } return !_documents.ContainsKey(GetAbsolutePath(documentItem.ItemSpec)); } protected static string GetDocumentLogicalPath(MSB.Framework.ITaskItem documentItem, string projectDirectory) { var link = documentItem.GetMetadata("Link"); if (!string.IsNullOrEmpty(link)) { // if a specific link is specified in the project file then use it to form the logical path. return link; } else { var result = documentItem.ItemSpec; if (Path.IsPathRooted(result)) { // If we have an absolute path, there are two possibilities: result = Path.GetFullPath(result); // If the document is within the current project directory (or subdirectory), then the logical path is the relative path // from the project's directory. if (result.StartsWith(projectDirectory, StringComparison.OrdinalIgnoreCase)) { result = result.Substring(projectDirectory.Length); } else { // if the document lies outside the project's directory (or subdirectory) then place it logically at the root of the project. // if more than one document ends up with the same logical name then so be it (the workspace will survive.) return Path.GetFileName(result); } } return result; } } protected string GetReferenceFilePath(ProjectItemInstance projectItem) { return GetAbsolutePath(projectItem.EvaluatedInclude); } public void AddDocument(string filePath, string logicalPath = null) { var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath); Dictionary<string, string> metadata = null; if (logicalPath != null && relativePath != logicalPath) { metadata = new Dictionary<string, string>(); metadata.Add("link", logicalPath); relativePath = filePath; // link to full path } _loadedProject.AddItem("Compile", relativePath, metadata); } public void RemoveDocument(string filePath) { var relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath); var items = _loadedProject.GetItems("Compile"); var item = items.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) || PathUtilities.PathsEqual(it.EvaluatedInclude, filePath)); if (item != null) { _loadedProject.RemoveItem(item); } } public void AddMetadataReference(MetadataReference reference, AssemblyIdentity identity) { var peRef = reference as PortableExecutableReference; if (peRef != null && peRef.FilePath != null) { var metadata = new Dictionary<string, string>(); if (!peRef.Properties.Aliases.IsEmpty) { metadata.Add("Aliases", string.Join(",", peRef.Properties.Aliases)); } if (IsInGAC(peRef.FilePath) && identity != null) { // Since the location of the reference is in GAC, need to use full identity name to find it again. // This typically happens when you base the reference off of a reflection assembly location. _loadedProject.AddItem("Reference", identity.GetDisplayName(), metadata); } else if (IsFrameworkReferenceAssembly(peRef.FilePath)) { // just use short name since this will be resolved by msbuild relative to the known framework reference assemblies. var fileName = identity != null ? identity.Name : Path.GetFileNameWithoutExtension(peRef.FilePath); _loadedProject.AddItem("Reference", fileName, metadata); } else // other location -- need hint to find correct assembly { string relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, peRef.FilePath); var fileName = Path.GetFileNameWithoutExtension(peRef.FilePath); metadata.Add("HintPath", relativePath); _loadedProject.AddItem("Reference", fileName, metadata); } } } private bool IsInGAC(string filePath) { return GlobalAssemblyCacheLocation.RootLocations.Any(gloc => PathUtilities.IsChildPath(gloc, filePath)); } private static string s_frameworkRoot; private static string FrameworkRoot { get { if (string.IsNullOrEmpty(s_frameworkRoot)) { var runtimeDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory(); s_frameworkRoot = Path.GetDirectoryName(runtimeDir); // back out one directory level to be root path of all framework versions } return s_frameworkRoot; } } private bool IsFrameworkReferenceAssembly(string filePath) { return PathUtilities.IsChildPath(FrameworkRoot, filePath); } public void RemoveMetadataReference(MetadataReference reference, AssemblyIdentity identity) { var peRef = reference as PortableExecutableReference; if (peRef != null && peRef.FilePath != null) { var item = FindReferenceItem(identity, peRef.FilePath); if (item != null) { _loadedProject.RemoveItem(item); } } } private MSB.Evaluation.ProjectItem FindReferenceItem(AssemblyIdentity identity, string filePath) { var references = _loadedProject.GetItems("Reference"); MSB.Evaluation.ProjectItem item = null; var fileName = Path.GetFileNameWithoutExtension(filePath); if (identity != null) { var shortAssemblyName = identity.Name; var fullAssemblyName = identity.GetDisplayName(); // check for short name match item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, shortAssemblyName, StringComparison.OrdinalIgnoreCase) == 0); // check for full name match if (item == null) { item = references.FirstOrDefault(it => string.Compare(it.EvaluatedInclude, fullAssemblyName, StringComparison.OrdinalIgnoreCase) == 0); } } // check for file path match if (item == null) { string relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, filePath); item = references.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, filePath) || PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) || PathUtilities.PathsEqual(GetHintPath(it), filePath) || PathUtilities.PathsEqual(GetHintPath(it), relativePath)); } // check for partial name match if (item == null && identity != null) { var partialName = identity.Name + ","; var items = references.Where(it => it.EvaluatedInclude.StartsWith(partialName, StringComparison.OrdinalIgnoreCase)).ToList(); if (items.Count == 1) { item = items[0]; } } return item; } //private string GetHintPath(MSB.Evaluation.ProjectItem item) //{ // return item.Metadata.FirstOrDefault(m => m.Name == "HintPath")?.EvaluatedValue ?? ""; //} //public void AddProjectReference(string projectName, IProjectFileReference reference) { AddProjectReference(projectName, reference); } //public void AddProjectReference(string projectName, ProjectFileReference reference) //{ // var metadata = new Dictionary<string, string>(); // metadata.Add("Name", projectName); // if (!reference.Aliases.IsEmpty) // { // metadata.Add("Aliases", string.Join(",", reference.Aliases)); // } // string relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, reference.Path); // _loadedProject.AddItem("ProjectReference", relativePath, metadata); //} //public void RemoveProjectReference(string projectName, string projectFilePath) //{ // string relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath); // var item = FindProjectReferenceItem(projectName, projectFilePath); // if (item != null) // { // _loadedProject.RemoveItem(item); // } //} //private MSB.Evaluation.ProjectItem FindProjectReferenceItem(string projectName, string projectFilePath) //{ // var references = _loadedProject.GetItems("ProjectReference"); // string relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, projectFilePath); // MSB.Evaluation.ProjectItem item = null; // // find by project file path // item = references.First(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) // || PathUtilities.PathsEqual(it.EvaluatedInclude, projectFilePath)); // // try to find by project name // if (item == null) // { // item = references.First(it => string.Compare(projectName, it.GetMetadataValue("Name"), StringComparison.OrdinalIgnoreCase) == 0); // } // return item; //} public void AddAnalyzerReference(AnalyzerReference reference) { var fileRef = reference as AnalyzerFileReference; if (fileRef != null) { string relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath); _loadedProject.AddItem("Analyzer", relativePath); } } public void RemoveAnalyzerReference(AnalyzerReference reference) { var fileRef = reference as AnalyzerFileReference; if (fileRef != null) { string relativePath = PathUtilities.GetRelativePath(_loadedProject.DirectoryPath, fileRef.FullPath); var analyzers = _loadedProject.GetItems("Analyzer"); var item = analyzers.FirstOrDefault(it => PathUtilities.PathsEqual(it.EvaluatedInclude, relativePath) || PathUtilities.PathsEqual(it.EvaluatedInclude, fileRef.FullPath)); if (item != null) { _loadedProject.RemoveItem(item); } } } public void Save() { _loadedProject.Save(); } internal static bool TryGetOutputKind(string outputKind, out OutputKind kind) { if (string.Equals(outputKind, "Library", StringComparison.OrdinalIgnoreCase)) { kind = OutputKind.DynamicallyLinkedLibrary; return true; } else if (string.Equals(outputKind, "Exe", StringComparison.OrdinalIgnoreCase)) { kind = OutputKind.ConsoleApplication; return true; } else if (string.Equals(outputKind, "WinExe", StringComparison.OrdinalIgnoreCase)) { kind = OutputKind.WindowsApplication; return true; } else if (string.Equals(outputKind, "Module", StringComparison.OrdinalIgnoreCase)) { kind = OutputKind.NetModule; return true; } else if (string.Equals(outputKind, "WinMDObj", StringComparison.OrdinalIgnoreCase)) { kind = OutputKind.WindowsRuntimeMetadata; return true; } else { kind = OutputKind.DynamicallyLinkedLibrary; return false; } } } }
/* * Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using Newtonsoft.Json; namespace XenAPI { /// <summary> /// A console /// First published in XenServer 4.0. /// </summary> public partial class Console : XenObject<Console> { #region Constructors public Console() { } public Console(string uuid, console_protocol protocol, string location, XenRef<VM> VM, Dictionary<string, string> other_config) { this.uuid = uuid; this.protocol = protocol; this.location = location; this.VM = VM; this.other_config = other_config; } /// <summary> /// Creates a new Console from a Hashtable. /// Note that the fields not contained in the Hashtable /// will be created with their default values. /// </summary> /// <param name="table"></param> public Console(Hashtable table) : this() { UpdateFrom(table); } /// <summary> /// Creates a new Console from a Proxy_Console. /// </summary> /// <param name="proxy"></param> public Console(Proxy_Console proxy) { UpdateFrom(proxy); } #endregion /// <summary> /// Updates each field of this instance with the value of /// the corresponding field of a given Console. /// </summary> public override void UpdateFrom(Console update) { uuid = update.uuid; protocol = update.protocol; location = update.location; VM = update.VM; other_config = update.other_config; } internal void UpdateFrom(Proxy_Console proxy) { uuid = proxy.uuid == null ? null : proxy.uuid; protocol = proxy.protocol == null ? (console_protocol) 0 : (console_protocol)Helper.EnumParseDefault(typeof(console_protocol), (string)proxy.protocol); location = proxy.location == null ? null : proxy.location; VM = proxy.VM == null ? null : XenRef<VM>.Create(proxy.VM); other_config = proxy.other_config == null ? null : Maps.convert_from_proxy_string_string(proxy.other_config); } public Proxy_Console ToProxy() { Proxy_Console result_ = new Proxy_Console(); result_.uuid = uuid ?? ""; result_.protocol = console_protocol_helper.ToString(protocol); result_.location = location ?? ""; result_.VM = VM ?? ""; result_.other_config = Maps.convert_to_proxy_string_string(other_config); return result_; } /// <summary> /// Given a Hashtable with field-value pairs, it updates the fields of this Console /// with the values listed in the Hashtable. Note that only the fields contained /// in the Hashtable will be updated and the rest will remain the same. /// </summary> /// <param name="table"></param> public void UpdateFrom(Hashtable table) { if (table.ContainsKey("uuid")) uuid = Marshalling.ParseString(table, "uuid"); if (table.ContainsKey("protocol")) protocol = (console_protocol)Helper.EnumParseDefault(typeof(console_protocol), Marshalling.ParseString(table, "protocol")); if (table.ContainsKey("location")) location = Marshalling.ParseString(table, "location"); if (table.ContainsKey("VM")) VM = Marshalling.ParseRef<VM>(table, "VM"); if (table.ContainsKey("other_config")) other_config = Maps.convert_from_proxy_string_string(Marshalling.ParseHashTable(table, "other_config")); } public bool DeepEquals(Console other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Helper.AreEqual2(this._uuid, other._uuid) && Helper.AreEqual2(this._protocol, other._protocol) && Helper.AreEqual2(this._location, other._location) && Helper.AreEqual2(this._VM, other._VM) && Helper.AreEqual2(this._other_config, other._other_config); } internal static List<Console> ProxyArrayToObjectList(Proxy_Console[] input) { var result = new List<Console>(); foreach (var item in input) result.Add(new Console(item)); return result; } public override string SaveChanges(Session session, string opaqueRef, Console server) { if (opaqueRef == null) { var reference = create(session, this); return reference == null ? null : reference.opaque_ref; } else { if (!Helper.AreEqual2(_other_config, server._other_config)) { Console.set_other_config(session, opaqueRef, _other_config); } return null; } } /// <summary> /// Get a record containing the current state of the given console. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_console">The opaque_ref of the given console</param> public static Console get_record(Session session, string _console) { if (session.JsonRpcClient != null) return session.JsonRpcClient.console_get_record(session.opaque_ref, _console); else return new Console(session.proxy.console_get_record(session.opaque_ref, _console ?? "").parse()); } /// <summary> /// Get a reference to the console instance with the specified UUID. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_uuid">UUID of object to return</param> public static XenRef<Console> get_by_uuid(Session session, string _uuid) { if (session.JsonRpcClient != null) return session.JsonRpcClient.console_get_by_uuid(session.opaque_ref, _uuid); else return XenRef<Console>.Create(session.proxy.console_get_by_uuid(session.opaque_ref, _uuid ?? "").parse()); } /// <summary> /// Create a new console instance, and return its handle. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Console> create(Session session, Console _record) { if (session.JsonRpcClient != null) return session.JsonRpcClient.console_create(session.opaque_ref, _record); else return XenRef<Console>.Create(session.proxy.console_create(session.opaque_ref, _record.ToProxy()).parse()); } /// <summary> /// Create a new console instance, and return its handle. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_record">All constructor arguments</param> public static XenRef<Task> async_create(Session session, Console _record) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_console_create(session.opaque_ref, _record); else return XenRef<Task>.Create(session.proxy.async_console_create(session.opaque_ref, _record.ToProxy()).parse()); } /// <summary> /// Destroy the specified console instance. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_console">The opaque_ref of the given console</param> public static void destroy(Session session, string _console) { if (session.JsonRpcClient != null) session.JsonRpcClient.console_destroy(session.opaque_ref, _console); else session.proxy.console_destroy(session.opaque_ref, _console ?? "").parse(); } /// <summary> /// Destroy the specified console instance. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_console">The opaque_ref of the given console</param> public static XenRef<Task> async_destroy(Session session, string _console) { if (session.JsonRpcClient != null) return session.JsonRpcClient.async_console_destroy(session.opaque_ref, _console); else return XenRef<Task>.Create(session.proxy.async_console_destroy(session.opaque_ref, _console ?? "").parse()); } /// <summary> /// Get the uuid field of the given console. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_console">The opaque_ref of the given console</param> public static string get_uuid(Session session, string _console) { if (session.JsonRpcClient != null) return session.JsonRpcClient.console_get_uuid(session.opaque_ref, _console); else return session.proxy.console_get_uuid(session.opaque_ref, _console ?? "").parse(); } /// <summary> /// Get the protocol field of the given console. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_console">The opaque_ref of the given console</param> public static console_protocol get_protocol(Session session, string _console) { if (session.JsonRpcClient != null) return session.JsonRpcClient.console_get_protocol(session.opaque_ref, _console); else return (console_protocol)Helper.EnumParseDefault(typeof(console_protocol), (string)session.proxy.console_get_protocol(session.opaque_ref, _console ?? "").parse()); } /// <summary> /// Get the location field of the given console. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_console">The opaque_ref of the given console</param> public static string get_location(Session session, string _console) { if (session.JsonRpcClient != null) return session.JsonRpcClient.console_get_location(session.opaque_ref, _console); else return session.proxy.console_get_location(session.opaque_ref, _console ?? "").parse(); } /// <summary> /// Get the VM field of the given console. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_console">The opaque_ref of the given console</param> public static XenRef<VM> get_VM(Session session, string _console) { if (session.JsonRpcClient != null) return session.JsonRpcClient.console_get_vm(session.opaque_ref, _console); else return XenRef<VM>.Create(session.proxy.console_get_vm(session.opaque_ref, _console ?? "").parse()); } /// <summary> /// Get the other_config field of the given console. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_console">The opaque_ref of the given console</param> public static Dictionary<string, string> get_other_config(Session session, string _console) { if (session.JsonRpcClient != null) return session.JsonRpcClient.console_get_other_config(session.opaque_ref, _console); else return Maps.convert_from_proxy_string_string(session.proxy.console_get_other_config(session.opaque_ref, _console ?? "").parse()); } /// <summary> /// Set the other_config field of the given console. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_console">The opaque_ref of the given console</param> /// <param name="_other_config">New value to set</param> public static void set_other_config(Session session, string _console, Dictionary<string, string> _other_config) { if (session.JsonRpcClient != null) session.JsonRpcClient.console_set_other_config(session.opaque_ref, _console, _other_config); else session.proxy.console_set_other_config(session.opaque_ref, _console ?? "", Maps.convert_to_proxy_string_string(_other_config)).parse(); } /// <summary> /// Add the given key-value pair to the other_config field of the given console. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_console">The opaque_ref of the given console</param> /// <param name="_key">Key to add</param> /// <param name="_value">Value to add</param> public static void add_to_other_config(Session session, string _console, string _key, string _value) { if (session.JsonRpcClient != null) session.JsonRpcClient.console_add_to_other_config(session.opaque_ref, _console, _key, _value); else session.proxy.console_add_to_other_config(session.opaque_ref, _console ?? "", _key ?? "", _value ?? "").parse(); } /// <summary> /// Remove the given key and its corresponding value from the other_config field of the given console. If the key is not in that Map, then do nothing. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> /// <param name="_console">The opaque_ref of the given console</param> /// <param name="_key">Key to remove</param> public static void remove_from_other_config(Session session, string _console, string _key) { if (session.JsonRpcClient != null) session.JsonRpcClient.console_remove_from_other_config(session.opaque_ref, _console, _key); else session.proxy.console_remove_from_other_config(session.opaque_ref, _console ?? "", _key ?? "").parse(); } /// <summary> /// Return a list of all the consoles known to the system. /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static List<XenRef<Console>> get_all(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.console_get_all(session.opaque_ref); else return XenRef<Console>.Create(session.proxy.console_get_all(session.opaque_ref).parse()); } /// <summary> /// Get all the console Records at once, in a single XML RPC call /// First published in XenServer 4.0. /// </summary> /// <param name="session">The session</param> public static Dictionary<XenRef<Console>, Console> get_all_records(Session session) { if (session.JsonRpcClient != null) return session.JsonRpcClient.console_get_all_records(session.opaque_ref); else return XenRef<Console>.Create<Proxy_Console>(session.proxy.console_get_all_records(session.opaque_ref).parse()); } /// <summary> /// Unique identifier/object reference /// </summary> public virtual string uuid { get { return _uuid; } set { if (!Helper.AreEqual(value, _uuid)) { _uuid = value; Changed = true; NotifyPropertyChanged("uuid"); } } } private string _uuid = ""; /// <summary> /// the protocol used by this console /// </summary> [JsonConverter(typeof(console_protocolConverter))] public virtual console_protocol protocol { get { return _protocol; } set { if (!Helper.AreEqual(value, _protocol)) { _protocol = value; Changed = true; NotifyPropertyChanged("protocol"); } } } private console_protocol _protocol; /// <summary> /// URI for the console service /// </summary> public virtual string location { get { return _location; } set { if (!Helper.AreEqual(value, _location)) { _location = value; Changed = true; NotifyPropertyChanged("location"); } } } private string _location = ""; /// <summary> /// VM to which this console is attached /// </summary> [JsonConverter(typeof(XenRefConverter<VM>))] public virtual XenRef<VM> VM { get { return _VM; } set { if (!Helper.AreEqual(value, _VM)) { _VM = value; Changed = true; NotifyPropertyChanged("VM"); } } } private XenRef<VM> _VM = new XenRef<VM>(Helper.NullOpaqueRef); /// <summary> /// additional configuration /// </summary> [JsonConverter(typeof(StringStringMapConverter))] public virtual Dictionary<string, string> other_config { get { return _other_config; } set { if (!Helper.AreEqual(value, _other_config)) { _other_config = value; Changed = true; NotifyPropertyChanged("other_config"); } } } private Dictionary<string, string> _other_config = new Dictionary<string, string>() {}; } }
using System; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace RedditSharp.Things { public class RedditUser : Thing { private const string OverviewUrl = "/user/{0}.json"; private const string CommentsUrl = "/user/{0}/comments.json"; private const string LinksUrl = "/user/{0}/submitted.json"; private const string SubscribedSubredditsUrl = "/subreddits/mine.json"; private const string LikedUrl = "/user/{0}/liked.json"; private const string DislikedUrl = "/user/{0}/disliked.json"; private const string SavedUrl = "/user/{0}/saved.json"; private const int MAX_LIMIT = 100; /// <summary> /// Initialize /// </summary> /// <param name="reddit"></param> /// <param name="json"></param> /// <param name="webAgent"></param> /// <returns>A reddit user</returns> public async Task<RedditUser> InitAsync(Reddit reddit, JToken json, IWebAgent webAgent) { CommonInit(reddit, json, webAgent); JsonConvert.PopulateObject(json["name"] == null ? json["data"].ToString() : json.ToString(), this, reddit.JsonSerializerSettings); return this; } /// <summary> /// Initialize /// </summary> /// <param name="reddit"></param> /// <param name="json"></param> /// <param name="webAgent"></param> /// <returns>A reddit user</returns> public RedditUser Init(Reddit reddit, JToken json, IWebAgent webAgent) { CommonInit(reddit, json, webAgent); JsonConvert.PopulateObject(json["name"] == null ? json["data"].ToString() : json.ToString(), this, reddit.JsonSerializerSettings); return this; } private void CommonInit(Reddit reddit, JToken json, IWebAgent webAgent) { base.Init(json); Reddit = reddit; WebAgent = webAgent; } /// <summary> /// Reddit username. /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// Returns true if the user has reddit gold. /// </summary> [JsonProperty("is_gold")] public bool HasGold { get; set; } /// <summary> /// Returns true if the user is a moderator of any subreddit. /// </summary> [JsonProperty("is_mod")] public bool IsModerator { get; set; } /// <summary> /// Total link karma of the user. /// </summary> [JsonProperty("link_karma")] public int LinkKarma { get; set; } /// <summary> /// Total comment karma of the user. /// </summary> [JsonProperty("comment_karma")] public int CommentKarma { get; set; } /// <summary> /// Date the user was created. /// </summary> [JsonProperty("created")] [JsonConverter(typeof(UnixTimestampConverter))] public DateTimeOffset Created { get; set; } /// <summary> /// Return the users overview. /// </summary> public Listing<VotableThing> Overview { get { return new Listing<VotableThing>(Reddit, string.Format(OverviewUrl, Name), WebAgent); } } /// <summary> /// Return a <see cref="Listing{T}"/> of posts liked by the logged in user. /// </summary> public Listing<Post> LikedPosts { get { return new Listing<Post>(Reddit, string.Format(LikedUrl, Name), WebAgent); } } /// <summary> /// Return a <see cref="Listing{T}"/> of posts disliked by the logged in user. /// </summary> public Listing<Post> DislikedPosts { get { return new Listing<Post>(Reddit, string.Format(DislikedUrl, Name), WebAgent); } } /// <summary> /// Return a <see cref="Listing{T}"/> of comments made by the user. /// </summary> public Listing<Comment> Comments { get { return new Listing<Comment>(Reddit, string.Format(CommentsUrl, Name), WebAgent); } } /// <summary> /// Return a <see cref="Listing{T}"/> of posts made by the user. /// </summary> public Listing<Post> Posts { get { return new Listing<Post>(Reddit, string.Format(LinksUrl, Name), WebAgent); } } /// <summary> /// Return a list of subscribed subreddits for the logged in user. /// </summary> public Listing<Subreddit> SubscribedSubreddits { get { return new Listing<Subreddit>(Reddit, SubscribedSubredditsUrl, WebAgent); } } /// <summary> /// Get a listing of comments and posts from the user sorted by <paramref name="sorting"/>, from time <paramref name="fromTime"/> /// and limited to <paramref name="limit"/>. /// </summary> /// <param name="sorting">How to sort the comments (hot, new, top, controversial).</param> /// <param name="limit">How many comments to fetch per request. Max is 100.</param> /// <param name="fromTime">What time frame of comments to show (hour, day, week, month, year, all).</param> /// <returns>The listing of comments requested.</returns> public Listing<VotableThing> GetOverview(Sort sorting = Sort.New, int limit = 25, FromTime fromTime = FromTime.All) { if ((limit < 1) || (limit > MAX_LIMIT)) throw new ArgumentOutOfRangeException("limit", "Valid range: [1," + MAX_LIMIT + "]"); string overviewUrl = string.Format(OverviewUrl, Name); overviewUrl += string.Format("?sort={0}&limit={1}&t={2}", Enum.GetName(typeof(Sort), sorting), limit, Enum.GetName(typeof(FromTime), fromTime)); return new Listing<VotableThing>(Reddit, overviewUrl, WebAgent); } /// <summary> /// Get a listing of comments from the user sorted by <paramref name="sorting"/>, from time <paramref name="fromTime"/> /// and limited to <paramref name="limit"/>. /// </summary> /// <param name="sorting">How to sort the comments (hot, new, top, controversial).</param> /// <param name="limit">How many comments to fetch per request. Max is 100.</param> /// <param name="fromTime">What time frame of comments to show (hour, day, week, month, year, all).</param> /// <returns>The listing of comments requested.</returns> public Listing<Comment> GetComments(Sort sorting = Sort.New, int limit = 25, FromTime fromTime = FromTime.All) { if ((limit < 1) || (limit > MAX_LIMIT)) throw new ArgumentOutOfRangeException("limit", "Valid range: [1," + MAX_LIMIT + "]"); string commentsUrl = string.Format(CommentsUrl, Name); commentsUrl += string.Format("?sort={0}&limit={1}&t={2}", Enum.GetName(typeof(Sort), sorting), limit, Enum.GetName(typeof(FromTime), fromTime)); return new Listing<Comment>(Reddit, commentsUrl, WebAgent); } /// <summary> /// Get a listing of posts from the user sorted by <paramref name="sorting"/>, from time <paramref name="fromTime"/> /// and limited to <paramref name="limit"/>. /// </summary> /// <param name="sorting">How to sort the posts (hot, new, top, controversial).</param> /// <param name="limit">How many posts to fetch per request. Max is 100.</param> /// <param name="fromTime">What time frame of posts to show (hour, day, week, month, year, all).</param> /// <returns>The listing of posts requested.</returns> public Listing<Post> GetPosts(Sort sorting = Sort.New, int limit = 25, FromTime fromTime = FromTime.All) { if ((limit < 1) || (limit > 100)) throw new ArgumentOutOfRangeException("limit", "Valid range: [1,100]"); string linksUrl = string.Format(LinksUrl, Name); linksUrl += string.Format("?sort={0}&limit={1}&t={2}", Enum.GetName(typeof(Sort), sorting), limit, Enum.GetName(typeof(FromTime), fromTime)); return new Listing<Post>(Reddit, linksUrl, WebAgent); } /// <summary> /// Get a listing of comments and posts saved by the user sorted by <paramref name="sorting"/>, from time <paramref name="fromTime"/> /// and limited to <paramref name="limit"/>. /// </summary> /// <param name="sorting">How to sort the comments (hot, new, top, controversial).</param> /// <param name="limit">How many comments to fetch per request. Max is 100.</param> /// <param name="fromTime">What time frame of comments to show (hour, day, week, month, year, all).</param> /// <returns>The listing of posts and/or comments requested that the user saved.</returns> public Listing<VotableThing> GetSaved(Sort sorting = Sort.New, int limit = 25, FromTime fromTime = FromTime.All) { if ((limit < 1) || (limit > MAX_LIMIT)) throw new ArgumentOutOfRangeException("limit", "Valid range: [1," + MAX_LIMIT + "]"); string savedUrl = string.Format(SavedUrl, Name); savedUrl += string.Format("?sort={0}&limit={1}&t={2}", Enum.GetName(typeof(Sort), sorting), limit, Enum.GetName(typeof(FromTime), fromTime)); return new Listing<VotableThing>(Reddit, savedUrl, WebAgent); } /// <inheritdoc/> public override string ToString() { return Name; } #region Obsolete Getter Methods [Obsolete("Use Overview property instead")] public Listing<VotableThing> GetOverview() { return Overview; } [Obsolete("Use Comments property instead")] public Listing<Comment> GetComments() { return Comments; } [Obsolete("Use Posts property instead")] public Listing<Post> GetPosts() { return Posts; } [Obsolete("Use SubscribedSubreddits property instead")] public Listing<Subreddit> GetSubscribedSubreddits() { return SubscribedSubreddits; } #endregion Obsolete Getter Methods } public enum Sort { New, Hot, Top, Controversial } public enum FromTime { All, Year, Month, Week, Day, Hour } }
S/W Version Information Model: SM-R770 Tizen-Version: 2.3.2.1 Build-Number: R770XXU1APK6 Build-Date: 2016.11.25 15:41:21 Crash Information Process Name: devapp PID: 5670 Date: 2017-04-18 22:53:13-0400 Executable File Path: /opt/usr/apps/edu.umich.edu.yctung.devapp/bin/devapp Signal: 11 (SIGSEGV) si_code: -6 signal sent by tkill (sent by pid 5670, uid 5000) Register Information r0 = 0x00904c00, r1 = 0x00000002 r2 = 0x00000000, r3 = 0x00000000 r4 = 0xf7625848, r5 = 0xf6d669d8 r6 = 0xf08ed100, r7 = 0xf08eca48 r8 = 0xf6d669e8, r9 = 0xf76258d0 r10 = 0xf6d669e8, fp = 0x00000000 ip = 0xf08ed184, sp = 0xf08ec9a0 lr = 0xf5c80ed5, pc = 0xf5c80ed8 cpsr = 0x00000030 Memory Information MemTotal: 714608 KB MemFree: 36508 KB Buffers: 36176 KB Cached: 220532 KB VmPeak: 124756 KB VmSize: 124752 KB VmLck: 0 KB VmPin: 0 KB VmHWM: 32776 KB VmRSS: 32776 KB VmData: 46428 KB VmStk: 6948 KB VmExe: 20 KB VmLib: 25340 KB VmPTE: 148 KB VmSwap: 0 KB Threads Information Threads: 6 PID = 5670 TID = 5786 5670 5770 5771 5772 5785 5786 Maps Information f00ef000 f08ee000 rw-p [stack:5786] f08ef000 f10ee000 rw-p [stack:5785] f10ee000 f10ef000 r-xp /usr/lib/evas/modules/savers/jpeg/linux-gnueabi-armv7l-1.7.99/module.so f10f7000 f10fa000 r-xp /usr/lib/evas/modules/engines/buffer/linux-gnueabi-armv7l-1.7.99/module.so f1131000 f113c000 r-xp /usr/lib/libcapi-media-sound-manager.so.0.1.54 f1144000 f1146000 r-xp /usr/lib/libcapi-media-wav-player.so.0.1.11 f114e000 f114f000 r-xp /usr/lib/libmmfkeysound.so.0.0.0 f1157000 f115f000 r-xp /usr/lib/libfeedback.so.0.1.4 f1178000 f1179000 r-xp /usr/lib/edje/modules/feedback/linux-gnueabi-armv7l-1.0.0/module.so f133e000 f1b3d000 rw-p [stack:5772] f1f3f000 f273e000 rw-p [stack:5771] f2b40000 f333f000 rw-p [stack:5770] f3401000 f3418000 r-xp /usr/lib/edje/modules/elm/linux-gnueabi-armv7l-1.0.0/module.so f3425000 f342a000 r-xp /usr/lib/bufmgr/libtbm_exynos.so.0.0.0 f3432000 f343d000 r-xp /usr/lib/evas/modules/engines/software_generic/linux-gnueabi-armv7l-1.7.99/module.so f3765000 f3857000 r-xp /usr/lib/libCOREGL.so.4.0 f3870000 f3875000 r-xp /usr/lib/libsystem.so.0.0.0 f387f000 f3880000 r-xp /usr/lib/libresponse.so.0.2.96 f3888000 f388d000 r-xp /usr/lib/libproc-stat.so.0.2.96 f3896000 f3898000 r-xp /usr/lib/libpkgmgr_installer_status_broadcast_server.so.0.1.0 f38a0000 f38a7000 r-xp /usr/lib/libpkgmgr_installer_client.so.0.1.0 f38b0000 f38d2000 r-xp /usr/lib/libpkgmgr-client.so.0.1.68 f38db000 f38e3000 r-xp /usr/lib/libcapi-appfw-package-manager.so.0.0.59 f38eb000 f38f1000 r-xp /usr/lib/libcapi-appfw-app-manager.so.0.2.8 f38fa000 f38ff000 r-xp /usr/lib/libcapi-media-tool.so.0.1.5 f3907000 f3928000 r-xp /usr/lib/libexif.so.12.3.3 f393b000 f3954000 r-xp /usr/lib/libprivacy-manager-client.so.0.0.8 f395c000 f3961000 r-xp /usr/lib/libmmutil_imgp.so.0.0.0 f3969000 f396f000 r-xp /usr/lib/libmmutil_jpeg.so.0.0.0 f3977000 f397b000 r-xp /usr/lib/libogg.so.0.7.1 f3983000 f39a5000 r-xp /usr/lib/libvorbis.so.0.4.3 f39ad000 f39af000 r-xp /usr/lib/libttrace.so.1.1 f39b7000 f39b9000 r-xp /usr/lib/libdri2.so.0.0.0 f39c1000 f39c9000 r-xp /usr/lib/libdrm.so.2.4.0 f39d1000 f39d2000 r-xp /usr/lib/libsecurity-privilege-checker.so.1.0.1 f39db000 f39de000 r-xp /usr/lib/libcapi-media-image-util.so.0.3.5 f39e6000 f39f5000 r-xp /usr/lib/libmdm-common.so.1.1.22 f39fe000 f3a45000 r-xp /usr/lib/libsndfile.so.1.0.26 f3a51000 f3a9a000 r-xp /usr/lib/pulseaudio/libpulsecommon-4.0.so f3aa3000 f3aa8000 r-xp /usr/lib/libjson.so.0.0.1 f3ab0000 f3ab3000 r-xp /usr/lib/libtinycompress.so.0.0.0 f3abb000 f3ac1000 r-xp /usr/lib/libxcb-render.so.0.0.0 f3ac9000 f3aca000 r-xp /usr/lib/libxcb-shm.so.0.0.0 f3ad3000 f3ad7000 r-xp /usr/lib/libEGL.so.1.4 f3ae7000 f3af8000 r-xp /usr/lib/libGLESv2.so.2.0 f3b08000 f3b13000 r-xp /usr/lib/libtbm.so.1.0.0 f3b1b000 f3b3e000 r-xp /usr/lib/libui-extension.so.0.1.0 f3b47000 f3b5d000 r-xp /usr/lib/libtts.so f3b66000 f3bae000 r-xp /usr/lib/libmdm.so.1.2.62 f5440000 f5546000 r-xp /usr/lib/libicuuc.so.57.1 f555c000 f56e4000 r-xp /usr/lib/libicui18n.so.57.1 f56f4000 f5701000 r-xp /usr/lib/libail.so.0.1.0 f570a000 f570d000 r-xp /usr/lib/libsyspopup_caller.so.0.1.0 f5715000 f574d000 r-xp /usr/lib/libpulse.so.0.16.2 f574e000 f5751000 r-xp /usr/lib/libpulse-simple.so.0.0.4 f5759000 f57ba000 r-xp /usr/lib/libasound.so.2.0.0 f57c4000 f57da000 r-xp /usr/lib/libavsysaudio.so.0.0.1 f57e2000 f57e9000 r-xp /usr/lib/libmmfcommon.so.0.0.0 f57f1000 f57f5000 r-xp /usr/lib/libmmfsoundcommon.so.0.0.0 f57fd000 f5808000 r-xp /usr/lib/libaudio-session-mgr.so.0.0.0 f5815000 f5819000 r-xp /usr/lib/libmmfsession.so.0.0.0 f5822000 f5829000 r-xp /usr/lib/libminizip.so.1.0.0 f5831000 f58e9000 r-xp /usr/lib/libcairo.so.2.11200.14 f58f4000 f5906000 r-xp /usr/lib/libefl-assist.so.0.1.0 f590e000 f5913000 r-xp /usr/lib/libcapi-system-info.so.0.2.0 f591b000 f5932000 r-xp /usr/lib/libmmfsound.so.0.1.0 f5944000 f5949000 r-xp /usr/lib/libstorage.so.0.1 f5951000 f5972000 r-xp /usr/lib/libefl-extension.so.0.1.0 f597a000 f5981000 r-xp /usr/lib/libcapi-media-audio-io.so.0.2.23 f598c000 f5997000 r-xp /usr/lib/evas/modules/engines/software_x11/linux-gnueabi-armv7l-1.7.99/module.so f5b31000 f5b3b000 r-xp /lib/libnss_files-2.13.so f5b44000 f5c13000 r-xp /usr/lib/libscim-1.0.so.8.2.3 f5c29000 f5c4d000 r-xp /usr/lib/ecore/immodules/libisf-imf-module.so f5c56000 f5c5c000 r-xp /usr/lib/libappsvc.so.0.1.0 f5c64000 f5c66000 r-xp /usr/lib/libcapi-appfw-app-common.so.0.3.2.5 f5c6f000 f5c73000 r-xp /usr/lib/libcapi-appfw-app-control.so.0.3.2.5 f5c7f000 f5c82000 r-xp /opt/usr/apps/edu.umich.edu.yctung.devapp/bin/devapp f5c92000 f5c94000 r-xp /usr/lib/libiniparser.so.0 f5c9d000 f5ca2000 r-xp /usr/lib/libappcore-common.so.1.1 f5cab000 f5cb3000 r-xp /usr/lib/libcapi-system-system-settings.so.0.0.2 f5cb4000 f5cb8000 r-xp /usr/lib/libcapi-appfw-application.so.0.3.2.5 f5cc5000 f5cc7000 r-xp /usr/lib/libXau.so.6.0.0 f5ccf000 f5cd6000 r-xp /lib/libcrypt-2.13.so f5d06000 f5d08000 r-xp /usr/lib/libiri.so f5d11000 f5eba000 r-xp /usr/lib/libcrypto.so.1.0.0 f5eda000 f5f21000 r-xp /usr/lib/libssl.so.1.0.0 f5f2d000 f5f5b000 r-xp /usr/lib/libidn.so.11.5.44 f5f63000 f5f6c000 r-xp /usr/lib/libcares.so.2.1.0 f5f76000 f5f89000 r-xp /usr/lib/libxcb.so.1.1.0 f5f92000 f5f94000 r-xp /usr/lib/journal/libjournal.so.0.1.0 f5f9c000 f5f9e000 r-xp /usr/lib/libSLP-db-util.so.0.1.0 f5fa7000 f6073000 r-xp /usr/lib/libxml2.so.2.7.8 f6080000 f6082000 r-xp /usr/lib/libgmodule-2.0.so.0.3200.3 f608b000 f6090000 r-xp /usr/lib/libffi.so.5.0.10 f6098000 f6099000 r-xp /usr/lib/libgthread-2.0.so.0.3200.3 f60a1000 f60a4000 r-xp /lib/libattr.so.1.1.0 f60ac000 f6140000 r-xp /usr/lib/libstdc++.so.6.0.16 f6153000 f6170000 r-xp /usr/lib/libsecurity-server-commons.so.1.0.0 f617a000 f6192000 r-xp /usr/lib/libpng12.so.0.50.0 f619a000 f61b0000 r-xp /lib/libexpat.so.1.6.0 f61ba000 f61fe000 r-xp /usr/lib/libcurl.so.4.3.0 f6207000 f6211000 r-xp /usr/lib/libXext.so.6.4.0 f621a000 f621e000 r-xp /usr/lib/libXtst.so.6.1.0 f6226000 f622c000 r-xp /usr/lib/libXrender.so.1.3.0 f6234000 f623a000 r-xp /usr/lib/libXrandr.so.2.2.0 f6242000 f6243000 r-xp /usr/lib/libXinerama.so.1.0.0 f624c000 f6255000 r-xp /usr/lib/libXi.so.6.1.0 f625d000 f6260000 r-xp /usr/lib/libXfixes.so.3.1.0 f6268000 f626a000 r-xp /usr/lib/libXgesture.so.7.0.0 f6272000 f6274000 r-xp /usr/lib/libXcomposite.so.1.0.0 f627c000 f627e000 r-xp /usr/lib/libXdamage.so.1.1.0 f6286000 f628d000 r-xp /usr/lib/libXcursor.so.1.0.2 f6295000 f6298000 r-xp /usr/lib/libecore_input_evas.so.1.7.99 f62a0000 f62a4000 r-xp /usr/lib/libecore_ipc.so.1.7.99 f62ad000 f62b2000 r-xp /usr/lib/libecore_fb.so.1.7.99 f62bb000 f639c000 r-xp /usr/lib/libX11.so.6.3.0 f63a7000 f63ca000 r-xp /usr/lib/libjpeg.so.8.0.2 f63e2000 f63f8000 r-xp /lib/libz.so.1.2.5 f6400000 f6402000 r-xp /usr/lib/libsecurity-extension-common.so.1.0.1 f640a000 f647f000 r-xp /usr/lib/libsqlite3.so.0.8.6 f6489000 f64a3000 r-xp /usr/lib/libpkgmgr_parser.so.0.1.0 f64ab000 f64df000 r-xp /usr/lib/libgobject-2.0.so.0.3200.3 f64e8000 f65bb000 r-xp /usr/lib/libgio-2.0.so.0.3200.3 f65c6000 f65d6000 r-xp /lib/libresolv-2.13.so f65da000 f65f2000 r-xp /usr/lib/liblzma.so.5.0.3 f65fa000 f65fd000 r-xp /lib/libcap.so.2.21 f6605000 f6634000 r-xp /usr/lib/libsecurity-server-client.so.1.0.1 f663c000 f663d000 r-xp /usr/lib/libecore_imf_evas.so.1.7.99 f6645000 f664b000 r-xp /usr/lib/libecore_imf.so.1.7.99 f6653000 f666a000 r-xp /usr/lib/liblua-5.1.so f6673000 f667a000 r-xp /usr/lib/libembryo.so.1.7.99 f6682000 f6688000 r-xp /lib/librt-2.13.so f6691000 f66e7000 r-xp /usr/lib/libpixman-1.so.0.28.2 f66f4000 f674a000 r-xp /usr/lib/libfreetype.so.6.11.3 f6756000 f677e000 r-xp /usr/lib/libfontconfig.so.1.8.0 f677f000 f67c4000 r-xp /usr/lib/libharfbuzz.so.0.10200.4 f67cd000 f67e0000 r-xp /usr/lib/libfribidi.so.0.3.1 f67e8000 f6802000 r-xp /usr/lib/libecore_con.so.1.7.99 f680b000 f6814000 r-xp /usr/lib/libedbus.so.1.7.99 f681c000 f686c000 r-xp /usr/lib/libecore_x.so.1.7.99 f686e000 f6877000 r-xp /usr/lib/libvconf.so.0.2.45 f687f000 f6890000 r-xp /usr/lib/libecore_input.so.1.7.99 f6898000 f689d000 r-xp /usr/lib/libecore_file.so.1.7.99 f68a5000 f68c7000 r-xp /usr/lib/libecore_evas.so.1.7.99 f68d0000 f6911000 r-xp /usr/lib/libeina.so.1.7.99 f691a000 f6933000 r-xp /usr/lib/libeet.so.1.7.99 f6944000 f69ad000 r-xp /lib/libm-2.13.so f69b6000 f69bc000 r-xp /usr/lib/libcapi-base-common.so.0.1.8 f69c5000 f69c6000 r-xp /usr/lib/libsecurity-extension-interface.so.1.0.1 f69ce000 f69f1000 r-xp /usr/lib/libpkgmgr-info.so.0.0.17 f69f9000 f69fe000 r-xp /usr/lib/libxdgmime.so.1.1.0 f6a06000 f6a30000 r-xp /usr/lib/libdbus-1.so.3.8.12 f6a39000 f6a50000 r-xp /usr/lib/libdbus-glib-1.so.2.2.2 f6a58000 f6a63000 r-xp /lib/libunwind.so.8.0.1 f6a90000 f6aae000 r-xp /usr/lib/libsystemd.so.0.4.0 f6ab8000 f6bdc000 r-xp /lib/libc-2.13.so f6bea000 f6bf2000 r-xp /lib/libgcc_s-4.6.so.1 f6bf3000 f6bf7000 r-xp /usr/lib/libsmack.so.1.0.0 f6c00000 f6c06000 r-xp /usr/lib/libprivilege-control.so.0.0.2 f6c0e000 f6cde000 r-xp /usr/lib/libglib-2.0.so.0.3200.3 f6cdf000 f6d3d000 r-xp /usr/lib/libedje.so.1.7.99 f6d47000 f6d5e000 r-xp /usr/lib/libecore.so.1.7.99 f6d75000 f6e43000 r-xp /usr/lib/libevas.so.1.7.99 f6e68000 f6fa4000 r-xp /usr/lib/libelementary.so.1.7.99 f6fbb000 f6fcf000 r-xp /lib/libpthread-2.13.so f6fda000 f6fdc000 r-xp /usr/lib/libdlog.so.0.0.0 f6fe4000 f6fe7000 r-xp /usr/lib/libbundle.so.0.1.22 f6fef000 f6ff1000 r-xp /lib/libdl-2.13.so f6ffa000 f7007000 r-xp /usr/lib/libaul.so.0.1.0 f7018000 f701e000 r-xp /usr/lib/libappcore-efl.so.1.1 f7027000 f702b000 r-xp /usr/lib/libsys-assert.so f7034000 f7051000 r-xp /lib/ld-2.13.so f705a000 f705f000 r-xp /usr/bin/launchpad-loader f751a000 f76bb000 rw-p [heap] ff17c000 ff844000 rw-p [stack] End of Maps Information Callstack Information (PID:5670) Call Stack Count: 1 0: _keep_reading_socket + 0x237 (0xf5c80ed8) [/opt/usr/apps/edu.umich.edu.yctung.devapp/bin/devapp] + 0x1ed8 End of Call Stack Package Information Package Name: edu.umich.edu.yctung.devapp Package ID : edu.umich.edu.yctung.devapp Version: 1.0.0 Package Type: rpm App Name: DevApp App ID: edu.umich.edu.yctung.devapp Type: capp Categories: Latest Debug Message Information --------- beginning of /dev/log_main 3532)]] 04-18 22:52:08.709-0400 W/W_HOME ( 2706): gesture.c: _manual_render_disable_timer_cb(145) > timeout callback expired 04-18 22:52:08.709-0400 W/W_HOME ( 2706): gesture.c: _manual_render_enable(138) > 0 04-18 22:52:08.709-0400 W/W_HOME ( 2706): gesture.c: _manual_render_cancel_schedule(226) > cancel schedule, manual render 04-18 22:52:08.709-0400 W/SHealthCommon( 3106): SHealthMessagePortConnection.cpp: SendServiceMessageImpl(705) > Current shealth version [3.1.30] 04-18 22:52:08.719-0400 W/SHealthWidget( 2848): WidgetMain.cpp: widget_update(147) > ipcClientInfo: 2, com.samsung.shealth.widget.hrlog (223532), msgName: timeline_summary_updated 04-18 22:52:08.719-0400 W/SHealthCommon( 2848): IpcProxy.cpp: OnServiceMessageReceived(186) > msgName: timeline_summary_updated 04-18 22:52:08.719-0400 W/SHealthWidget( 2848): HrLogWidgetViewController.cpp: OnIpcProxyMessageReceived(71) > ##24Hour Widget Service SummaryUpdate Called 04-18 22:52:08.719-0400 W/WSLib ( 2848): ICUStringUtil.cpp: GetStrFromIcu(147) > ts:1492555928733.000000, pattern:[HH:mm] 04-18 22:52:08.719-0400 E/TIZEN_N_SYSTEM_SETTINGS( 2848): system_settings.c: system_settings_get_value_string(522) > Enter [system_settings_get_value_string] 04-18 22:52:08.719-0400 E/TIZEN_N_SYSTEM_SETTINGS( 2848): system_settings.c: system_settings_get_value(386) > Enter [system_settings_get_value] 04-18 22:52:08.719-0400 E/TIZEN_N_SYSTEM_SETTINGS( 2848): system_settings.c: system_settings_get_item(361) > Enter [system_settings_get_item], key=13 04-18 22:52:08.719-0400 E/TIZEN_N_SYSTEM_SETTINGS( 2848): system_settings.c: system_settings_get_item(374) > Enter [system_settings_get_item], index = 13, key = 13, type = 0 04-18 22:52:08.719-0400 E/WSLib ( 2848): ICUStringUtil.cpp: GetStrFromIcu(170) > locale en_US 04-18 22:52:08.719-0400 W/WSLib ( 2848): ICUStringUtil.cpp: GetStrFromIcu(195) > formattedString:[22:52] 04-18 22:52:08.719-0400 E/TIZEN_N_SYSTEM_SETTINGS( 2848): system_settings.c: system_settings_get_value_string(522) > Enter [system_settings_get_value_string] 04-18 22:52:08.719-0400 E/TIZEN_N_SYSTEM_SETTINGS( 2848): system_settings.c: system_settings_get_value(386) > Enter [system_settings_get_value] 04-18 22:52:08.719-0400 E/TIZEN_N_SYSTEM_SETTINGS( 2848): system_settings.c: system_settings_get_item(361) > Enter [system_settings_get_item], key=13 04-18 22:52:08.719-0400 E/TIZEN_N_SYSTEM_SETTINGS( 2848): system_settings.c: system_settings_get_item(374) > Enter [system_settings_get_item], index = 13, key = 13, type = 0 04-18 22:52:08.729-0400 I/CAPI_WIDGET_APPLICATION( 2848): widget_app.c: __provider_update_cb(281) > received updating signal 04-18 22:52:08.759-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __display_lock_state(1882) > Lock LCD OFF is successfully done 04-18 22:52:08.759-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_lcdon_completed_cb(518) > event lcdon completed[1] 04-18 22:52:08.759-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer-self.c: clock_viewer_self_hide(1066) > ===== HIDE ===== 04-18 22:52:08.759-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: clock_viewer_hide(1452) > reservied[0], gesture[0], clock visible[0] 04-18 22:52:08.759-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: _clock_viewer_send_clock_stop(1059) > clock stop << 04-18 22:52:08.759-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: _clock_viewer_send_clock_changed(1069) > clock changed << 04-18 22:52:08.769-0400 W/WATCH_CORE( 2781): appcore-watch.c: __signal_alpm_handler(1151) > signal_alpm_handler: ambient mode: 0, state: 3 04-18 22:52:08.769-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_ambient_tick(339) > _watch_core_ambient_tick, watch: com.samsung.chronograph16 04-18 22:52:08.769-0400 D/chronograph( 2781): ChronographApp.cpp: _appAmbientTick(186) > >>>HIT<<< 04-18 22:52:08.769-0400 D/chronograph( 2781): ChronographViewController.cpp: _getCurrentDate(2107) > BEGIN >>>> 04-18 22:52:08.769-0400 D/chronograph-common( 2781): ChronographIcuDataModel.cpp: getFormattedDateString(77) > regionFormat = en_US 04-18 22:52:08.769-0400 D/chronograph-common( 2781): ChronographIcuDataModel.cpp: getFormattedDateString(77) > regionFormat = en_US 04-18 22:52:08.769-0400 D/chronograph( 2781): ChronographViewController.cpp: _getCurrentDate(2129) > timestamp = 1492570328 :: dateStr = TUE :: dayStr = 18 :: dateText = TUE 18 04-18 22:52:08.769-0400 I/HealthDataService( 2907): RequestHandler.cpp: OnHealthIpcMessageSync2ndParty(147) > Server Received: SHARE_ADD 04-18 22:52:08.769-0400 W/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_ambient_changed(354) > _watch_core_ambient_changed: 0 04-18 22:52:08.769-0400 D/chronograph( 2781): ChronographApp.cpp: _appAmbientChanged(195) > >>>HIT<<< 04-18 22:52:08.769-0400 D/chronograph( 2781): ChronographViewController.cpp: onEventAmbientMode(338) > onEventAmbientMode >>>> [isAmbientMode=0] 04-18 22:52:08.769-0400 I/chronograph( 2781): ChronographViewController.cpp: onEventAmbientMode(358) > Ambient Mode Unset >>>> 04-18 22:52:08.769-0400 W/chronograph( 2781): ChronographViewController.cpp: _hideAodView(907) > hideAodView >>>> 04-18 22:52:08.769-0400 D/chronograph( 2781): ChronographViewController.cpp: _setWatchTouchEvent(1025) > BEGIN >>>> 04-18 22:52:08.769-0400 D/chronograph( 2781): ChronographViewController.cpp: _setCurrentHandPosition(973) > BEGIN >>>> 04-18 22:52:08.769-0400 D/chronograph( 2781): ChronographViewController.cpp: _getCurrentDate(2107) > BEGIN >>>> 04-18 22:52:08.769-0400 D/chronograph-common( 2781): ChronographIcuDataModel.cpp: getFormattedDateString(77) > regionFormat = en_US 04-18 22:52:08.769-0400 D/chronograph-common( 2781): ChronographIcuDataModel.cpp: getFormattedDateString(77) > regionFormat = en_US 04-18 22:52:08.779-0400 D/chronograph( 2781): ChronographViewController.cpp: _getCurrentDate(2129) > timestamp = 1492570328 :: dateStr = TUE :: dayStr = 18 :: dateText = TUE 18 04-18 22:52:08.789-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(325) > [alarm-server]ALARM_CLEAR ioctl is successfully done. 04-18 22:52:08.789-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(332) > Setted RTC Alarm date/time is 19-4-2017, 04:00:00 (UTC). 04-18 22:52:08.789-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(347) > [alarm-server]RTC ALARM_SET ioctl is successfully done. 04-18 22:52:08.789-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __display_unlock_state(1925) > Unlock LCD OFF is successfully done 04-18 22:52:08.789-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: alarm_manager_alarm_delete(2460) > alarm_id[1008179025] is removed. 04-18 22:52:08.799-0400 W/STARTER ( 2598): clock-mgr.c: _on_lcd_signal_receive_cb(1592) > [_on_lcd_signal_receive_cb:1592] _on_lcd_signal_receive_cb, 1592, Post LCD on by [gesture] 04-18 22:52:08.799-0400 W/STARTER ( 2598): clock-mgr.c: _post_lcd_on(1344) > [_post_lcd_on:1344] LCD ON as reserved app[(null)] alpm mode[1] 04-18 22:52:08.799-0400 D/chronograph( 2781): ChronographApp.cpp: _appResume(161) > >>>HIT<<< 04-18 22:52:08.799-0400 D/chronograph( 2781): ChronographViewController.cpp: onResume(221) > State is Resume[isPaused=0], StopwatchState=0 04-18 22:52:08.799-0400 W/chronograph( 2781): ChronographSweepSecond.cpp: setSweepSecond(55) > setSweepSecond >>>> 04-18 22:52:08.799-0400 D/chronograph( 2781): ChronographSweepSecond.cpp: setSweepSecond(67) > Current sec = 8, msec = 809 04-18 22:52:08.799-0400 D/chronograph( 2781): ChronographSweepSecond.cpp: setSweepSecond(71) > Create sweepSecondAnimation !! 04-18 22:52:08.799-0400 D/chronograph-common( 2781): ChronographSensor.cpp: enableAccelerometer(44) > BEGIN >>>> 04-18 22:52:08.799-0400 D/chronograph-common( 2781): ChronographSensor.cpp: _startAccelerometer(75) > BEGIN >>>> 04-18 22:52:08.799-0400 I/healthData( 3106): client_dbus_connection.c: client_dbus_sendto_server_sync_with_2nd_party(370) > Server said: OK {} 04-18 22:52:08.809-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:08.819-0400 I/APP_CORE( 5670): appcore-efl.c: __do_app(453) > [APP 5670] Event: RESUME State: PAUSED 04-18 22:52:08.819-0400 I/CAPI_APPFW_APPLICATION( 5670): app_main.c: _ui_app_appcore_resume(628) > app_appcore_resume 04-18 22:52:08.819-0400 W/STARTER ( 2598): pkg-monitor.c: _proc_mgr_status_cb(449) > [_proc_mgr_status_cb:449] >> P[5670] goes to (3) 04-18 22:52:08.829-0400 W/AUL_AMD ( 2478): amd_key.c: _key_ungrab(254) > fail(-1) to ungrab key(XF86Stop) 04-18 22:52:08.829-0400 W/AUL_AMD ( 2478): amd_launch.c: __e17_status_handler(2391) > back key ungrab error 04-18 22:52:08.829-0400 W/AUL ( 2478): app_signal.c: aul_send_app_status_change_signal(686) > aul_send_app_status_change_signal app(edu.umich.edu.yctung.devapp) pid(5670) status(fg) type(uiapp) 04-18 22:52:08.829-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_visibility_change_cb(703) > Window visibility : [HIDE] lcd[2] begin_flag[0] 04-18 22:52:08.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:09.189-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:09.389-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:09.519-0400 E/EFL ( 5670): ecore_x<5670> ecore_x_events.c:563 _ecore_x_event_handle_button_press() ButtonEvent:press time=4923879 button=1 04-18 22:52:09.589-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:09.659-0400 E/EFL ( 5670): ecore_x<5670> ecore_x_events.c:722 _ecore_x_event_handle_button_release() ButtonEvent:release time=4924010 button=1 04-18 22:52:09.739-0400 D/devapp ( 5670): button is clicked 04-18 22:52:09.789-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:09.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:10.069-0400 D/devapp ( 5670): connect to server successfully 04-18 22:52:10.069-0400 D/devapp ( 5670): temp = 83886080 04-18 22:52:10.069-0400 D/devapp ( 5670): write to socket bytes n = 31 / 31 04-18 22:52:10.079-0400 D/devapp ( 5670): _keep_reading_socket starts 04-18 22:52:10.079-0400 D/devapp ( 5670): wait to read action 04-18 22:52:10.109-0400 D/devapp ( 5670): n = 1, reaction = 1 04-18 22:52:10.109-0400 D/devapp ( 5670): reaction == LIBAS_REACTION_SET_MEDIA 04-18 22:52:10.189-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:10.389-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:10.589-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:10.659-0400 E/EFL ( 2304): ecore_x<2304> ecore_x_netwm.c:1520 ecore_x_netwm_ping_send() Send ECORE_X_ATOM_NET_WM_PING to client win:0x3000002 time=4924010 04-18 22:52:10.659-0400 E/EFL ( 5670): ecore_x<5670> ecore_x_events.c:1958 _ecore_x_event_handle_client_message() Received ECORE_X_ATOM_NET_WM_PING, so send pong to root time=4924010 04-18 22:52:10.659-0400 E/EFL ( 2304): ecore_x<2304> ecore_x_events.c:1964 _ecore_x_event_handle_client_message() Received pong ECORE_X_ATOM_NET_WM_PING from client time=4924010 04-18 22:52:10.789-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:10.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:11.189-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:11.389-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:11.589-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:11.789-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:11.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:12.189-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:12.389-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:12.589-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:12.789-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:12.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:13.189-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:13.389-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:13.589-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:13.789-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:13.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:14.189-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:14.389-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:14.589-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:14.789-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:14.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:15.189-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:15.389-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:15.589-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:15.789-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:15.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:16.189-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:16.389-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:16.589-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:16.789-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:16.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:17.189-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:17.389-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:17.589-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:17.609-0400 E/WMS ( 2431): wms_event_handler.c: _wms_event_handler_cb_nomove_detector(23510) > _wms_event_handler_cb_nomove_detector is called 04-18 22:52:17.789-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:17.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:18.189-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:18.389-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:18.589-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:18.789-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:18.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:19.189-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:19.389-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:19.589-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:19.789-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:19.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:20.189-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:20.389-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:20.589-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:20.789-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:20.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:21.189-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:21.389-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:21.589-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:21.789-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:21.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:22.189-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:22.389-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:22.589-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:22.789-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:22.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:23.189-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:23.389-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:23.589-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:23.789-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:23.989-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick 04-18 22:52:24.069-0400 W/WATCH_CORE( 2781): appcore-watch.c: __signal_lcd_status_handler(1231) > signal_lcd_status_signal: LCDOff 04-18 22:52:24.069-0400 W/W_HOME ( 2706): dbus.c: _dbus_message_recv_cb(204) > LCD off 04-18 22:52:24.069-0400 W/W_HOME ( 2706): gesture.c: _manual_render_cancel_schedule(226) > cancel schedule, manual render 04-18 22:52:24.069-0400 W/W_HOME ( 2706): gesture.c: _manual_render_disable_timer_del(157) > timer del 04-18 22:52:24.069-0400 W/W_HOME ( 2706): gesture.c: _manual_render_enable(138) > 1 04-18 22:52:24.069-0400 W/W_HOME ( 2706): event_manager.c: _lcd_off_cb(736) > lcd state: 0 04-18 22:52:24.069-0400 W/W_HOME ( 2706): event_manager.c: _state_control(176) > control:4, app_state:2 win_state:1(0) pm_state:0 home_visible:1 clock_visible:1 tutorial_state:0 editing : 0, home_clocklist:0, addviewer:0 scrolling : 0, powersaving : 0, apptray state : 1, apptray visibility : 0, apptray edit visibility : 0 04-18 22:52:24.079-0400 W/STARTER ( 2598): clock-mgr.c: _on_lcd_signal_receive_cb(1605) > [_on_lcd_signal_receive_cb:1605] _on_lcd_signal_receive_cb, 1605, Pre LCD off by [timeout] 04-18 22:52:24.079-0400 W/STARTER ( 2598): clock-mgr.c: _pre_lcd_off(1378) > [_pre_lcd_off:1378] Will LCD OFF as wake_up_setting[1] 04-18 22:52:24.079-0400 E/STARTER ( 2598): scontext_util.c: scontext_util_handle_lock_state(64) > [scontext_util_handle_lock_state:64] wear state[0],bPossible [0] 04-18 22:52:24.079-0400 W/STARTER ( 2598): clock-mgr.c: _check_reserved_popup_status(200) > [_check_reserved_popup_status:200] Current reserved apps status : 0 04-18 22:52:24.079-0400 W/STARTER ( 2598): clock-mgr.c: _check_reserved_apps_status(236) > [_check_reserved_apps_status:236] Current reserved apps status : 0 04-18 22:52:24.079-0400 W/WAKEUP-SERVICE( 3184): WakeupService.cpp: OnReceiveDisplayChanged(979) > INFO: LCDOff receive data : -149599476 04-18 22:52:24.079-0400 W/WAKEUP-SERVICE( 3184): WakeupService.cpp: OnReceiveDisplayChanged(980) > INFO: WakeupServiceStop 04-18 22:52:24.079-0400 W/WAKEUP-SERVICE( 3184): WakeupService.cpp: WakeupServiceStop(399) > INFO: SEAMLESS WAKEUP STOP REQUEST 04-18 22:52:24.079-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_lcdoff_cb(554) > event pre lcdoff[1] 04-18 22:52:24.079-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer-util-status.c: clock_viewer_util_status_get_wear_status(413) > enabled[1] status[1] setup[0] darkscreen[0] 04-18 22:52:24.079-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_lcdoff_cb(624) > clock start >> [0] ambient[3] visible[0], self[2] 04-18 22:52:24.079-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_lcdoff_cb(635) > clock begin >> 04-18 22:52:24.079-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer-self.c: clock_viewer_self_update(987) > Flush time[22]:[52]:[24].[95], move[1,-1] 04-18 22:52:24.089-0400 I/TDM ( 1955): tdm_exynos_display.c: exynos_output_set_property(1184) > [4938.440443] id[0] 04-18 22:52:24.089-0400 I/TDM ( 1955): tdm_exynos_display.c: __exynos_output_aod_set_config(984) > [4938.440468] aod_set_config:mode[3] 04-18 22:52:24.089-0400 E/TBM ( 1955): tbm_bufmgr.c: tbm_bo_get_handle(1413) > [tbm_bo_get_handle] : '_tbm_bo_is_valid(bo)' failed. 04-18 22:52:24.089-0400 E/TBM ( 1955): tbm_bufmgr.c: tbm_bo_get_handle(1413) > [tbm_bo_get_handle] : '_tbm_bo_is_valid(bo)' failed. 04-18 22:52:24.089-0400 E/TBM ( 1955): tbm_bufmgr.c: tbm_bo_get_handle(1413) > [tbm_bo_get_handle] : '_tbm_bo_is_valid(bo)' failed. 04-18 22:52:24.089-0400 W/WATCH_CORE( 2781): appcore-watch.c: __signal_alpm_handler(1151) > signal_alpm_handler: ambient mode: 1, state: 2 04-18 22:52:24.089-0400 D/chronograph( 2781): ChronographApp.cpp: _appPause(150) > >>>HIT<<< 04-18 22:52:24.089-0400 W/chronograph( 2781): ChronographViewController.cpp: onPause(183) > State is Pause[isPaused=1], StopwatchState=0 04-18 22:52:24.089-0400 W/chronograph( 2781): ChronographSweepSecond.cpp: resetSweepSecond(103) > resetSweepSecond >>>> 04-18 22:52:24.089-0400 D/chronograph( 2781): ChronographSweepSecond.cpp: resetSweepSecond(107) > Stop and Clear sweepAnimation !! 04-18 22:52:24.089-0400 D/chronograph-common( 2781): ChronographSensor.cpp: disableAcceleormeter(52) > BEGIN >>>> 04-18 22:52:24.089-0400 D/chronograph-common( 2781): ChronographSensor.cpp: _stopAccelerometer(129) > BEGIN >>>> 04-18 22:52:24.089-0400 E/WAKEUP-SERVICE( 3184): WakeupService.cpp: _WakeupIsAvailable(288) > ERROR: db/private/com.samsung.wfmw/is_locked FAILED 04-18 22:52:24.089-0400 E/WAKEUP-SERVICE( 3184): WakeupService.cpp: _WakeupIsAvailable(301) > ERROR: db/private/com.samsung.clock/alarm/alarm_ringing FAILED 04-18 22:52:24.089-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer-self.c: clock_viewer_self_show_fake_hands(1083) > Show fake hands default[0] 04-18 22:52:24.089-0400 E/W_CLOCK_VIEWER( 2727): clock-viewer-self.c: __rotate(1038) > hand geo[160,-1][40x360] 04-18 22:52:24.089-0400 E/W_CLOCK_VIEWER( 2727): clock-viewer-self.c: __rotate(1038) > hand geo[160,-1][40x360] 04-18 22:52:24.099-0400 E/WAKEUP-SERVICE( 3184): WakeupService.cpp: _WakeupIsAvailable(314) > ERROR: file/calendar/alarm_state FAILED 04-18 22:52:24.109-0400 W/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_ambient_changed(354) > _watch_core_ambient_changed: 1 04-18 22:52:24.109-0400 D/chronograph( 2781): ChronographApp.cpp: _appAmbientChanged(195) > >>>HIT<<< 04-18 22:52:24.109-0400 D/chronograph( 2781): ChronographViewController.cpp: onEventAmbientMode(338) > onEventAmbientMode >>>> [isAmbientMode=1] 04-18 22:52:24.109-0400 I/chronograph( 2781): ChronographViewController.cpp: onEventAmbientMode(344) > Ambient Mode Set >>>> 04-18 22:52:24.109-0400 D/chronograph( 2781): ChronographViewController.cpp: _unsetWatchTouchEvent(1043) > BEGIN >>>> 04-18 22:52:24.109-0400 W/chronograph( 2781): ChronographViewController.cpp: _showAodView(878) > showAodView >>>> 04-18 22:52:24.109-0400 D/chronograph( 2781): ChronographViewController.cpp: _getCurrentDate(2107) > BEGIN >>>> 04-18 22:52:24.109-0400 D/chronograph-common( 2781): ChronographIcuDataModel.cpp: getFormattedDateString(77) > regionFormat = en_US 04-18 22:52:24.109-0400 D/chronograph-common( 2781): ChronographIcuDataModel.cpp: getFormattedDateString(77) > regionFormat = en_US 04-18 22:52:24.109-0400 D/chronograph( 2781): ChronographViewController.cpp: _getCurrentDate(2129) > timestamp = 1492570344 :: dateStr = TUE :: dayStr = 18 :: dateText = TUE 18 04-18 22:52:24.109-0400 E/ALARM_MANAGER( 2781): alarm-lib.c: alarmmgr_add_alarm_withcb(1178) > trigger_at_time(47256), start(19-4-2017, 12:00:00), repeat(1), interval(86400), type(-1073741822) 04-18 22:52:24.119-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_pre_cb(317) > RENDER PRE [1] timer[0] 04-18 22:52:24.119-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_post_cb(351) > RENDER POST [1] timer[0] lcd[3] count[0][1] drawdone[0] 04-18 22:52:24.119-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __is_cached_cookie(230) > Find cached cookie for [2781]. 04-18 22:52:24.139-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_pre_cb(317) > RENDER PRE [1] timer[0] 04-18 22:52:24.139-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_post_cb(351) > RENDER POST [1] timer[0] lcd[3] count[0][2] drawdone[0] 04-18 22:52:24.139-0400 I/TIZEN_N_SOUND_MANAGER( 3184): sound_manager_product.c: sound_manager_svoice_wakeup_enable(1255) > [SVOICE] Wake up Disable start 04-18 22:52:24.149-0400 I/TIZEN_N_SOUND_MANAGER( 3184): sound_manager_product.c: sound_manager_svoice_wakeup_enable(1258) > [SVOICE] Wake up Disable end. (ret: 0x0) 04-18 22:52:24.149-0400 W/TIZEN_N_SOUND_MANAGER( 3184): sound_manager_private.c: __convert_sound_manager_error_code(156) > [sound_manager_svoice_wakeup_enable] ERROR_NONE (0x00000000) 04-18 22:52:24.149-0400 W/WAKEUP-SERVICE( 3184): WakeupService.cpp: WakeupSetSeamlessValue(360) > INFO: WAKEUP SET : 0 04-18 22:52:24.149-0400 I/HIGEAR ( 3184): WakeupService.cpp: WakeupServiceStop(403) > [svoice:Application:WakeupServiceStop:IN] 04-18 22:52:24.159-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_pre_cb(317) > RENDER PRE [1] timer[0] 04-18 22:52:24.159-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_post_cb(351) > RENDER POST [1] timer[0] lcd[3] count[0][3] drawdone[0] 04-18 22:52:24.179-0400 E/ALARM_MANAGER( 2429): alarm-manager-schedule.c: _alarm_next_duetime(509) > alarm_id: 1827625670, next duetime: 1492617600 04-18 22:52:24.179-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __alarm_add_to_list(496) > [alarm-server]: After add alarm_id(1827625670) 04-18 22:52:24.179-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __alarm_create(1061) > [alarm-server]:alarm_context.c_due_time(1492574400), due_time(1492617600) 04-18 22:52:24.189-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_pre_cb(317) > RENDER PRE [1] timer[0] 04-18 22:52:24.189-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_post_cb(351) > RENDER POST [1] timer[0] lcd[3] count[0][4] drawdone[0] 04-18 22:52:24.229-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_pre_cb(317) > RENDER PRE [1] timer[0] 04-18 22:52:24.229-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_post_cb(351) > RENDER POST [1] timer[0] lcd[3] count[0][5] drawdone[0] 04-18 22:52:24.259-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_pre_cb(317) > RENDER PRE [1] timer[0] 04-18 22:52:24.259-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_post_cb(351) > RENDER POST [1] timer[0] lcd[3] count[0][6] drawdone[0] 04-18 22:52:24.299-0400 W/SHealthCommon( 3106): SystemUtil.cpp: OnDeviceStatusChanged(1041) > lcdState:3 04-18 22:52:24.299-0400 W/SHealthService( 3106): SHealthServiceController.cpp: OnSystemUtilLcdStateChanged(676) >  ### 04-18 22:52:24.299-0400 W/SHealthCommon( 2848): SystemUtil.cpp: OnDeviceStatusChanged(1041) > lcdState:3 04-18 22:52:24.299-0400 W/W_INDICATOR( 2601): windicator_moment_bar.c: windicator_hide_moment_bar_directly(1504) > [windicator_hide_moment_bar_directly:1504] windicator_hide_moment_bar_directly 04-18 22:52:24.309-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_pre_cb(317) > RENDER PRE [1] timer[0] 04-18 22:52:24.309-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_post_cb(351) > RENDER POST [1] timer[0] lcd[3] count[0][7] drawdone[0] 04-18 22:52:24.329-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_pre_cb(317) > RENDER PRE [1] timer[0] 04-18 22:52:24.329-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_post_cb(351) > RENDER POST [1] timer[0] lcd[3] count[0][8] drawdone[0] 04-18 22:52:24.339-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __display_lock_state(1882) > Lock LCD OFF is successfully done 04-18 22:52:24.339-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(325) > [alarm-server]ALARM_CLEAR ioctl is successfully done. 04-18 22:52:24.339-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(332) > Setted RTC Alarm date/time is 19-4-2017, 04:00:00 (UTC). 04-18 22:52:24.339-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(347) > [alarm-server]RTC ALARM_SET ioctl is successfully done. 04-18 22:52:24.349-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __display_unlock_state(1925) > Unlock LCD OFF is successfully done 04-18 22:52:24.349-0400 I/CAPI_WATCH_APPLICATION( 2781): watch_app_main.c: _watch_core_ambient_tick(339) > _watch_core_ambient_tick, watch: com.samsung.chronograph16 04-18 22:52:24.349-0400 D/chronograph( 2781): ChronographApp.cpp: _appAmbientTick(186) > >>>HIT<<< 04-18 22:52:24.349-0400 D/chronograph( 2781): ChronographViewController.cpp: _getCurrentDate(2107) > BEGIN >>>> 04-18 22:52:24.349-0400 D/chronograph-common( 2781): ChronographIcuDataModel.cpp: getFormattedDateString(77) > regionFormat = en_US 04-18 22:52:24.349-0400 D/chronograph-common( 2781): ChronographIcuDataModel.cpp: getFormattedDateString(77) > regionFormat = en_US 04-18 22:52:24.349-0400 D/chronograph( 2781): ChronographViewController.cpp: _getCurrentDate(2129) > timestamp = 1492570344 :: dateStr = TUE :: dayStr = 18 :: dateText = TUE 18 04-18 22:52:24.359-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_pre_cb(317) > RENDER PRE [1] timer[0] 04-18 22:52:24.359-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_post_cb(351) > RENDER POST [1] timer[0] lcd[3] count[0][9] drawdone[0] 04-18 22:52:24.369-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_clockdraw_cb(415) > Clock draw done 04-18 22:52:24.369-0400 I/WATCH_CORE( 2781): appcore-watch-signal.c: _watch_core_send_alpm_update_done(282) > send a alpm update done signal 04-18 22:52:24.389-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_pre_cb(317) > RENDER PRE [2] timer[0] 04-18 22:52:24.389-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_post_cb(351) > RENDER POST [2] timer[0] lcd[3] count[1][10] drawdone[1] 04-18 22:52:24.439-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_pre_cb(317) > RENDER PRE [2] timer[0] 04-18 22:52:24.439-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_post_cb(351) > RENDER POST [2] timer[0] lcd[3] count[2][11] drawdone[1] 04-18 22:52:24.479-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_pre_cb(317) > RENDER PRE [2] timer[0] 04-18 22:52:24.479-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_post_cb(351) > RENDER POST [2] timer[0] lcd[3] count[3][12] drawdone[1] 04-18 22:52:24.509-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_pre_cb(317) > RENDER PRE [2] timer[0] 04-18 22:52:24.509-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_post_cb(351) > RENDER POST [2] timer[0] lcd[3] count[4][13] drawdone[1] 04-18 22:52:24.539-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_pre_cb(317) > RENDER PRE [2] timer[0] 04-18 22:52:24.539-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_post_cb(351) > RENDER POST [2] timer[0] lcd[3] count[5][14] drawdone[1] 04-18 22:52:24.589-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_render_check_timer_cb(294) > Render check timer expired 04-18 22:52:24.649-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_visibility_change_cb(703) > Window visibility : [VISIBLE] lcd[3] begin_flag[0] 04-18 22:52:24.649-0400 I/APP_CORE( 5670): appcore-efl.c: __do_app(453) > [APP 5670] Event: PAUSE State: RUNNING 04-18 22:52:24.649-0400 I/CAPI_APPFW_APPLICATION( 5670): app_main.c: _ui_app_appcore_pause(611) > app_appcore_pause 04-18 22:52:24.669-0400 W/APP_CORE( 5670): appcore-efl.c: _capture_and_make_file(1721) > Capture : win[3000002] -> redirected win[604e4f] for edu.umich.edu.yctung.devapp[5670] 04-18 22:52:24.789-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer-self.c: clock_viewer_self_show(1054) > ===== SHOW ===== 04-18 22:52:24.789-0400 E/ALARM_MANAGER( 2727): alarm-lib.c: alarmmgr_add_alarm_withcb(1178) > trigger_at_time(576), start(18-4-2017, 23:02:01), repeat(1), interval(600), type(-1073741822) 04-18 22:52:24.789-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __is_cached_cookie(230) > Find cached cookie for [2727]. 04-18 22:52:24.809-0400 E/ALARM_MANAGER( 2429): alarm-manager-schedule.c: _alarm_next_duetime(509) > alarm_id: 1827625671, next duetime: 1492570921 04-18 22:52:24.809-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __alarm_add_to_list(496) > [alarm-server]: After add alarm_id(1827625671) 04-18 22:52:24.809-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __alarm_create(1061) > [alarm-server]:alarm_context.c_due_time(1492574400), due_time(1492570921) 04-18 22:52:24.809-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __display_lock_state(1882) > Lock LCD OFF is successfully done 04-18 22:52:24.809-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(325) > [alarm-server]ALARM_CLEAR ioctl is successfully done. 04-18 22:52:24.809-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(332) > Setted RTC Alarm date/time is 19-4-2017, 03:02:01 (UTC). 04-18 22:52:24.809-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(347) > [alarm-server]RTC ALARM_SET ioctl is successfully done. 04-18 22:52:24.819-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __display_unlock_state(1925) > Unlock LCD OFF is successfully done 04-18 22:52:24.819-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_clockend_timer_cb(257) > clock end << [1] 04-18 22:52:24.829-0400 W/STARTER ( 2598): clock-mgr.c: _on_lcd_signal_receive_cb(1618) > [_on_lcd_signal_receive_cb:1618] _on_lcd_signal_receive_cb, 1618, Post LCD off by [timeout] 04-18 22:52:24.829-0400 W/STARTER ( 2598): clock-mgr.c: _post_lcd_off(1510) > [_post_lcd_off:1510] LCD OFF as reserved app[(null)] alpm mode[1] 04-18 22:52:24.839-0400 W/STARTER ( 2598): clock-mgr.c: _post_lcd_off(1517) > [_post_lcd_off:1517] Current reserved apps status : 0 04-18 22:52:24.839-0400 W/STARTER ( 2598): clock-mgr.c: _post_lcd_off(1535) > [_post_lcd_off:1535] raise homescreen after 20 sec. home_visible[0] 04-18 22:52:24.839-0400 E/ALARM_MANAGER( 2598): alarm-lib.c: alarmmgr_add_alarm_withcb(1178) > trigger_at_time(20), start(18-4-2017, 22:52:45), repeat(1), interval(20), type(-1073741822) 04-18 22:52:24.839-0400 E/W_CLOCK_VIEWER( 2727): clock-viewer-smart-lcdoff.c: clock_viewer_smart_lcdoff_start(181) > smart lcd off is not enabled 04-18 22:52:24.839-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __is_cached_cookie(230) > Find cached cookie for [2598]. 04-18 22:52:24.839-0400 W/W_INDICATOR( 2601): windicator_dbus.c: _windicator_dbus_lcd_off_completed_cb(355) > [_windicator_dbus_lcd_off_completed_cb:355] LCD Off completed signal is received 04-18 22:52:24.839-0400 W/W_INDICATOR( 2601): windicator_dbus.c: _windicator_dbus_lcd_off_completed_cb(360) > [_windicator_dbus_lcd_off_completed_cb:360] Moment bar status -> idle. (Hide Moment bar) 04-18 22:52:24.839-0400 W/W_INDICATOR( 2601): windicator_moment_bar.c: windicator_hide_moment_bar_directly(1504) > [windicator_hide_moment_bar_directly:1504] windicator_hide_moment_bar_directly 04-18 22:52:24.849-0400 I/TDM ( 1955): tdm_display.c: tdm_layer_unset_buffer(1602) > [4939.209342] layer(0x6bb260) now usable 04-18 22:52:24.849-0400 I/TDM ( 1955): tdm_exynos_display.c: exynos_layer_unset_buffer(1678) > [4939.209363] layer[0x6bae80]zpos[2] 04-18 22:52:24.849-0400 I/TDM ( 1955): tdm_exynos_display.c: exynos_output_set_property(1184) > [4939.209545] id[0] 04-18 22:52:24.849-0400 I/TDM ( 1955): tdm_exynos_display.c: __exynos_output_aod_change_state(1142) > [4939.209559] aod_change_state:mode[3] 04-18 22:52:24.849-0400 I/TDM ( 1955): tdm_exynos_display.c: __exynos_output_aod_change_state(1149) > [4939.209569] aod_change_state:state[181 -> 1] 04-18 22:52:24.859-0400 E/ALARM_MANAGER( 2429): alarm-manager-schedule.c: _alarm_next_duetime(509) > alarm_id: 1827625672, next duetime: 1492570365 04-18 22:52:24.859-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __alarm_add_to_list(496) > [alarm-server]: After add alarm_id(1827625672) 04-18 22:52:24.859-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __alarm_create(1061) > [alarm-server]:alarm_context.c_due_time(1492570921), due_time(1492570365) 04-18 22:52:24.859-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_lcdoff_completed_cb(668) > event lcdoff completed[1][0] 04-18 22:52:24.859-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __display_lock_state(1882) > Lock LCD OFF is successfully done 04-18 22:52:24.859-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(325) > [alarm-server]ALARM_CLEAR ioctl is successfully done. 04-18 22:52:24.859-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(332) > Setted RTC Alarm date/time is 19-4-2017, 02:52:45 (UTC). 04-18 22:52:24.859-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(347) > [alarm-server]RTC ALARM_SET ioctl is successfully done. 04-18 22:52:24.859-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer-util-status.c: clock_viewer_util_status_get_wear_status(413) > enabled[1] status[1] setup[0] darkscreen[0] 04-18 22:52:24.869-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __display_unlock_state(1925) > Unlock LCD OFF is successfully done 04-18 22:52:25.349-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer.c: __clock_viewer_black_cover_timer_cb(231) > Remove black screen or fake hands 04-18 22:52:25.359-0400 W/W_CLOCK_VIEWER( 2727): clock-viewer-self.c: clock_viewer_self_hide_fake_hands(1152) > Hide fake hands 04-18 22:52:25.379-0400 I/TDM ( 1955): tdm_exynos_display.c: exynos_output_commit(1324) > [4939.731712] set aod state[2] 04-18 22:52:25.379-0400 I/TDM ( 1955): 04-18 22:52:25.379-0400 I/TDM ( 1955): tdm_exynos_display.c: exynos_output_commit(1369) > [4939.735600] set aod state[3] 04-18 22:52:25.379-0400 I/TDM ( 1955): 04-18 22:52:29.659-0400 I/APP_CORE( 5670): appcore-efl.c: __do_app(453) > [APP 5670] Event: MEM_FLUSH State: PAUSED 04-18 22:52:44.999-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __alarm_handler_idle(1484) > Lock the display not to enter LCD OFF 04-18 22:52:44.999-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __display_lock_state(1882) > Lock LCD OFF is successfully done 04-18 22:52:45.019-0400 W/AUL ( 2429): app_signal.c: aul_update_freezer_status(456) > aul_update_freezer_status pid(2598) type(wakeup) 04-18 22:52:45.019-0400 E/RESOURCED( 2593): freezer-process.c: freezer_process_pid_set(150) > Cant find process info for 2598 04-18 22:52:45.029-0400 E/ALARM_MANAGER( 2598): alarm-lib.c: __handle_expiry_method_call(152) > [alarm-lib] : Alarm expired for [ALARM.astarter] : Alarm id [1827625672] 04-18 22:52:45.029-0400 W/STARTER ( 2598): clock-mgr.c: __starter_clock_mgr_homescreen_alarm_cb(979) > [__starter_clock_mgr_homescreen_alarm_cb:979] homescreen alarm timer expired [1827625672] 04-18 22:52:45.039-0400 W/AUL ( 2598): launch.c: app_request_to_launchpad(284) > request cmd(0) to(com.samsung.w-home) 04-18 22:52:45.039-0400 W/AUL_AMD ( 2478): amd_request.c: __request_handler(669) > __request_handler: 0 04-18 22:52:45.039-0400 W/AUL_AMD ( 2478): amd_launch.c: _start_app(1782) > caller pid : 2598 04-18 22:52:45.049-0400 W/AUL ( 2478): app_signal.c: aul_send_app_resume_request_signal(567) > aul_send_app_resume_request_signal app(com.samsung.w-home) pid(2706) type(uiapp) bg(0) 04-18 22:52:45.049-0400 W/AUL_AMD ( 2478): amd_launch.c: __nofork_processing(1229) > __nofork_processing, cmd: 0, pid: 2706 04-18 22:52:45.049-0400 I/APP_CORE( 2706): appcore-efl.c: __do_app(453) > [APP 2706] Event: RESET State: PAUSED 04-18 22:52:45.049-0400 I/CAPI_APPFW_APPLICATION( 2706): app_main.c: app_appcore_reset(245) > app_appcore_reset 04-18 22:52:45.049-0400 W/CAPI_APPFW_APP_CONTROL( 2706): app_control.c: app_control_error(136) > [app_control_get_extra_data] KEY_NOT_FOUND(0xffffff82) 04-18 22:52:45.049-0400 W/W_HOME ( 2706): main.c: _app_control_progress(1571) > Service value : show_clock 04-18 22:52:45.049-0400 W/W_HOME ( 2706): main.c: _app_control_progress(1588) > Show clock operation 04-18 22:52:45.049-0400 W/W_HOME ( 2706): gesture.c: _clock_show(242) > clock show 04-18 22:52:45.049-0400 W/W_HOME ( 2706): gesture.c: _clock_show(257) > home raise 04-18 22:52:45.049-0400 E/W_HOME ( 2706): gesture.c: gesture_win_aux_set(395) > wm.policy.win.do.not.use.deiconify.approve:-1 04-18 22:52:45.049-0400 W/W_HOME ( 2706): dbus_util.c: home_dbus_home_raise_signal_send(298) > Sending HOME RAISE signal, result:0 04-18 22:52:45.049-0400 W/W_HOME ( 2706): gesture.c: _clock_show(260) > home raise done 04-18 22:52:45.049-0400 W/W_HOME ( 2706): gesture.c: _clock_show(267) > show clock 04-18 22:52:45.049-0400 W/W_HOME ( 2706): index.c: index_hide(337) > hide VI:0 visibility:0 vi:(nil) 04-18 22:52:45.049-0400 W/W_HOME ( 2706): gesture.c: _manual_render(182) > 04-18 22:52:45.059-0400 W/AUL_AMD ( 2478): amd_launch.c: __reply_handler(999) > listen fd(23) , send fd(22), pid(2706), cmd(0) 04-18 22:52:45.059-0400 W/AUL ( 2598): launch.c: app_request_to_launchpad(298) > request cmd(0) result(2706) 04-18 22:52:45.069-0400 W/W_INDICATOR( 2601): windicator_moment_bar.c: windicator_hide_moment_bar_directly(1504) > [windicator_hide_moment_bar_directly:1504] windicator_hide_moment_bar_directly 04-18 22:52:45.069-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __alarm_expired(1445) > alarm_id[1827625672] is expired. 04-18 22:52:45.069-0400 E/ALARM_MANAGER( 2429): alarm-manager-schedule.c: _alarm_next_duetime(509) > alarm_id: 1827625672, next duetime: 1492570385 04-18 22:52:45.069-0400 W/WATCH_CORE( 2781): appcore-watch.c: __signal_process_manager_handler(1269) > process_manager_signal 04-18 22:52:45.069-0400 I/WATCH_CORE( 2781): appcore-watch.c: __signal_process_manager_handler(1279) > Skip the process_manager signal in ambient mode 04-18 22:52:45.069-0400 E/ALARM_MANAGER( 2429): alarm-manager-schedule.c: __find_next_alarm_to_be_scheduled(547) > The duetime of alarm(1850700647) is OVER. 04-18 22:52:45.079-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(325) > [alarm-server]ALARM_CLEAR ioctl is successfully done. 04-18 22:52:45.079-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(332) > Setted RTC Alarm date/time is 19-4-2017, 02:53:05 (UTC). 04-18 22:52:45.079-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(347) > [alarm-server]RTC ALARM_SET ioctl is successfully done. 04-18 22:52:45.079-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __alarm_handler_idle(1510) > Unlock the display from LCD OFF 04-18 22:52:45.089-0400 I/APP_CORE( 2706): appcore-efl.c: __do_app(529) > Legacy lifecycle: 1 04-18 22:52:45.099-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __display_unlock_state(1925) > Unlock LCD OFF is successfully done 04-18 22:52:45.099-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __is_cached_cookie(230) > Find cached cookie for [2598]. 04-18 22:52:45.099-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __alarm_remove_from_list(575) > [alarm-server]:Remove alarm id(1827625672) 04-18 22:52:45.099-0400 E/ALARM_MANAGER( 2429): alarm-manager-schedule.c: __find_next_alarm_to_be_scheduled(547) > The duetime of alarm(1850700647) is OVER. 04-18 22:52:45.099-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __display_lock_state(1882) > Lock LCD OFF is successfully done 04-18 22:52:45.099-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(325) > [alarm-server]ALARM_CLEAR ioctl is successfully done. 04-18 22:52:45.099-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(332) > Setted RTC Alarm date/time is 19-4-2017, 03:02:01 (UTC). 04-18 22:52:45.099-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __rtc_set(347) > [alarm-server]RTC ALARM_SET ioctl is successfully done. 04-18 22:52:45.109-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: __display_unlock_state(1925) > Unlock LCD OFF is successfully done 04-18 22:52:45.109-0400 E/ALARM_MANAGER( 2429): alarm-manager.c: alarm_manager_alarm_delete(2460) > alarm_id[1827625672] is removed. 04-18 22:52:45.109-0400 W/STARTER ( 2598): pkg-monitor.c: _app_mgr_status_cb(415) > [_app_mgr_status_cb:415] Resume request [2706] 04-18 22:52:46.059-0400 W/AUL_AMD ( 2478): amd_key.c: _key_ungrab(254) > fail(-1) to ungrab key(XF86Stop) 04-18 22:52:46.059-0400 W/AUL_AMD ( 2478): amd_launch.c: __grab_timeout_handler(1453) > back key ungrab error 04-18 22:53:05.369-0400 E/devapp ( 5670): wrong # of byte read, n = 1 04-18 22:53:05.369-0400 E/devapp ( 5670): wrong # of byte read, n = 3 04-18 22:53:13.249-0400 E/devapp ( 5670): wrong # of byte read, n = 1 04-18 22:53:13.249-0400 D/devapp ( 5670): FS = 4689654, chCnt = 12288246, repeatCnt = 12288246 04-18 22:53:13.559-0400 W/AUL_PAD ( 3282): sigchild.h: __launchpad_process_sigchld(188) > dead_pid = 5670 pgid = 5670 04-18 22:53:13.559-0400 W/AUL_PAD ( 3282): sigchild.h: __launchpad_process_sigchld(189) > ssi_code = 2 ssi_status = 11 04-18 22:53:13.579-0400 W/AUL_PAD ( 3282): sigchild.h: __launchpad_process_sigchld(197) > after __sigchild_action 04-18 22:53:13.589-0400 I/AUL_AMD ( 2478): amd_main.c: __app_dead_handler(262) > __app_dead_handler, pid: 5670 04-18 22:53:13.589-0400 W/AUL ( 2478): app_signal.c: aul_send_app_terminated_signal(799) > aul_send_app_terminated_signal pid(5670) 04-18 22:53:13.619-0400 W/CRASH_MANAGER( 5824): worker.c: worker_job(1199) > 1105670646576149257039
using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Windows.Forms; using NetGore; using NetGore.Content; using NetGore.Editor; using WeifenLuo.WinFormsUI.Docking; using NetGore.Graphics; using NetGore.IO; using SFML.Graphics; namespace DemoGame.Editor { public partial class SkeletonEditorForm : DockContent { const string _filterBody = "Skeleton body (*" + SkeletonBodyInfo.FileSuffix + ")|*" + SkeletonBodyInfo.FileSuffix; const string _filterFrame = "Skeleton frame (*" + Skeleton.FileSuffix + ")|*" + Skeleton.FileSuffix; const string _filterSet = "Skeleton set (*" + SkeletonSet.FileSuffix + ")|*" + SkeletonSet.FileSuffix; const string _skeletonSetFromStringDelimiter = "\r\n"; readonly Stopwatch _watch = new Stopwatch(); ICamera2D _camera; IContentManager _content; TickCount _currentTime; /// <summary> /// World position of the cursor for the game screen /// </summary> Vector2 _cursorPos = new Vector2(); DrawingManager _drawingManager; string _fileAnim = string.Empty; string _fileBody = string.Empty; string _fileFrame = string.Empty; Font _font; SkeletonBody _frameBody = null; bool _moveSelectedNode = false; Skeleton _skeleton; SkeletonAnimation _skeletonAnim; KeyEventArgs ks = new KeyEventArgs(Keys.None); /// <summary> /// Initializes a new instance of the <see cref="SkeletonEditorForm"/> class. /// </summary> public SkeletonEditorForm() { InitializeComponent(); HookInput(); GameScreen.SkeletonEditorForm = this; btnSelectBodyGrhData.GrhDataSelected -= btnSelectBodyGrhData_GrhDataSelected; btnSelectBodyGrhData.GrhDataSelected += btnSelectBodyGrhData_GrhDataSelected; btnSelectBodyGrhData.SelectedGrhDataHandler = btnSelectBodyGrhData_SelectedGrhDataHandler; } public DrawingManager DrawingManager { get { return _drawingManager; } } /// <summary> /// Gets or sets the file for the current skeleton animation /// </summary> string FileAnim { get { return _fileAnim; } set { _fileAnim = value; lblAnimation.Text = "Loaded: " + Path.GetFileName(_fileAnim); } } /// <summary> /// Gets or sets the file for the current skeleton body /// </summary> string FileBody { get { return _fileBody; } set { _fileBody = value; gbBodies.Text = "Bone Bodies: " + Path.GetFileName(_fileBody); } } /// <summary> /// Gets or sets the file for the current skeleton frame /// </summary> string FileFrame { get { return _fileFrame; } set { _fileFrame = value; lblSkeleton.Text = "Loaded: " + Path.GetFileName(_fileFrame); } } /// <summary> /// Gets the selected drawable skeleton item in the list /// </summary> public SkeletonBodyItem SelectedDSI { get { try { return lstBodies.SelectedItem as SkeletonBodyItem; } catch { return null; } } } /// <summary> /// Gets or sets the currently selected node /// </summary> public SkeletonNode SelectedNode { get { return cmbSkeletonNodes.SelectedItem as SkeletonNode; } set { cmbSkeletonNodes.SelectedItem = value; } } /// <summary> /// Gets the SkeletonAnimation's SkeletonBody /// </summary> public SkeletonBody SkeletonBody { get { return _skeletonAnim.SkeletonBody; } } /// <summary> /// Draws the screen. /// </summary> internal void DrawGame() { // Screen var sb = _drawingManager.BeginDrawWorld(_camera); try { // Draw the center lines RenderLine.Draw(sb, new Vector2(-100, 0), new Vector2(100, 0), Color.Lime); RenderLine.Draw(sb, new Vector2(0, -5), new Vector2(0, 5), Color.Red); if (radioEdit.Checked) { // Edit skeleton SkeletonDrawer.Draw(_skeleton, _camera, sb, SelectedNode); if (_frameBody != null && chkDrawBody.Checked) _frameBody.Draw(sb, Vector2.Zero); } else { // Animate skeletons if (chkDrawBody.Checked) _skeletonAnim.Draw(sb); if (chkDrawSkel.Checked) SkeletonDrawer.Draw(_skeletonAnim.Skeleton, _camera, sb); } } finally { _drawingManager.EndDrawWorld(); } // On-screen GUI sb = _drawingManager.BeginDrawGUI(); try { var fontColor = Color.White; var borderColor = Color.Black; // Cursor position text sb.DrawStringShaded(_font, _cursorPos.Round().ToString(), new Vector2(2), fontColor, borderColor); // Name of the node under the cursor var nodeUnderCursor = _skeleton.RootNode.GetAllNodes().FirstOrDefault(x => x.HitTest(_camera, _cursorPos)); if (nodeUnderCursor != null) { sb.DrawStringShaded(_font, "Node: " + nodeUnderCursor.Name, _camera.ToScreen(_cursorPos) + new Vector2(12, -12), fontColor, borderColor); } } finally { _drawingManager.EndDrawGUI(); } } /// <summary> /// Handles the MouseDown event of the GameScreen control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param> void GameScreen_MouseDown(object sender, MouseEventArgs e) { if (radioEdit.Checked) { if (e.Button == MouseButtons.Left) { // Select new node var nodes = _skeleton.RootNode.GetAllNodes(); foreach (var node in nodes) { if (node.HitTest(_camera, _cursorPos)) { SelectedNode = node; // Select the node _moveSelectedNode = true; // Enable dragging break; } } } else if (e.Button == MouseButtons.Right) { // Add new node if (!chkCanAlter.Checked) { MessageBox.Show("Node adding and removing locked. Enable node add/remove in the settings panel.", "Invalid operation", MessageBoxButtons.OK); return; } if (_skeleton.RootNode == null) { // Create the root node _skeleton.RootNode = new SkeletonNode(_cursorPos); SelectedNode = _skeleton.RootNode; SelectedNode.Name = "New Root"; } else { // Create a child node if (SelectedNode == null) { const string errmsg = "You must first select a node before creating a new node. The selected node will be used as the new node's parent."; MessageBox.Show(errmsg, "Select a node", MessageBoxButtons.OK); } else { var newNode = new SkeletonNode(SelectedNode, _cursorPos); UpdateFrameNodeCBs(); SelectedNode = newNode; } } } } } /// <summary> /// Handles the MouseMove event of the GameScreen control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param> void GameScreen_MouseMove(object sender, MouseEventArgs e) { _cursorPos = _camera.ToWorld(e.X, e.Y); if (_skeleton.RootNode == null || e.Button != MouseButtons.Left || !_moveSelectedNode) return; if (chkCanTransform.Checked) { if (ks.Control) { // Unlocked movement, move the node and its children SelectedNode.MoveTo(_cursorPos); UpdateNodeInfo(); } else { // Unlocked movement, move just the one node SelectedNode.Position = _cursorPos; UpdateNodeInfo(); } } else { if (ks.Control) { // Locked movement, the node and all of its children SelectedNode.Rotate(_cursorPos); UpdateNodeInfo(); } else { // Locked movement, move the node and its children if (SelectedNode.Parent != null) SelectedNode.SetAngle(_cursorPos); else SelectedNode.MoveTo(_cursorPos); UpdateNodeInfo(); } } } /// <summary> /// Handles the MouseUp event of the GameScreen control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param> void GameScreen_MouseUp(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Left) _moveSelectedNode = false; } /// <summary> /// Handles the MouseWheel event of the GameScreen control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.Windows.Forms.MouseEventArgs"/> instance containing the event data.</param> void GameScreen_MouseWheel(object sender, MouseEventArgs e) { var center = _camera.Center; _camera.Scale += e.Delta / 1000f; _camera.CenterOn(center); } /// <summary> /// Handles the Resize event of the GameScreen control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void GameScreen_Resize(object sender, EventArgs e) { if (_camera == null || GameScreen == null) return; var oldCenter = _camera.Center; _camera.Size = new Vector2(GameScreen.ClientSize.Width, GameScreen.ClientSize.Height); _camera.CenterOn(oldCenter); } static string GetLoadSkeletonDialogResult(string filter) { string result; using (var fd = new OpenFileDialog()) { fd.Filter = filter; fd.InitialDirectory = ContentPaths.Dev.Skeletons; fd.RestoreDirectory = true; fd.ShowDialog(); result = fd.FileName; } return result; } static string[] GetLoadSkeletonDialogResults(string filter) { string[] result; using (var fd = new OpenFileDialog()) { fd.Filter = filter; fd.InitialDirectory = ContentPaths.Dev.Skeletons; fd.RestoreDirectory = true; fd.ShowDialog(); result = fd.FileNames; } return result; } static string GetSaveSkeletonDialogResult(string filter) { string result; using (var fd = new SaveFileDialog()) { fd.Filter = filter; fd.InitialDirectory = ContentPaths.Dev.Skeletons; fd.RestoreDirectory = true; fd.ShowDialog(); result = fd.FileName; } return result; } /// <summary> /// Gets the current game time where time 0 is when the application started /// </summary> /// <returns>Current game time in milliseconds</returns> public TickCount GetTime() { return _currentTime; } void HookInput() { RecursiveHookInput(this); } void KeyDownForward(object sender, KeyEventArgs e) { OnKeyDown(e); } void KeyUpForward(object sender, KeyEventArgs e) { OnKeyUp(e); } public void LoadAnim(string filePath) { var newSet = SkeletonLoader.LoadSkeletonSet(filePath); _skeletonAnim.ChangeSet(newSet); FileAnim = filePath; txtFrames.Text = _skeletonAnim.SkeletonSet.GetFramesString(); UpdateAnimationNodeCBs(); } public void LoadBody(string filePath) { var bodyInfo = SkeletonLoader.LoadSkeletonBodyInfo(filePath); _skeletonAnim.SkeletonBody = new SkeletonBody(bodyInfo, _skeletonAnim.Skeleton); _frameBody = new SkeletonBody(bodyInfo, _skeleton); UpdateBodyList(); FileBody = filePath; } public void LoadSkelSets(string filePath) { // Load the skeleton sets into the specified combobox cmbSkeletonBodies.Items.Clear(); DirectoryInfo skelBodiesFolder = new DirectoryInfo(filePath); DirectoryInfo[] skelBodies = skelBodiesFolder.GetDirectories(); foreach (DirectoryInfo skelBody in skelBodies) cmbSkeletonBodies.Items.Add(skelBody.Name); } public void LoadFrame(string filePath) { var newSkeleton = SkeletonLoader.LoadSkeleton(filePath); LoadFrame(newSkeleton); FileFrame = filePath; } void LoadFrame(Skeleton skel) { _skeleton = skel; if (_frameBody != null) _frameBody.Attach(_skeleton); SelectedNode = _skeleton.RootNode; UpdateFrameNodeCBs(); } /// <summary> /// Raises the <see cref="E:System.Windows.Forms.Control.KeyDown"/> event. /// </summary> /// <param name="e">A <see cref="T:System.Windows.Forms.KeyEventArgs"/> that contains the event data.</param> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (DesignMode) return; ks = e; const float TranslateRate = 7f; const float ScaleRate = 0.08f; var oldCenter = _camera.Center; switch (e.KeyCode) { case Keys.NumPad5: ResetCamera(); break; case Keys.NumPad8: _camera.Translate(new Vector2(0, -TranslateRate / _camera.Scale)); break; case Keys.NumPad4: _camera.Translate(new Vector2(-TranslateRate / _camera.Scale, 0)); break; case Keys.NumPad6: _camera.Translate(new Vector2(TranslateRate / _camera.Scale, 0)); break; case Keys.NumPad2: _camera.Translate(new Vector2(0, TranslateRate / _camera.Scale)); break; case Keys.NumPad9: _camera.Zoom(_camera.Min + ((_camera.Size / 2) / _camera.Scale), _camera.Size, _camera.Scale + ScaleRate); break; case Keys.NumPad7: _camera.Zoom(_camera.Min + ((_camera.Size / 2) / _camera.Scale), _camera.Size, _camera.Scale - ScaleRate); break; case Keys.Delete: if (!chkCanAlter.Checked) { MessageBox.Show("Node adding and removing locked. Enable node add/remove in the settings panel.", "Invalid operation", MessageBoxButtons.OK); return; } var removeNode = SelectedNode; if (removeNode == null) return; SelectedNode = removeNode.Parent; removeNode.Remove(); break; } _camera.CenterOn(oldCenter); } /// <summary> /// Raises the <see cref="E:System.Windows.Forms.Control.KeyUp"/> event. /// </summary> /// <param name="e">A <see cref="T:System.Windows.Forms.KeyEventArgs"/> that contains the event data.</param> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); if (DesignMode) return; ks = e; } /// <summary> /// Raises the <see cref="E:System.Windows.Forms.Form.Load"/> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); if (DesignMode) return; // Create the engine objects _drawingManager = new DrawingManager(GameScreen.RenderWindow); _camera = new Camera2D(new Vector2(GameScreen.Width, GameScreen.Height)) { KeepInMap = false }; _content = ContentManager.Create(); _font = _content.LoadFont("Font/Arial", 14, ContentLevel.GameScreen); GrhInfo.Load(ContentPaths.Dev, _content); // Create the skeleton-related objects _skeleton = new Skeleton(); var frameSkeleton = new Skeleton(SkeletonLoader.StandingSkeletonName, ContentPaths.Dev); var frame = new SkeletonFrame(SkeletonLoader.StandingSkeletonName, frameSkeleton); _skeletonAnim = new SkeletonAnimation(GetTime(), frame); LoadFrame(Skeleton.GetFilePath(SkeletonLoader.StandingSkeletonName, ContentPaths.Dev)); LoadAnim(SkeletonSet.GetFilePath(SkeletonLoader.WalkingSkeletonSetName, ContentPaths.Dev)); LoadBody(SkeletonBodyInfo.GetFilePath(SkeletonLoader.BasicSkeletonBodyName, ContentPaths.Dev)); LoadSkelSets(ContentPaths.Build.Grhs + "\\Character\\Skeletons"); _watch.Start(); ResetCamera(); GameScreen.MouseWheel += GameScreen_MouseWheel; } private void ResetCamera() { _camera.Zoom(new Vector2(0, -25), _camera.Size, 3f); } void RecursiveHookInput(Control rootC) { foreach (Control c in rootC.Controls) { if (c.GetType() != typeof(TextBoxBase) && c.GetType() != typeof(ListControl)) { c.KeyDown += KeyDownForward; c.KeyUp += KeyUpForward; } RecursiveHookInput(c); } } void SetAnimByTxt() { try { var newSet = SkeletonLoader.LoadSkeletonSetFromString(txtFrames.Text, _skeletonSetFromStringDelimiter); if (newSet == null) { txtFrames.BackColor = EditorColors.Error; return; } _skeletonAnim.ChangeSet(newSet); txtFrames.BackColor = EditorColors.Normal; } catch { txtFrames.BackColor = EditorColors.Error; } } void UpdateAnimationNodeCBs() { var nodes = _skeletonAnim.Skeleton.RootNode.GetAllNodes(); var sourceSelected = cmbSource.SelectedItem; var targetSelected = cmbTarget.SelectedItem; cmbSource.Items.Clear(); cmbSource.Items.AddRange(nodes.OfType<object>().ToArray()); cmbTarget.Items.Clear(); cmbTarget.Items.AddRange(nodes.OfType<object>().ToArray()); if (sourceSelected != null && cmbSource.Items.Contains(sourceSelected)) cmbSource.SelectedItem = sourceSelected; if (targetSelected != null && cmbTarget.Items.Contains(targetSelected)) cmbTarget.SelectedItem = targetSelected; } void UpdateBodyList() { var selected = lstBodies.SelectedItem; lstBodies.Items.Clear(); lstBodies.Items.AddRange(SkeletonBody.BodyItems.OfType<object>().ToArray()); if (selected != null && lstBodies.Items.Contains(selected)) lstBodies.SelectedItem = selected; else lstBodies.SelectedIndex = lstBodies.Items.Count > 0 ? 0 : -1; UpdateAnimationNodeCBs(); } void UpdateFrameNodeCBs() { var selected = cmbSkeletonNodes.SelectedItem; cmbSkeletonNodes.Items.Clear(); var nodes = _skeleton.RootNode.GetAllNodes(); cmbSkeletonNodes.Items.AddRange(nodes.OfType<object>().ToArray()); if (selected != null && cmbSkeletonNodes.Items.Contains(selected)) cmbSkeletonNodes.SelectedItem = selected; } /// <summary> /// Updates the game. /// </summary> public void UpdateGame() { if (!_watch.IsRunning) return; _currentTime = (TickCount)_watch.ElapsedMilliseconds; _skeletonAnim.Update(_currentTime); } /// <summary> /// Updates the node info. /// </summary> public void UpdateNodeInfo() { if (SelectedNode == null) return; txtName.Text = SelectedNode.Name; txtX.Text = SelectedNode.X.ToString(); txtY.Text = SelectedNode.Y.ToString(); txtAngle.Text = SelectedNode.GetAngle().ToString(); txtLength.Text = SelectedNode.GetLength().ToString("#.###"); chkIsMod.Checked = SelectedNode.IsModifier; } void UpdateSelectedDSI() { lstBodies.RefreshItemAt(lstBodies.SelectedIndex); } /// <summary> /// Handles the Click event of the btnAdd control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnAdd_Click(object sender, EventArgs e) { try { if (cmbSkeletonBodies.SelectedItem == null || cmbSkeletonBodyNodes.SelectedItem == null) return; var skelBodies = cmbSkeletonBodies.SelectedItem.ToString(); var skelBodyNodes = cmbSkeletonBodyNodes.SelectedItem.ToString(); Array.Resize(ref SkeletonBody.BodyItems, SkeletonBody.BodyItems.Length + 1); var spriteCategorization = new SpriteCategorization("Character.Skeletons." + skelBodies, skelBodyNodes); var grhData = GrhInfo.GetData(spriteCategorization); if (grhData == null) return; var bodyItemInfo = new SkeletonBodyItemInfo(grhData.GrhIndex, _skeleton.RootNode.Name, string.Empty, Vector2.Zero, Vector2.Zero); var bodyItem = new SkeletonBodyItem(bodyItemInfo); SkeletonBody.BodyItems[SkeletonBody.BodyItems.Length - 1] = bodyItem; UpdateBodyList(); } catch { } } /// <summary> /// Handles the Click event of the btnAnimLoad control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnAnimLoad_Click(object sender, EventArgs e) { var result = GetLoadSkeletonDialogResult(_filterSet); if (result != null && result.Length > 1) LoadAnim(result); } /// <summary> /// Handles the Click event of the btnAnimSaveAs control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnAnimSaveAs_Click(object sender, EventArgs e) { var result = GetSaveSkeletonDialogResult(_filterSet); if (result != null && result.Length > 1) { var skelSet = SkeletonLoader.LoadSkeletonSetFromString(txtFrames.Text, _skeletonSetFromStringDelimiter); skelSet.Write(result); FileAnim = result; } } /// <summary> /// Handles the Click event of the btnAnimSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnAnimSave_Click(object sender, EventArgs e) { if (FileAnim != null && FileAnim.Length > 1) { var skelSet = SkeletonLoader.LoadSkeletonSetFromString(txtFrames.Text, _skeletonSetFromStringDelimiter); skelSet.Write(FileAnim); } } /// <summary> /// Handles the Click event of the btnBodyLoad control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnBodyLoad_Click(object sender, EventArgs e) { var result = GetLoadSkeletonDialogResult(_filterBody); if (result != null && result.Length > 1) LoadBody(result); } /// <summary> /// Handles the Click event of the btnBodySaveAs control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnBodySaveAs_Click(object sender, EventArgs e) { var result = GetSaveSkeletonDialogResult(_filterBody); if (result != null && result.Length > 1) { SkeletonBody.BodyInfo.Save(result); FileBody = result; } } /// <summary> /// Handles the Click event of the btnBodySave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnBodySave_Click(object sender, EventArgs e) { if (FileBody != null && FileBody.Length > 1) SkeletonBody.BodyInfo.Save(FileBody); } /// <summary> /// Handles the Click event of the btnClearTarget control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnClearTarget_Click(object sender, EventArgs e) { cmbTarget.SelectedItem = null; } /// <summary> /// Handles the Click event of the btnCopyInherits control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnCopyInherits_Click(object sender, EventArgs e) { var results = GetLoadSkeletonDialogResults(_filterFrame); if (results == null || results.Length <= 0) return; foreach (var s in results) { if (!File.Exists(s)) continue; var tmpSkel = SkeletonLoader.LoadSkeleton(s); _skeleton.CopyIsModifier(tmpSkel); tmpSkel.Write(s); } } /// <summary> /// Handles the Click event of the btnCopyLen control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnCopyLen_Click(object sender, EventArgs e) { var results = GetLoadSkeletonDialogResults(_filterFrame); if (results == null || results.Length <= 0) return; foreach (var s in results) { if (!File.Exists(s)) continue; var tmpSkel = SkeletonLoader.LoadSkeleton(s); Skeleton.CopyLength(_skeleton, tmpSkel); tmpSkel.Write(s); } } /// <summary> /// Handles the Click event of the btnCopyRoot control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnCopyRoot_Click(object sender, EventArgs e) { var rX = MessageBox.Show("Copy the X axis?", "Skeleton frame root copy", MessageBoxButtons.YesNoCancel); if (rX == DialogResult.Cancel) return; var rY = MessageBox.Show("Copy the Y axis?", "Skeleton frame root copy", MessageBoxButtons.YesNoCancel); if (rY == DialogResult.Cancel) return; if (rX == DialogResult.No && rY == DialogResult.No) return; var results = GetLoadSkeletonDialogResults(_filterFrame); if (results != null && results.Length > 0) { foreach (var s in results) { if (!File.Exists(s)) continue; var tmpSkel = SkeletonLoader.LoadSkeleton(s); var newPos = _skeleton.RootNode.Position; if (rX == DialogResult.Yes) newPos.X = tmpSkel.RootNode.X; if (rY == DialogResult.Yes) newPos.Y = tmpSkel.RootNode.Y; tmpSkel.RootNode.MoveTo(newPos); tmpSkel.Write(s); } } } /// <summary> /// Handles the Click event of the btnDelete control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnDelete_Click(object sender, EventArgs e) { if (lstBodies.SelectedIndex == -1) return; var sel = lstBodies.SelectedIndex; for (var i = sel; i < lstBodies.Items.Count - 1; i++) { lstBodies.Items[i] = lstBodies.Items[i + 1]; SkeletonBody.BodyItems[i] = SkeletonBody.BodyItems[i + 1]; _frameBody.BodyItems[i] = _frameBody.BodyItems[i + 1]; } lstBodies.RemoveItemAtAndReselect(lstBodies.Items.Count - 1); Array.Resize(ref SkeletonBody.BodyItems, SkeletonBody.BodyItems.Length - 1); Array.Resize(ref _frameBody.BodyItems, _frameBody.BodyItems.Length - 1); } /// <summary> /// Handles the Click event of the btnDown control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnDown_Click(object sender, EventArgs e) { var selIndex = lstBodies.SelectedIndex; if (selIndex < 0 || selIndex >= lstBodies.Items.Count - 1) return; var o1 = lstBodies.Items[selIndex]; var o2 = lstBodies.Items[selIndex + 1]; lstBodies.Items[selIndex] = o2; lstBodies.Items[selIndex + 1] = o1; o1 = SkeletonBody.BodyItems[selIndex]; o2 = SkeletonBody.BodyItems[selIndex + 1]; SkeletonBody.BodyItems[selIndex] = (SkeletonBodyItem)o2; SkeletonBody.BodyItems[selIndex + 1] = (SkeletonBodyItem)o1; o1 = _frameBody.BodyItems[selIndex]; o2 = _frameBody.BodyItems[selIndex + 1]; _frameBody.BodyItems[selIndex] = (SkeletonBodyItem)o2; _frameBody.BodyItems[selIndex + 1] = (SkeletonBodyItem)o1; var tmp = SkeletonBody.BodyInfo.Items[selIndex]; SkeletonBody.BodyInfo.Items[selIndex] = SkeletonBody.BodyInfo.Items[selIndex + 1]; SkeletonBody.BodyInfo.Items[selIndex + 1] = tmp; tmp = _frameBody.BodyInfo.Items[selIndex]; _frameBody.BodyInfo.Items[selIndex] = _frameBody.BodyInfo.Items[selIndex + 1]; _frameBody.BodyInfo.Items[selIndex + 1] = tmp; lstBodies.SelectedIndex = selIndex + 1; } /// <summary> /// Handles the Click event of the btnFall control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnFall_Click(object sender, EventArgs e) { if (!radioAnimate.Checked) return; var newSet = new SkeletonSet(SkeletonLoader.FallingSkeletonSetName, ContentPaths.Dev); _skeletonAnim.ChangeSet(newSet); } /// <summary> /// Handles the Click event of the btnInterpolate control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnInterpolate_Click(object sender, EventArgs e) { var result = GetLoadSkeletonDialogResult(_filterFrame); if (result == null || result.Length <= 1) return; var frame1Skeleton = SkeletonLoader.LoadSkeleton(result); var frame1 = new SkeletonFrame(result, frame1Skeleton, 10); result = GetLoadSkeletonDialogResult(_filterFrame); if (result == null || result.Length <= 1) return; var frame2Skeleton = SkeletonLoader.LoadSkeleton(result); var frame2 = new SkeletonFrame(result, frame2Skeleton, 10); var frames = new[] { frame1, frame2 }; var ss = new SkeletonSet(frames); var sa = new SkeletonAnimation(GetTime(), ss); sa.Update(5); LoadFrame(sa.Skeleton); } /// <summary> /// Handles the Click event of the btnJump control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnJump_Click(object sender, EventArgs e) { if (!radioAnimate.Checked) return; var newSet = new SkeletonSet(SkeletonLoader.JumpingSkeletonSetName, ContentPaths.Dev); _skeletonAnim.ChangeSet(newSet); } /// <summary> /// Handles the Click event of the btnPause control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnPause_Click(object sender, EventArgs e) { if (_watch.IsRunning) _watch.Stop(); else _watch.Start(); } /// <summary> /// Handles the Click event of the btnPlay control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnPlay_Click(object sender, EventArgs e) { if (!_watch.IsRunning) _watch.Start(); SetAnimByTxt(); } /// <summary> /// Handles the GrhDataSelected event of the btnSelectBodyGrhData control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="NetGore.EventArgs{GrhData}"/> instance containing the event data.</param> void btnSelectBodyGrhData_GrhDataSelected(object sender, EventArgs<GrhData> e) { if (e.Item1 == null) txtGrhIndex.Text = ""; else txtGrhIndex.Text = e.Item1.GrhIndex.ToString(); } GrhData btnSelectBodyGrhData_SelectedGrhDataHandler(object sender) { if (SelectedDSI == null || SelectedDSI.Grh == null) return null; return SelectedDSI.Grh.GrhData; } /// <summary> /// Handles the Click event of the btnShiftNodes control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnShiftNodes_Click(object sender, EventArgs e) { using (var f = new ShiftNodesInputForm()) { if (f.ShowDialog(this) != DialogResult.OK) return; var p = f.Value; if (p != Vector2.Zero) { foreach (var node in _skeleton.RootNode.GetAllNodes()) { node.Position += p; } } } } /// <summary> /// Handles the Click event of the btnSkeletonLoad control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnSkeletonLoad_Click(object sender, EventArgs e) { var result = GetLoadSkeletonDialogResult(_filterFrame); if (result != null && result.Length > 1) LoadFrame(result); } /// <summary> /// Handles the Click event of the btnSkeletonSaveAs control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnSkeletonSaveAs_Click(object sender, EventArgs e) { var result = GetSaveSkeletonDialogResult(_filterFrame); if (result != null && result.Length > 1) { _skeleton.Write(result); FileFrame = result; } } /// <summary> /// Handles the Click event of the btnSkeletonSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnSkeletonSave_Click(object sender, EventArgs e) { if (FileFrame != null && FileFrame.Length > 1) _skeleton.Write(FileFrame); } /// <summary> /// Handles the Click event of the btnStand control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnStand_Click(object sender, EventArgs e) { if (!radioAnimate.Checked) return; var standingSet = SkeletonLoader.GetStandingSkeletonSet(); _skeletonAnim.ChangeSet(standingSet); } /// <summary> /// Handles the Click event of the btnUp control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnUp_Click(object sender, EventArgs e) { var selIndex = lstBodies.SelectedIndex; if (selIndex <= 0) return; var o1 = lstBodies.Items[selIndex]; var o2 = lstBodies.Items[selIndex - 1]; lstBodies.Items[selIndex] = o2; lstBodies.Items[selIndex - 1] = o1; o1 = SkeletonBody.BodyItems[selIndex]; o2 = SkeletonBody.BodyItems[selIndex - 1]; SkeletonBody.BodyItems[selIndex] = (SkeletonBodyItem)o2; SkeletonBody.BodyItems[selIndex - 1] = (SkeletonBodyItem)o1; o1 = _frameBody.BodyItems[selIndex]; o2 = _frameBody.BodyItems[selIndex - 1]; _frameBody.BodyItems[selIndex] = (SkeletonBodyItem)o2; _frameBody.BodyItems[selIndex - 1] = (SkeletonBodyItem)o1; var tmp = SkeletonBody.BodyInfo.Items[selIndex]; SkeletonBody.BodyInfo.Items[selIndex] = SkeletonBody.BodyInfo.Items[selIndex - 1]; SkeletonBody.BodyInfo.Items[selIndex - 1] = tmp; tmp = _frameBody.BodyInfo.Items[selIndex]; _frameBody.BodyInfo.Items[selIndex] = _frameBody.BodyInfo.Items[selIndex - 1]; _frameBody.BodyInfo.Items[selIndex - 1] = tmp; lstBodies.SelectedIndex = selIndex - 1; } /// <summary> /// Handles the Click event of the btnWalk control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void btnWalk_Click(object sender, EventArgs e) { if (!radioAnimate.Checked) return; var newSet = new SkeletonSet(SkeletonLoader.WalkingSkeletonSetName, ContentPaths.Dev); _skeletonAnim.ChangeSet(newSet); } /// <summary> /// Handles the CheckedChanged event of the chkIsMod control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void chkIsMod_CheckedChanged(object sender, EventArgs e) { try { SelectedNode.IsModifier = chkIsMod.Checked; chkIsMod.BackColor = EditorColors.Normal; } catch { chkIsMod.BackColor = EditorColors.Error; } } /// <summary> /// Handles the SelectedIndexChanged event of the cmbSkeletonNodes control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void cmbSkeletonNodes_SelectedIndexChanged(object sender, EventArgs e) { UpdateNodeInfo(); } /// <summary> /// Handles the SelectedIndexChanged event of the cmbSource control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void cmbSource_SelectedIndexChanged(object sender, EventArgs e) { if (SelectedDSI == null) return; try { SelectedDSI.Source = cmbSource.SelectedItem as SkeletonNode; cmbSource.BackColor = EditorColors.Normal; UpdateSelectedDSI(); } catch { cmbSource.BackColor = EditorColors.Error; } } /// <summary> /// Handles the SelectedIndexChanged event of the cmbTarget control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void cmbTarget_SelectedIndexChanged(object sender, EventArgs e) { if (SelectedDSI == null) return; try { SelectedDSI.Dest = cmbTarget.SelectedItem as SkeletonNode; cmbTarget.BackColor = EditorColors.Normal; UpdateSelectedDSI(); } catch { cmbTarget.BackColor = EditorColors.Error; } } /// <summary> /// Handles the SelectedIndexChanged event of the lstBodies control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void lstBodies_SelectedIndexChanged(object sender, EventArgs e) { var item = SelectedDSI; if (item == null) return; txtOffsetX.Text = item.ItemInfo.Offset.X.ToString(); txtOffsetY.Text = item.ItemInfo.Offset.Y.ToString(); txtOriginX.Text = item.ItemInfo.Origin.X.ToString(); txtOriginY.Text = item.ItemInfo.Origin.Y.ToString(); if (item.Grh.GrhData != null) txtGrhIndex.Text = item.Grh.GrhData.GrhIndex.ToString(); if (item.Source == null) cmbSource.SelectedItem = null; else cmbSource.SelectedItem = cmbSource.Items.OfType<SkeletonNode>().FirstOrDefault(x => x.Name == item.Source.Name); if (item.Dest == null) cmbTarget.SelectedItem = null; else cmbTarget.SelectedItem = cmbTarget.Items.OfType<SkeletonNode>().FirstOrDefault(x => x.Name == item.Dest.Name); } /// <summary> /// Handles the CheckedChanged event of the radioAnimate control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void radioAnimate_CheckedChanged(object sender, EventArgs e) { if (radioAnimate.Checked) SetAnimByTxt(); } /// <summary> /// Handles the TextChanged event of the txtAngle control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void txtAngle_TextChanged(object sender, EventArgs e) { try { SelectedNode.SetAngle(Parser.Current.ParseFloat(txtAngle.Text)); txtAngle.BackColor = EditorColors.Normal; } catch { txtAngle.BackColor = EditorColors.Error; } } /// <summary> /// Handles the TextChanged event of the txtFrames control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void txtFrames_TextChanged(object sender, EventArgs e) { SetAnimByTxt(); } /// <summary> /// Handles the TextChanged event of the txtGrhIndex control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void txtGrhIndex_TextChanged(object sender, EventArgs e) { try { var grhIndex = Parser.Current.ParseGrhIndex(txtGrhIndex.Text); var grhData = GrhInfo.GetData(grhIndex); if (grhData == null) { txtGrhIndex.BackColor = EditorColors.Error; return; } SelectedDSI.Grh.SetGrh(grhData, AnimType.Loop, (TickCount)_watch.ElapsedMilliseconds); SelectedDSI.ItemInfo.GrhIndex = grhIndex; txtGrhIndex.BackColor = EditorColors.Normal; UpdateSelectedDSI(); } catch { txtGrhIndex.BackColor = EditorColors.Error; } } /// <summary> /// Handles the TextChanged event of the txtLength control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void txtLength_TextChanged(object sender, EventArgs e) { try { SelectedNode.SetLength(Parser.Current.ParseFloat(txtLength.Text)); txtLength.BackColor = EditorColors.Normal; } catch { txtLength.BackColor = EditorColors.Error; } } /// <summary> /// Handles the TextChanged event of the txtName control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void txtName_TextChanged(object sender, EventArgs e) { try { SelectedNode.Name = txtName.Text; txtName.BackColor = EditorColors.Normal; } catch { txtName.BackColor = EditorColors.Error; } } /// <summary> /// Handles the TextChanged event of the txtOffsetX control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void txtOffsetX_TextChanged(object sender, EventArgs e) { try { var x = Parser.Current.ParseFloat(txtOffsetX.Text); SelectedDSI.ItemInfo.Offset = new Vector2(x, SelectedDSI.ItemInfo.Offset.Y); txtOffsetX.BackColor = EditorColors.Normal; } catch { txtOffsetX.BackColor = EditorColors.Error; } } /// <summary> /// Handles the TextChanged event of the txtOffsetY control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void txtOffsetY_TextChanged(object sender, EventArgs e) { try { var y = Parser.Current.ParseFloat(txtOffsetY.Text); SelectedDSI.ItemInfo.Offset = new Vector2(SelectedDSI.ItemInfo.Offset.X, y); txtOffsetY.BackColor = EditorColors.Normal; } catch { txtOffsetY.BackColor = EditorColors.Error; } } /// <summary> /// Handles the TextChanged event of the txtOriginX control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void txtOriginX_TextChanged(object sender, EventArgs e) { try { var x = Parser.Current.ParseFloat(txtOriginX.Text); SelectedDSI.ItemInfo.Origin = new Vector2(x, SelectedDSI.ItemInfo.Origin.Y); txtOriginX.BackColor = EditorColors.Normal; } catch { txtOriginX.BackColor = EditorColors.Error; } } /// <summary> /// Handles the TextChanged event of the txtOriginY control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void txtOriginY_TextChanged(object sender, EventArgs e) { try { var y = Parser.Current.ParseFloat(txtOriginY.Text); SelectedDSI.ItemInfo.Origin = new Vector2(SelectedDSI.ItemInfo.Origin.X, y); txtOriginY.BackColor = EditorColors.Normal; } catch { txtOriginY.BackColor = EditorColors.Error; } } /// <summary> /// Handles the TextChanged event of the txtX control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void txtX_TextChanged(object sender, EventArgs e) { try { if (SelectedNode.Parent == null) SelectedNode.MoveTo(new Vector2(Parser.Current.ParseFloat(txtX.Text), SelectedNode.Y)); else SelectedNode.X = Parser.Current.ParseFloat(txtX.Text); txtX.BackColor = EditorColors.Normal; } catch { txtX.BackColor = EditorColors.Error; } } /// <summary> /// Handles the TextChanged event of the txtY control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> void txtY_TextChanged(object sender, EventArgs e) { try { if (SelectedNode.Parent == null) SelectedNode.MoveTo(new Vector2(SelectedNode.X, Parser.Current.ParseFloat(txtY.Text))); else SelectedNode.Y = Parser.Current.ParseFloat(txtY.Text); txtY.BackColor = EditorColors.Normal; } catch { txtY.BackColor = EditorColors.Error; } } private void txtAngle_Leave(object sender, EventArgs e) { if (SelectedNode != null) txtAngle.Text = SelectedNode.GetAngle().ToString(); } private void txtLength_Leave(object sender, EventArgs e) { txtLength.Text = SelectedNode.GetLength().ToString("#.###"); } private void cmbSkeletonBodies_SelectedIndexChanged(object sender, EventArgs e) { cmbSkeletonBodyNodes.Items.Clear(); DirectoryInfo skelBodiesFolder = new DirectoryInfo(ContentPaths.Build.Grhs + "\\Character\\Skeletons\\" + cmbSkeletonBodies.SelectedItem.ToString()); foreach (FileInfo skelBodyNode in skelBodiesFolder.GetFiles()) cmbSkeletonBodyNodes.Items.Add(skelBodyNode.Name); } } }
using UnityEngine; using System.Collections.Generic; public class MegaLoftLayerCloneSplineRules : MegaLoftLayerRules { public int curve = 0; public bool snap = false; [ContextMenu("Help")] public void Help() { Application.OpenURL("http://www.west-racing.com/mf/?page_id=2205"); } public override bool Valid() { if ( LayerEnabled && layerPath && layerPath.splines != null ) { if ( rules.Count > 0 ) return true; } return false; } public override Vector3 GetPos(MegaShapeLoft loft, float ca, float a) { return Vector3.zero; } public override bool PrepareLoft(MegaShapeLoft loft, int sc) { if ( layerPath == null ) return false; if ( rules.Count == 0 ) return false; Random.seed = Seed; Init(); BuildRules(); float tlen = layerPath.splines[curve].length * Length; BuildLoftObjects(tlen); for ( int r = 0; r < rules.Count; r++ ) { for ( int i = 0; i < rules[r].lofttris.Count; i++ ) { rules[r].lofttris[i].offset = 0; rules[r].lofttris[i].tris = new int[rules[r].lofttris[i].sourcetris.Length * rules[r].usage]; } } int vcount = 0; int tcount = 0; for ( int r = 0; r < loftobjs.Count; r++ ) { vcount += loftobjs[r].verts.Length; tcount += loftobjs[r].tris.Length; } if ( loftverts == null || loftverts.Length != vcount ) loftverts = new Vector3[vcount]; if ( loftuvs == null || loftuvs.Length != vcount ) loftuvs = new Vector2[vcount]; if ( lofttris == null || lofttris.Length != tcount ) lofttris = new int[tcount]; return true; } Vector3 Deform(Vector3 p, MegaShape path, float percent, float off, Vector3 scale, float removeDof, Vector3 locoff, Vector3 sploff) { p = tm.MultiplyPoint3x4(p); p.z += off; p.x *= scale.x; p.y *= scale.y; p.z *= scale.z; p += locoff; float alpha = (p.z / path.splines[curve].length) + percent; float tw1 = 0.0f; Vector3 ps = path.InterpCurve3D(curve, alpha, path.normalizedInterp, ref tw1) + sploff; Vector3 ps1 = path.InterpCurve3D(curve, alpha + (tangent * 0.001f), path.normalizedInterp) + sploff; if ( path.splines[curve].closed ) alpha = Mathf.Repeat(alpha, 1.0f); else alpha = Mathf.Clamp01(alpha); tw = Quaternion.AngleAxis((twist * twistCrv.Evaluate(alpha)) + tw1, Vector3.forward); Vector3 relativePos = ps1 - ps; relativePos.y *= removeDof; Quaternion rotation = Quaternion.LookRotation(relativePos) * tw; //wtm.SetTRS(ps, rotation, Vector3.one); MegaMatrix.SetTR(ref wtm, ps, rotation); wtm = mat * wtm; p.z = 0.0f; return wtm.MultiplyPoint3x4(p); } public override int BuildMesh(MegaShapeLoft loft, int triindex) { if ( tangent < 0.1f ) tangent = 0.1f; //mat = layerPath.transform.localToWorldMatrix; //mat = transform.localToWorldMatrix * layerPath.transform.worldToLocalMatrix; // * transform.worldToLocalMatrix; //mat = surfaceLoft.transform.localToWorldMatrix; mat = Matrix4x4.identity; tm = Matrix4x4.identity; MegaMatrix.Rotate(ref tm, Mathf.Deg2Rad * tmrot); float off = 0.0f; int trioff = 0; int vi = 0; Vector3 sploff = Vector3.zero; if ( snap ) sploff = layerPath.splines[0].knots[0].p - layerPath.splines[curve].knots[0].p; for ( int r = 0; r < rules.Count; r++ ) { for ( int i = 0; i < rules[r].lofttris.Count; i++ ) rules[r].lofttris[i].offset = 0; } for ( int r = 0; r < loftobjs.Count; r++ ) { MegaLoftRule obj = loftobjs[r]; Vector3 sscl = (scale + obj.scale) * GlobalScale; Vector3 soff = Vector3.Scale(offset + obj.offset, sscl); off -= obj.bounds.min[(int)axis]; off += (obj.gapin * obj.bounds.size[(int)axis]); for ( int i = 0; i < obj.verts.Length; i++ ) { Vector3 p = obj.verts[i]; p = Deform(p, layerPath, start, off, sscl, RemoveDof, soff, sploff); loftverts[vi] = p; loftuvs[vi++] = obj.uvs[i]; } for ( int i = 0; i < obj.lofttris.Count; i++ ) { int toff = obj.lofttris[i].offset; for ( int t = 0; t < obj.lofttris[i].sourcetris.Length; t++ ) obj.lofttris[i].tris[toff++] = obj.lofttris[i].sourcetris[t] + trioff + triindex; obj.lofttris[i].offset = toff; } off += obj.bounds.max[(int)axis]; off += (obj.gapout * obj.bounds.size[(int)axis]); trioff = vi; } if ( conform ) { CalcBounds(loftverts); DoConform(loft, loftverts); } return triindex; } public override MegaLoftLayerBase Copy(GameObject go) { MegaLoftLayerCloneSplineRules layer = go.AddComponent<MegaLoftLayerCloneSplineRules>(); Copy(this, layer); loftverts = null; loftuvs = null; loftcols = null; lofttris = null; return null; } // Conform public bool conform = false; public GameObject target; public Collider conformCollider; public float[] offsets; public float[] last; public float conformAmount = 1.0f; public float raystartoff = 0.0f; public float raydist = 10.0f; public float conformOffset = 0.0f; float minz = 0.0f; public bool showConformParams = false; public void SetTarget(GameObject targ) { target = targ; if ( target ) { conformCollider = target.GetComponent<Collider>(); } } void CalcBounds(Vector3[] verts) { minz = verts[0].y; for ( int i = 1; i < verts.Length; i++ ) { if ( verts[i].y < minz ) minz = verts[i].y; } } public void InitConform(Vector3[] verts) { if ( offsets == null || offsets.Length != verts.Length ) { offsets = new float[verts.Length]; last = new float[verts.Length]; for ( int i = 0; i < verts.Length; i++ ) offsets[i] = verts[i].y - minz; } // Only need to do this if target changes, move to SetTarget if ( target ) { //MeshFilter mf = target.GetComponent<MeshFilter>(); //targetMesh = mf.sharedMesh; conformCollider = target.GetComponent<Collider>(); } } // We could do a bary centric thing if we grid up the bounds void DoConform(MegaShapeLoft loft, Vector3[] verts) { InitConform(verts); if ( target && conformCollider ) { Matrix4x4 loctoworld = transform.localToWorldMatrix; Matrix4x4 tm = loctoworld; // * worldtoloc; Matrix4x4 invtm = tm.inverse; Ray ray = new Ray(); RaycastHit hit; float ca = conformAmount * loft.conformAmount; // When calculating alpha need to do caps sep for ( int i = 0; i < verts.Length; i++ ) { Vector3 origin = tm.MultiplyPoint(verts[i]); origin.y += raystartoff; ray.origin = origin; ray.direction = Vector3.down; //loftverts[i] = loftverts1[i]; if ( conformCollider.Raycast(ray, out hit, raydist) ) { Vector3 lochit = invtm.MultiplyPoint(hit.point); verts[i].y = Mathf.Lerp(verts[i].y, lochit.y + offsets[i] + conformOffset, ca); //conformAmount); last[i] = verts[i].y; } else { Vector3 ht = ray.origin; ht.y -= raydist; verts[i].y = last[i]; //lochit.z + offsets[i] + offset; } } } else { } } }
// dnlib: See LICENSE.txt for more info using System.Collections.Generic; namespace dnlib.DotNet { /// <summary> /// Various helper methods for <see cref="IType"/> classes to prevent infinite recursion /// </summary> struct TypeHelper { RecursionCounter recursionCounter; internal static bool ContainsGenericParameter(StandAloneSig ss) => ss is not null && TypeHelper.ContainsGenericParameter(ss.Signature); internal static bool ContainsGenericParameter(InterfaceImpl ii) => ii is not null && TypeHelper.ContainsGenericParameter(ii.Interface); internal static bool ContainsGenericParameter(GenericParamConstraint gpc) => gpc is not null && ContainsGenericParameter(gpc.Constraint); internal static bool ContainsGenericParameter(MethodSpec ms) => ms is not null && ContainsGenericParameter(ms.GenericInstMethodSig); internal static bool ContainsGenericParameter(MemberRef mr) { if (mr is null) return false; if (ContainsGenericParameter(mr.Signature)) return true; var cl = mr.Class; if (cl is ITypeDefOrRef tdr) return tdr.ContainsGenericParameter; if (cl is MethodDef md) return TypeHelper.ContainsGenericParameter(md.Signature); return false; } /// <summary> /// Checks whether <paramref name="callConv"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>. /// </summary> /// <param name="callConv">Calling convention signature</param> /// <returns><c>true</c> if <paramref name="callConv"/> contains a <see cref="GenericVar"/> /// or a <see cref="GenericMVar"/>.</returns> public static bool ContainsGenericParameter(CallingConventionSig callConv) { if (callConv is FieldSig fs) return ContainsGenericParameter(fs); if (callConv is MethodBaseSig mbs) return ContainsGenericParameter(mbs); if (callConv is LocalSig ls) return ContainsGenericParameter(ls); if (callConv is GenericInstMethodSig gim) return ContainsGenericParameter(gim); return false; } /// <summary> /// Checks whether <paramref name="fieldSig"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>. /// </summary> /// <param name="fieldSig">Field signature</param> /// <returns><c>true</c> if <paramref name="fieldSig"/> contains a <see cref="GenericVar"/> /// or a <see cref="GenericMVar"/>.</returns> public static bool ContainsGenericParameter(FieldSig fieldSig) => new TypeHelper().ContainsGenericParameterInternal(fieldSig); /// <summary> /// Checks whether <paramref name="methodSig"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>. /// </summary> /// <param name="methodSig">Method or property signature</param> /// <returns><c>true</c> if <paramref name="methodSig"/> contains a <see cref="GenericVar"/> /// or a <see cref="GenericMVar"/>.</returns> public static bool ContainsGenericParameter(MethodBaseSig methodSig) => new TypeHelper().ContainsGenericParameterInternal(methodSig); /// <summary> /// Checks whether <paramref name="localSig"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>. /// </summary> /// <param name="localSig">Local signature</param> /// <returns><c>true</c> if <paramref name="localSig"/> contains a <see cref="GenericVar"/> /// or a <see cref="GenericMVar"/>.</returns> public static bool ContainsGenericParameter(LocalSig localSig) => new TypeHelper().ContainsGenericParameterInternal(localSig); /// <summary> /// Checks whether <paramref name="gim"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>. /// </summary> /// <param name="gim">Generic method signature</param> /// <returns><c>true</c> if <paramref name="gim"/> contains a <see cref="GenericVar"/> /// or a <see cref="GenericMVar"/>.</returns> public static bool ContainsGenericParameter(GenericInstMethodSig gim) => new TypeHelper().ContainsGenericParameterInternal(gim); /// <summary> /// Checks whether <paramref name="type"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>. /// </summary> /// <param name="type">Type</param> /// <returns><c>true</c> if <paramref name="type"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>.</returns> public static bool ContainsGenericParameter(IType type) { if (type is TypeDef td) return ContainsGenericParameter(td); if (type is TypeRef tr) return ContainsGenericParameter(tr); if (type is TypeSpec ts) return ContainsGenericParameter(ts); if (type is TypeSig sig) return ContainsGenericParameter(sig); if (type is ExportedType et) return ContainsGenericParameter(et); return false; } /// <summary> /// Checks whether <paramref name="type"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>. /// </summary> /// <param name="type">Type</param> /// <returns><c>true</c> if <paramref name="type"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>.</returns> public static bool ContainsGenericParameter(TypeDef type) => new TypeHelper().ContainsGenericParameterInternal(type); /// <summary> /// Checks whether <paramref name="type"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>. /// </summary> /// <param name="type">Type</param> /// <returns><c>true</c> if <paramref name="type"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>.</returns> public static bool ContainsGenericParameter(TypeRef type) => new TypeHelper().ContainsGenericParameterInternal(type); /// <summary> /// Checks whether <paramref name="type"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>. /// </summary> /// <param name="type">Type</param> /// <returns><c>true</c> if <paramref name="type"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>.</returns> public static bool ContainsGenericParameter(TypeSpec type) => new TypeHelper().ContainsGenericParameterInternal(type); /// <summary> /// Checks whether <paramref name="type"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>. /// </summary> /// <param name="type">Type</param> /// <returns><c>true</c> if <paramref name="type"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>.</returns> public static bool ContainsGenericParameter(TypeSig type) => new TypeHelper().ContainsGenericParameterInternal(type); /// <summary> /// Checks whether <paramref name="type"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>. /// </summary> /// <param name="type">Type</param> /// <returns><c>true</c> if <paramref name="type"/> contains a <see cref="GenericVar"/> or a /// <see cref="GenericMVar"/>.</returns> public static bool ContainsGenericParameter(ExportedType type) => new TypeHelper().ContainsGenericParameterInternal(type); bool ContainsGenericParameterInternal(TypeDef type) => false; bool ContainsGenericParameterInternal(TypeRef type) => false; bool ContainsGenericParameterInternal(TypeSpec type) { if (type is null) return false; if (!recursionCounter.Increment()) return false; bool res = ContainsGenericParameterInternal(type.TypeSig); recursionCounter.Decrement(); return res; } bool ContainsGenericParameterInternal(ITypeDefOrRef tdr) { if (tdr is null) return false; // TypeDef and TypeRef contain no generic parameters return ContainsGenericParameterInternal(tdr as TypeSpec); } bool ContainsGenericParameterInternal(TypeSig type) { if (type is null) return false; if (!recursionCounter.Increment()) return false; bool res; switch (type.ElementType) { case ElementType.Void: case ElementType.Boolean: case ElementType.Char: case ElementType.I1: case ElementType.U1: case ElementType.I2: case ElementType.U2: case ElementType.I4: case ElementType.U4: case ElementType.I8: case ElementType.U8: case ElementType.R4: case ElementType.R8: case ElementType.String: case ElementType.ValueType: case ElementType.Class: case ElementType.TypedByRef: case ElementType.I: case ElementType.U: case ElementType.Object: res = ContainsGenericParameterInternal((type as TypeDefOrRefSig).TypeDefOrRef); break; case ElementType.Var: case ElementType.MVar: res = true; break; case ElementType.FnPtr: res = ContainsGenericParameterInternal((type as FnPtrSig).Signature); break; case ElementType.GenericInst: var gi = (GenericInstSig)type; res = ContainsGenericParameterInternal(gi.GenericType) || ContainsGenericParameter(gi.GenericArguments); break; case ElementType.Ptr: case ElementType.ByRef: case ElementType.Array: case ElementType.SZArray: case ElementType.Pinned: case ElementType.ValueArray: case ElementType.Module: res = ContainsGenericParameterInternal((type as NonLeafSig).Next); break; case ElementType.CModReqd: case ElementType.CModOpt: res = ContainsGenericParameterInternal((type as ModifierSig).Modifier) || ContainsGenericParameterInternal((type as NonLeafSig).Next); break; case ElementType.End: case ElementType.R: case ElementType.Internal: case ElementType.Sentinel: default: res = false; break; } recursionCounter.Decrement(); return res; } bool ContainsGenericParameterInternal(ExportedType type) => false; bool ContainsGenericParameterInternal(CallingConventionSig callConv) { if (callConv is FieldSig fs) return ContainsGenericParameterInternal(fs); if (callConv is MethodBaseSig mbs) return ContainsGenericParameterInternal(mbs); if (callConv is LocalSig ls) return ContainsGenericParameterInternal(ls); if (callConv is GenericInstMethodSig gim) return ContainsGenericParameterInternal(gim); return false; } bool ContainsGenericParameterInternal(FieldSig fs) { if (fs is null) return false; if (!recursionCounter.Increment()) return false; bool res = ContainsGenericParameterInternal(fs.Type); recursionCounter.Decrement(); return res; } bool ContainsGenericParameterInternal(MethodBaseSig mbs) { if (mbs is null) return false; if (!recursionCounter.Increment()) return false; bool res = ContainsGenericParameterInternal(mbs.RetType) || ContainsGenericParameter(mbs.Params) || ContainsGenericParameter(mbs.ParamsAfterSentinel); recursionCounter.Decrement(); return res; } bool ContainsGenericParameterInternal(LocalSig ls) { if (ls is null) return false; if (!recursionCounter.Increment()) return false; bool res = ContainsGenericParameter(ls.Locals); recursionCounter.Decrement(); return res; } bool ContainsGenericParameterInternal(GenericInstMethodSig gim) { if (gim is null) return false; if (!recursionCounter.Increment()) return false; bool res = ContainsGenericParameter(gim.GenericArguments); recursionCounter.Decrement(); return res; } bool ContainsGenericParameter(IList<TypeSig> types) { if (types is null) return false; if (!recursionCounter.Increment()) return false; bool res = false; int count = types.Count; for (int i = 0; i < count; i++) { var type = types[i]; if (ContainsGenericParameter(type)) { res = true; break; } } recursionCounter.Decrement(); return res; } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.S3.Model { /// <summary> /// Container for the parameters to the PutObject operation. /// <para>Adds an object to a bucket.</para> /// </summary> public partial class PutObjectRequest : PutWithACLRequest { private S3CannedACL cannedACL; private string bucketName; private string key; private S3StorageClass storageClass; private string websiteRedirectLocation; private HeadersCollection headersCollection = new HeadersCollection(); private MetadataCollection metadataCollection = new MetadataCollection(); private ServerSideEncryptionMethod serverSideEncryption; private ServerSideEncryptionCustomerMethod serverSideCustomerEncryption; private string serverSideEncryptionCustomerProvidedKey; private string serverSideEncryptionCustomerProvidedKeyMD5; private string serverSideEncryptionKeyManagementServiceKeyId; private Stream inputStream; private string filePath; private string contentBody; private bool autoCloseStream = true; private bool autoResetStreamPosition = true; private string md5Digest; /// <summary> /// A canned access control list (CACL) to apply to the object. /// Please refer to <see cref="T:Amazon.S3.S3CannedACL"/> for /// information on S3 Canned ACLs. /// </summary> public S3CannedACL CannedACL { get { return this.cannedACL; } set { this.cannedACL = value; } } // Check to see if CannedACL property is set internal bool IsSetCannedACL() { return cannedACL != null && cannedACL != S3CannedACL.NoACL; } /// <summary> /// Input stream for the request; content for the request will be read from the stream. /// </summary> public Stream InputStream { get { return this.inputStream; } set { this.inputStream = value; } } // Check to see if Body property is set internal bool IsSetInputStream() { return this.inputStream != null; } /// <summary> /// <para> /// The full path and name to a file to be uploaded. /// If this is set the request will upload the specified file to S3. /// </para> /// <para> /// For WinRT and Windows Phone this property must be in the form of "ms-appdata:///local/file.txt". /// </para> /// </summary> public string FilePath { get { return this.filePath; } set { this.filePath = value; } } /// <summary> /// Text content to be uploaded. Use this property if you want to upload plaintext to S3. /// The content type will be set to 'text/plain'. /// </summary> public string ContentBody { get { return this.contentBody; } set { this.contentBody = value; } } /// <summary> /// If this value is set to true then the stream used with this request will be closed when all the content /// is read from the stream. /// Default: true. /// </summary> public bool AutoCloseStream { get { return this.autoCloseStream; } set { this.autoCloseStream = value; } } /// <summary> /// If this value is set to true then the stream will be seeked back to the start before being read for upload. /// Default: true. /// </summary> public bool AutoResetStreamPosition { get { return this.autoResetStreamPosition; } set { this.autoResetStreamPosition = value; } } /// <summary> /// The name of the bucket to contain the object. /// </summary> public string BucketName { get { return this.bucketName; } set { this.bucketName = value; } } // Check to see if Bucket property is set internal bool IsSetBucket() { return this.bucketName != null; } /// <summary> /// The collection of headers for the request. /// </summary> public HeadersCollection Headers { get { if (this.headersCollection == null) this.headersCollection = new HeadersCollection(); return this.headersCollection; } internal set { this.headersCollection = value; } } /// <summary> /// The collection of meta data for the request. /// </summary> public MetadataCollection Metadata { get { if (this.metadataCollection == null) this.metadataCollection = new MetadataCollection(); return this.metadataCollection; } internal set { this.metadataCollection = value; } } public string Key { get { return this.key; } set { this.key = value; } } // Check to see if Key property is set internal bool IsSetKey() { return this.key != null; } /// <summary> /// The Server-side encryption algorithm used when storing this object in S3. /// /// </summary> public ServerSideEncryptionMethod ServerSideEncryptionMethod { get { return this.serverSideEncryption; } set { this.serverSideEncryption = value; } } // Check to see if ServerSideEncryption property is set internal bool IsSetServerSideEncryptionMethod() { return this.serverSideEncryption != null && this.serverSideEncryption != ServerSideEncryptionMethod.None; } /// <summary> /// The Server-side encryption algorithm to be used with the customer provided key. /// /// </summary> public ServerSideEncryptionCustomerMethod ServerSideEncryptionCustomerMethod { get { return this.serverSideCustomerEncryption; } set { this.serverSideCustomerEncryption = value; } } // Check to see if ServerSideEncryptionCustomerMethod property is set internal bool IsSetServerSideEncryptionCustomerMethod() { return this.serverSideCustomerEncryption != null && this.serverSideCustomerEncryption != ServerSideEncryptionCustomerMethod.None; } /// <summary> /// The base64-encoded encryption key for Amazon S3 to use to encrypt the object /// <para> /// Using the encryption key you provide as part of your request Amazon S3 manages both the encryption, as it writes /// to disks, and decryption, when you access your objects. Therefore, you don't need to maintain any data encryption code. The only /// thing you do is manage the encryption keys you provide. /// </para> /// <para> /// When you retrieve an object, you must provide the same encryption key as part of your request. Amazon S3 first verifies /// the encryption key you provided matches, and then decrypts the object before returning the object data to you. /// </para> /// <para> /// Important: Amazon S3 does not store the encryption key you provide. /// </para> /// </summary> public string ServerSideEncryptionCustomerProvidedKey { get { return this.serverSideEncryptionCustomerProvidedKey; } set { this.serverSideEncryptionCustomerProvidedKey = value; } } /// <summary> /// Checks if ServerSideEncryptionCustomerProvidedKey property is set. /// </summary> /// <returns>true if ServerSideEncryptionCustomerProvidedKey property is set.</returns> internal bool IsSetServerSideEncryptionCustomerProvidedKey() { return !System.String.IsNullOrEmpty(this.serverSideEncryptionCustomerProvidedKey); } /// <summary> /// The MD5 of the customer encryption key specified in the ServerSideEncryptionCustomerProvidedKey property. The MD5 is /// base 64 encoded. This field is optional, the SDK will calculate the MD5 if this is not set. /// </summary> public string ServerSideEncryptionCustomerProvidedKeyMD5 { get { return this.serverSideEncryptionCustomerProvidedKeyMD5; } set { this.serverSideEncryptionCustomerProvidedKeyMD5 = value; } } /// <summary> /// Checks if ServerSideEncryptionCustomerProvidedKeyMD5 property is set. /// </summary> /// <returns>true if ServerSideEncryptionCustomerProvidedKey property is set.</returns> internal bool IsSetServerSideEncryptionCustomerProvidedKeyMD5() { return !System.String.IsNullOrEmpty(this.serverSideEncryptionCustomerProvidedKeyMD5); } /// <summary> /// The id of the AWS Key Management Service key that Amazon S3 should use to encrypt and decrypt the object. /// If a key id is not specified, the default key will be used for encryption and decryption. /// </summary> public string ServerSideEncryptionKeyManagementServiceKeyId { get { return this.serverSideEncryptionKeyManagementServiceKeyId; } set { this.serverSideEncryptionKeyManagementServiceKeyId = value; } } /// <summary> /// Checks if ServerSideEncryptionKeyManagementServiceKeyId property is set. /// </summary> /// <returns>true if ServerSideEncryptionKeyManagementServiceKeyId property is set.</returns> internal bool IsSetServerSideEncryptionKeyManagementServiceKeyId() { return !System.String.IsNullOrEmpty(this.serverSideEncryptionKeyManagementServiceKeyId); } /// <summary> /// The type of storage to use for the object. Defaults to 'STANDARD'. /// /// </summary> public S3StorageClass StorageClass { get { return this.storageClass; } set { this.storageClass = value; } } // Check to see if StorageClass property is set internal bool IsSetStorageClass() { return this.storageClass != null; } /// <summary> /// If the bucket is configured as a website, redirects requests for this object to another object in the same bucket or to an external URL. /// Amazon S3 stores the value of this header in the object metadata. /// /// </summary> public string WebsiteRedirectLocation { get { return this.websiteRedirectLocation; } set { this.websiteRedirectLocation = value; } } // Check to see if WebsiteRedirectLocation property is set internal bool IsSetWebsiteRedirectLocation() { return this.websiteRedirectLocation != null; } /// <summary> /// Attach a callback that will be called as data is being sent to the AWS Service. /// </summary> public EventHandler<Amazon.Runtime.StreamTransferProgressArgs> StreamTransferProgress { get { return this.StreamUploadProgressCallback; } set { this.StreamUploadProgressCallback = value; } } /// <summary> /// This is a convenience property for Headers.ContentType. /// </summary> public string ContentType { get { return this.Headers.ContentType; } set { this.Headers.ContentType = value; } } /// <summary> /// An MD5 digest for the content. /// </summary> /// <remarks> /// <para> /// The base64 encoded 128-bit MD5 digest of the message /// (without the headers) according to RFC 1864. This header /// can be used as a message integrity check to verify that /// the data is the same data that was originally sent. /// </para> /// <para> /// If supplied, after the file has been uploaded to S3, /// S3 checks to ensure that the MD5 hash of the uploaded file /// matches the hash supplied. /// </para> /// <para> /// Although it is optional, we recommend using the /// Content-MD5 mechanism as an end-to-end integrity check. /// </para> /// </remarks> public string MD5Digest { get { return this.md5Digest; } set { this.md5Digest = value; } } /// <summary> /// Checks if MD5Digest property is set. /// </summary> /// <returns>true if MD5Digest property is set.</returns> internal bool IsSetMD5Digest() { return !System.String.IsNullOrEmpty(this.md5Digest); } internal override bool IncludeSHA256Header { get { return false; } } internal override bool Expect100Continue { get { return true; } } } }
/* * 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 NUnit.Framework; using QuantConnect.Algorithm; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Orders; using QuantConnect.Orders.Fees; using QuantConnect.Securities; using QuantConnect.Securities.Option; using QuantConnect.Tests.Engine.DataFeeds; namespace QuantConnect.Tests.Common.Securities { // The tests have been verified using the CBOE Margin Calculator // http://www.cboe.com/trading-tools/calculators/margin-calculator [TestFixture] public class OptionMarginBuyingPowerModelTests { // Test class to enable calling protected methods [Test] public void OptionMarginBuyingPowerModelInitializationTests() { var tz = TimeZones.NewYork; var option = new Option( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig( typeof(TradeBar), Symbols.SPY_P_192_Feb19_2016, Resolution.Minute, tz, tz, true, false, false ), new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties("", Currencies.USD, 100, 0.01m, 1), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); var buyingPowerModel = new OptionMarginModel(); // we test that options dont have leverage (100%) and it cannot be changed Assert.AreEqual(1m, buyingPowerModel.GetLeverage(option)); Assert.Throws<InvalidOperationException>(() => buyingPowerModel.SetLeverage(option, 10m)); Assert.AreEqual(1m, buyingPowerModel.GetLeverage(option)); } [Test] public void TestLongCallsPuts() { const decimal price = 1.2345m; const decimal underlyingPrice = 200m; var tz = TimeZones.NewYork; var equity = new QuantConnect.Securities.Equity.Equity( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false), new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); equity.SetMarketPrice(new Tick { Value = underlyingPrice }); var optionPut = new Option( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig( typeof(TradeBar), Symbols.SPY_P_192_Feb19_2016, Resolution.Minute, tz, tz, true, false, false ), new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties("", Currencies.USD, 100, 0.01m, 1), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); optionPut.SetMarketPrice(new Tick { Value = price }); optionPut.Underlying = equity; optionPut.Holdings.SetHoldings(1m, 2); var optionCall = new Option( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig( typeof(TradeBar), Symbols.SPY_C_192_Feb19_2016, Resolution.Minute, tz, tz, true, false, false ), new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties("", Currencies.USD, 100, 0.01m, 1), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); optionCall.SetMarketPrice(new Tick { Value = price }); optionCall.Underlying = equity; optionCall.Holdings.SetHoldings(1.5m, 2); var buyingPowerModel = new OptionMarginModel(); // we expect long positions to be 100% charged. Assert.AreEqual(optionPut.Holdings.AbsoluteHoldingsCost, buyingPowerModel.GetMaintenanceMargin(optionPut)); Assert.AreEqual(optionCall.Holdings.AbsoluteHoldingsCost, buyingPowerModel.GetMaintenanceMargin(optionCall)); } [Test] public void TestShortCallsITM() { const decimal price = 14m; const decimal underlyingPrice = 196m; var tz = TimeZones.NewYork; var equity = new QuantConnect.Securities.Equity.Equity( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false), new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); equity.SetMarketPrice(new Tick { Value = underlyingPrice }); var optionCall = new Option( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig( typeof(TradeBar), Symbols.SPY_C_192_Feb19_2016, Resolution.Minute, tz, tz, true, false, false ), new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties("", Currencies.USD, 100, 0.01m, 1), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); optionCall.SetMarketPrice(new Tick { Value = price }); optionCall.Underlying = equity; optionCall.Holdings.SetHoldings(price, -2); var buyingPowerModel = new OptionMarginModel(); // short option positions are very expensive in terms of margin. // Margin = 2 * 100 * (14 + 0.2 * 196) = 10640 Assert.AreEqual(10640m, buyingPowerModel.GetMaintenanceMargin(optionCall)); } [Test] public void TestShortCallsOTM() { const decimal price = 14m; const decimal underlyingPrice = 180m; var tz = TimeZones.NewYork; var equity = new QuantConnect.Securities.Equity.Equity( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false), new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); equity.SetMarketPrice(new Tick { Value = underlyingPrice }); var optionCall = new Option( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig( typeof(TradeBar), Symbols.SPY_C_192_Feb19_2016, Resolution.Minute, tz, tz, true, false, false ), new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties("", Currencies.USD, 100, 0.01m, 1), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); optionCall.SetMarketPrice(new Tick { Value = price }); optionCall.Underlying = equity; optionCall.Holdings.SetHoldings(price, -2); var buyingPowerModel = new OptionMarginModel(); // short option positions are very expensive in terms of margin. // Margin = 2 * 100 * (14 + 0.2 * 180 - (192 - 180)) = 7600 Assert.AreEqual(7600, (double)buyingPowerModel.GetMaintenanceMargin(optionCall), 0.01); } [Test] public void TestShortPutsITM() { const decimal price = 14m; const decimal underlyingPrice = 182m; var tz = TimeZones.NewYork; var equity = new QuantConnect.Securities.Equity.Equity( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false), new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); equity.SetMarketPrice(new Tick { Value = underlyingPrice }); var optionPut = new Option( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig( typeof(TradeBar), Symbols.SPY_P_192_Feb19_2016, Resolution.Minute, tz, tz, true, false, false ), new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties("", Currencies.USD, 100, 0.01m, 1), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); optionPut.SetMarketPrice(new Tick { Value = price }); optionPut.Underlying = equity; optionPut.Holdings.SetHoldings(price, -2); var buyingPowerModel = new OptionMarginModel(); // short option positions are very expensive in terms of margin. // Margin = 2 * 100 * (14 + 0.2 * 182) = 10080 Assert.AreEqual(10080m, buyingPowerModel.GetMaintenanceMargin(optionPut)); } [Test] public void TestShortPutsOTM() { const decimal price = 14m; const decimal underlyingPrice = 196m; var tz = TimeZones.NewYork; var equity = new QuantConnect.Securities.Equity.Equity( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false), new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); equity.SetMarketPrice(new Tick { Value = underlyingPrice }); var optionCall = new Option( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig( typeof(TradeBar), Symbols.SPY_P_192_Feb19_2016, Resolution.Minute, tz, tz, true, false, false ), new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties("", Currencies.USD, 100, 0.01m, 1), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); optionCall.SetMarketPrice(new Tick { Value = price }); optionCall.Underlying = equity; optionCall.Holdings.SetHoldings(price, -2); var buyingPowerModel = new OptionMarginModel(); // short option positions are very expensive in terms of margin. // Margin = 2 * 100 * (14 + 0.2 * 196 - (196 - 192)) = 9840 Assert.AreEqual(9840, (double)buyingPowerModel.GetMaintenanceMargin(optionCall), 0.01); } [Test] public void TestShortPutFarITM() { const decimal price = 0.18m; const decimal underlyingPrice = 200m; var tz = TimeZones.NewYork; var equity = new QuantConnect.Securities.Equity.Equity( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false), new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); equity.SetMarketPrice(new Tick { Value = underlyingPrice }); var optionPutSymbol = Symbol.CreateOption(Symbols.SPY, Market.USA, OptionStyle.American, OptionRight.Put, 207m, new DateTime(2015, 02, 27)); var optionPut = new Option( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), optionPutSymbol, Resolution.Minute, tz, tz, true, false, false), new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties("", Currencies.USD, 100, 0.01m, 1), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); optionPut.SetMarketPrice(new Tick { Value = price }); optionPut.Underlying = equity; optionPut.Holdings.SetHoldings(price, -2); var buyingPowerModel = new OptionMarginModel(); // short option positions are very expensive in terms of margin. // Margin = 2 * 100 * (0.18 + 0.2 * 200) = 8036 Assert.AreEqual(8036, (double)buyingPowerModel.GetMaintenanceMargin(optionPut), 0.01); } [Test] public void TestShortPutMovingFarITM() { const decimal optionPriceStart = 4.68m; const decimal underlyingPriceStart = 192m; const decimal optionPriceEnd = 0.18m; const decimal underlyingPriceEnd = 200m; var tz = TimeZones.NewYork; var equity = new QuantConnect.Securities.Equity.Equity( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), Symbols.SPY, Resolution.Minute, tz, tz, true, false, false), new Cash(Currencies.USD, 0, 1m), SymbolProperties.GetDefault(Currencies.USD), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); equity.SetMarketPrice(new Tick { Value = underlyingPriceStart }); var optionPutSymbol = Symbol.CreateOption(Symbols.SPY, Market.USA, OptionStyle.American, OptionRight.Put, 207m, new DateTime(2015, 02, 27)); var optionPut = new Option( SecurityExchangeHours.AlwaysOpen(tz), new SubscriptionDataConfig(typeof(TradeBar), optionPutSymbol, Resolution.Minute, tz, tz, true, false, false), new Cash(Currencies.USD, 0, 1m), new OptionSymbolProperties("", Currencies.USD, 100, 0.01m, 1), ErrorCurrencyConverter.Instance, RegisteredSecurityDataTypesProvider.Null ); optionPut.SetMarketPrice(new Tick { Value = optionPriceStart }); optionPut.Underlying = equity; optionPut.Holdings.SetHoldings(optionPriceStart, -2); var buyingPowerModel = new OptionMarginModel(); // short option positions are very expensive in terms of margin. // Margin = 2 * 100 * (4.68 + 0.2 * 192) = 8616 Assert.AreEqual(8616, (double)buyingPowerModel.GetMaintenanceMargin(optionPut), 0.01); equity.SetMarketPrice(new Tick { Value = underlyingPriceEnd }); optionPut.SetMarketPrice(new Tick { Value = optionPriceEnd }); // short option positions are very expensive in terms of margin. // Margin = 2 * 100 * (4.68 + 0.2 * 200) = 8936 Assert.AreEqual(8936, (double)buyingPowerModel.GetMaintenanceMargin(optionPut), 0.01); } [TestCase(0)] [TestCase(10000)] public void NonAccountCurrency_GetBuyingPower(decimal nonAccountCurrencyCash) { var algorithm = new QCAlgorithm(); algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm)); algorithm.Portfolio.SetAccountCurrency("EUR"); algorithm.Portfolio.SetCash(10000); algorithm.Portfolio.SetCash(Currencies.USD, nonAccountCurrencyCash, 0.88m); var option = algorithm.AddOption("SPY"); var buyingPowerModel = new OptionMarginModel(); var quantity = buyingPowerModel.GetBuyingPower(new BuyingPowerParameters( algorithm.Portfolio, option, OrderDirection.Buy)); Assert.AreEqual(10000m + algorithm.Portfolio.CashBook[Currencies.USD].ValueInAccountCurrency, quantity.Value); } // This test set showcases some odd behaviour by our OptionMarginModel margin requirement calculation. // ~-1.5% Target (~-15K). If we are already shorted or long we reduce holdings to 0, this is because the requirement for a // short option position is at base ~-200K, but the issue is if we have zero holdings it allows us to buy -31 contracts for // 478 margin requirement per unit. This is because the margin requirement seems to be contingent upon the current holdings. [TestCase(-31, 31, -.015)] // Short to Short (-31 + 31 = 0) [TestCase(0, -31, -.015)] // Open Short (0 + -31 = -31) [TestCase(31, -31, -.015)] // Long To Short (31 + -31 = 0) // -40% Target (~-400k), All end up at different allocations. // This is because of the initial margin requirement calculations. [TestCase(-31, -380, -0.40)] // Short to Shorter (-31 + -380 = -411) [TestCase(0, -836, -0.40)] // Open Short (0 + -836 = -836) [TestCase(31, -467, -0.40)] // Long To Short (31 + -467 = -436) // 40% Target (~400k), All end up at different allocations. // This is because of the initial margin requirement calculations. [TestCase(-31, 855, 0.40)] // Short to Long (-31 + 855 = 824) [TestCase(0, 836, 0.40)] // Open Long (0 + 836 = 836) [TestCase(31, 818, 0.40)] // Long To Longer (31 + 818 = 849) // ~0.04% Target (~400). This is below the needed margin for one unit. We end up at 0 holdings for all cases. [TestCase(-31, 31, 0.0004)] // Short to Long (-31 + 31 = 0) [TestCase(0, 0, 0.0004)] // Open Long (0 + 0 = 0) [TestCase(31, -31, 0.0004)] // Long To Longer (31 + -31 = 0) public void CallOTM_MarginRequirement(int startingHoldings, int expectedOrderSize, decimal targetPercentage) { // Initialize algorithm var algorithm = new QCAlgorithm(); algorithm.SetFinishedWarmingUp(); algorithm.Transactions.SetOrderProcessor(new FakeOrderProcessor()); algorithm.SetCash(1000000); algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm)); var optionSymbol = Symbols.CreateOptionSymbol("SPY", OptionRight.Call, 411m, DateTime.UtcNow); var option = algorithm.AddOptionContract(optionSymbol); option.Holdings.SetHoldings(4.74m, startingHoldings); option.FeeModel = new ConstantFeeModel(0); option.SetLeverage(1); // Update option data UpdatePrice(option, 4.78m); // Update the underlying data UpdatePrice(option.Underlying, 395.51m); var model = new OptionMarginModel(); var result = model.GetMaximumOrderQuantityForTargetBuyingPower(algorithm.Portfolio, option, targetPercentage, 0); Assert.AreEqual(expectedOrderSize, result.Quantity); } private static void UpdatePrice(Security security, decimal close) { security.SetMarketPrice(new TradeBar { Time = DateTime.Now, Symbol = security.Symbol, Open = close, High = close, Low = close, Close = close }); } } }
using Android.App; using Android.Graphics; using Android.OS; using Android.Views; using Android.Widget; using Skobbler.Ngx; using Skobbler.Ngx.Map; using Skobbler.Ngx.Navigation; using Skobbler.Ngx.Routing; using System; namespace Skobbler.SDKDemo.Activities { public class MapCacheActivity : Activity, ISKMapSurfaceListener, ISKNavigationListener, ISKRouteListener { public static string TAG = "MapCacheActivity"; private SKMapSurfaceView _mapView; private SKMapViewHolder _mapViewGroup; private SKCoordinate _currentPosition = new SKCoordinate(23.593823f, 46.773716f); private SKCoordinate _routeDestinationPoint = new SKCoordinate(23.596824f, 46.770088f); protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); SetContentView(Resource.Layout.activity_map_cache); _mapViewGroup = FindViewById<SKMapViewHolder>(Resource.Id.view_group_map); _mapViewGroup.SetMapSurfaceListener(this); } protected override void OnResume() { base.OnResume(); _mapViewGroup.OnResume(); } protected override void OnPause() { base.OnPause(); _mapViewGroup.OnPause(); } protected override void OnDestroy() { base.OnDestroy(); _mapViewGroup = null; } public void OnSurfaceCreated(SKMapViewHolder skMapViewHolder) { _mapView = skMapViewHolder.MapSurfaceView; FindViewById<RelativeLayout>(Resource.Id.chess_board_background).Visibility = ViewStates.Gone; _mapView = _mapViewGroup.MapSurfaceView; _mapView.SetPositionAsCurrent(_currentPosition, 0, true); _mapView.SetZoom(17.0F); SKNavigationManager.Instance.SetNavigationListener(this); AddStartDestinationPins(); LaunchRouteCalculation(_currentPosition, _routeDestinationPoint); } private void AddStartDestinationPins() { SKAnnotation annotation1 = new SKAnnotation(10) { Location = _routeDestinationPoint, MininumZoomLevel = 5, AnnotationType = SKAnnotation.SkAnnotationTypeRed }; _mapView.AddAnnotation(annotation1, SKAnimationSettings.AnimationNone); SKAnnotation annotation2 = new SKAnnotation(11) { Location = _currentPosition, MininumZoomLevel = 5, AnnotationType = SKAnnotation.SkAnnotationTypeGreen }; _mapView.AddAnnotation(annotation2, SKAnimationSettings.AnimationNone); } private void LaunchRouteCalculation(SKCoordinate startPoint, SKCoordinate destinationPoint) { SKRouteSettings route = new SKRouteSettings { StartCoordinate = startPoint, DestinationCoordinate = destinationPoint, MaximumReturnedRoutes = 1, RouteMode = SKRouteSettings.SKRouteMode.CarFastest, RouteExposed = true }; SKRouteManager.Instance.SetRouteListener(this); SKRouteManager.Instance.CalculateRoute(route); } #region Empty callback methods public void OnActionPan() { } public void OnActionZoom() { } public void OnMapRegionChanged(SKCoordinateRegion region) { } public void OnDoubleTap(SKScreenPoint point) { } public void OnSingleTap(SKScreenPoint point) { } public void OnRotateMap() { } public void OnLongPress(SKScreenPoint point) { } public void OnInternetConnectionNeeded() { } public void OnMapActionDown(SKScreenPoint point) { } public void OnMapActionUp(SKScreenPoint point) { } public void OnMapPOISelected(SKMapPOI mapPOI) { } public void OnAnnotationSelected(SKAnnotation annotation) { } public void OnCompassSelected() { } public void OnInternationalisationCalled(int result) { } public void OnCustomPOISelected(SKMapCustomPOI customPoi) { } public void OnDestinationReached() { } public void OnUpdateNavigationState(SKNavigationState navigationState) { } public void OnReRoutingStarted() { } public void OnFreeDriveUpdated(string countryCode, string streetName, SKNavigationState.SKStreetType streetType, double currentSpeed, double speedLimit) { } public void OnViaPointReached(int index) { } public void OnVisualAdviceChanged(bool firstVisualAdviceChanged, bool secondVisualAdviceChanged, SKNavigationState navigationState) { } public void OnPOIClusterSelected(SKPOICluster arg0) { } public void OnTunnelEvent(bool arg0) { } public void OnMapRegionChangeEnded(SKCoordinateRegion arg0) { } public void OnMapRegionChangeStarted(SKCoordinateRegion arg0) { } public void OnCurrentPositionSelected() { } public void OnObjectSelected(int arg0) { } public void OnSignalNewAdviceWithAudioFiles(string[] arg0, bool arg1) { } public void OnSignalNewAdviceWithInstruction(string arg0) { } public void OnSpeedExceededWithAudioFiles(string[] arg0, bool arg1) { } public void OnSpeedExceededWithInstruction(string arg0, bool arg1) { } public void OnBoundingBoxImageRendered(int arg0) { } public void OnGLInitializationError(string arg0) { } public void OnRouteCalculationCompleted(SKRouteInfo skRouteInfo) { } public void OnRouteCalculationFailed(SKRouteListenerSKRoutingErrorCode skRoutingErrorCode) { } public void OnAllRoutesCompleted() { } public void OnServerLikeRouteCalculationCompleted(SKRouteJsonAnswer skRouteJsonAnswer) { } public void OnOnlineRouteComputationHanging(int i) { } #endregion public void OnScreenshotReady(Bitmap screenshot) { } public void OnFreeDriveUpdated(string p0, string p1, string p2, SKNavigationState.SKStreetType p3, double p4, double p5) { } } }
// 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 gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V8.Services { /// <summary>Settings for <see cref="FeedItemTargetServiceClient"/> instances.</summary> public sealed partial class FeedItemTargetServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="FeedItemTargetServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="FeedItemTargetServiceSettings"/>.</returns> public static FeedItemTargetServiceSettings GetDefault() => new FeedItemTargetServiceSettings(); /// <summary> /// Constructs a new <see cref="FeedItemTargetServiceSettings"/> object with default settings. /// </summary> public FeedItemTargetServiceSettings() { } private FeedItemTargetServiceSettings(FeedItemTargetServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetFeedItemTargetSettings = existing.GetFeedItemTargetSettings; MutateFeedItemTargetsSettings = existing.MutateFeedItemTargetsSettings; OnCopy(existing); } partial void OnCopy(FeedItemTargetServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>FeedItemTargetServiceClient.GetFeedItemTarget</c> and /// <c>FeedItemTargetServiceClient.GetFeedItemTargetAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetFeedItemTargetSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>FeedItemTargetServiceClient.MutateFeedItemTargets</c> and /// <c>FeedItemTargetServiceClient.MutateFeedItemTargetsAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings MutateFeedItemTargetsSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="FeedItemTargetServiceSettings"/> object.</returns> public FeedItemTargetServiceSettings Clone() => new FeedItemTargetServiceSettings(this); } /// <summary> /// Builder class for <see cref="FeedItemTargetServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class FeedItemTargetServiceClientBuilder : gaxgrpc::ClientBuilderBase<FeedItemTargetServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public FeedItemTargetServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public FeedItemTargetServiceClientBuilder() { UseJwtAccessWithScopes = FeedItemTargetServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref FeedItemTargetServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<FeedItemTargetServiceClient> task); /// <summary>Builds the resulting client.</summary> public override FeedItemTargetServiceClient Build() { FeedItemTargetServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<FeedItemTargetServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<FeedItemTargetServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private FeedItemTargetServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return FeedItemTargetServiceClient.Create(callInvoker, Settings); } private async stt::Task<FeedItemTargetServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return FeedItemTargetServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => FeedItemTargetServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => FeedItemTargetServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => FeedItemTargetServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>FeedItemTargetService client wrapper, for convenient use.</summary> /// <remarks> /// Service to manage feed item targets. /// </remarks> public abstract partial class FeedItemTargetServiceClient { /// <summary> /// The default endpoint for the FeedItemTargetService service, which is a host of "googleads.googleapis.com" /// and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default FeedItemTargetService scopes.</summary> /// <remarks> /// The default FeedItemTargetService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="FeedItemTargetServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="FeedItemTargetServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="FeedItemTargetServiceClient"/>.</returns> public static stt::Task<FeedItemTargetServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new FeedItemTargetServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="FeedItemTargetServiceClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="FeedItemTargetServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="FeedItemTargetServiceClient"/>.</returns> public static FeedItemTargetServiceClient Create() => new FeedItemTargetServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="FeedItemTargetServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="FeedItemTargetServiceSettings"/>.</param> /// <returns>The created <see cref="FeedItemTargetServiceClient"/>.</returns> internal static FeedItemTargetServiceClient Create(grpccore::CallInvoker callInvoker, FeedItemTargetServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } FeedItemTargetService.FeedItemTargetServiceClient grpcClient = new FeedItemTargetService.FeedItemTargetServiceClient(callInvoker); return new FeedItemTargetServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC FeedItemTargetService client</summary> public virtual FeedItemTargetService.FeedItemTargetServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::FeedItemTarget GetFeedItemTarget(GetFeedItemTargetRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItemTarget> GetFeedItemTargetAsync(GetFeedItemTargetRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItemTarget> GetFeedItemTargetAsync(GetFeedItemTargetRequest request, st::CancellationToken cancellationToken) => GetFeedItemTargetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item targets to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::FeedItemTarget GetFeedItemTarget(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedItemTarget(new GetFeedItemTargetRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item targets to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItemTarget> GetFeedItemTargetAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedItemTargetAsync(new GetFeedItemTargetRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item targets to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItemTarget> GetFeedItemTargetAsync(string resourceName, st::CancellationToken cancellationToken) => GetFeedItemTargetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item targets to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::FeedItemTarget GetFeedItemTarget(gagvr::FeedItemTargetName resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedItemTarget(new GetFeedItemTargetRequest { ResourceNameAsFeedItemTargetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item targets to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItemTarget> GetFeedItemTargetAsync(gagvr::FeedItemTargetName resourceName, gaxgrpc::CallSettings callSettings = null) => GetFeedItemTargetAsync(new GetFeedItemTargetRequest { ResourceNameAsFeedItemTargetName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="resourceName"> /// Required. The resource name of the feed item targets to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::FeedItemTarget> GetFeedItemTargetAsync(gagvr::FeedItemTargetName resourceName, st::CancellationToken cancellationToken) => GetFeedItemTargetAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateFeedItemTargetsResponse MutateFeedItemTargets(MutateFeedItemTargetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedItemTargetsResponse> MutateFeedItemTargetsAsync(MutateFeedItemTargetsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedItemTargetsResponse> MutateFeedItemTargetsAsync(MutateFeedItemTargetsRequest request, st::CancellationToken cancellationToken) => MutateFeedItemTargetsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose feed item targets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual feed item targets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual MutateFeedItemTargetsResponse MutateFeedItemTargets(string customerId, scg::IEnumerable<FeedItemTargetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateFeedItemTargets(new MutateFeedItemTargetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose feed item targets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual feed item targets. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedItemTargetsResponse> MutateFeedItemTargetsAsync(string customerId, scg::IEnumerable<FeedItemTargetOperation> operations, gaxgrpc::CallSettings callSettings = null) => MutateFeedItemTargetsAsync(new MutateFeedItemTargetsRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), Operations = { gax::GaxPreconditions.CheckNotNull(operations, nameof(operations)), }, }, callSettings); /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer whose feed item targets are being modified. /// </param> /// <param name="operations"> /// Required. The list of operations to perform on individual feed item targets. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<MutateFeedItemTargetsResponse> MutateFeedItemTargetsAsync(string customerId, scg::IEnumerable<FeedItemTargetOperation> operations, st::CancellationToken cancellationToken) => MutateFeedItemTargetsAsync(customerId, operations, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>FeedItemTargetService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to manage feed item targets. /// </remarks> public sealed partial class FeedItemTargetServiceClientImpl : FeedItemTargetServiceClient { private readonly gaxgrpc::ApiCall<GetFeedItemTargetRequest, gagvr::FeedItemTarget> _callGetFeedItemTarget; private readonly gaxgrpc::ApiCall<MutateFeedItemTargetsRequest, MutateFeedItemTargetsResponse> _callMutateFeedItemTargets; /// <summary> /// Constructs a client wrapper for the FeedItemTargetService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="FeedItemTargetServiceSettings"/> used within this client.</param> public FeedItemTargetServiceClientImpl(FeedItemTargetService.FeedItemTargetServiceClient grpcClient, FeedItemTargetServiceSettings settings) { GrpcClient = grpcClient; FeedItemTargetServiceSettings effectiveSettings = settings ?? FeedItemTargetServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetFeedItemTarget = clientHelper.BuildApiCall<GetFeedItemTargetRequest, gagvr::FeedItemTarget>(grpcClient.GetFeedItemTargetAsync, grpcClient.GetFeedItemTarget, effectiveSettings.GetFeedItemTargetSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetFeedItemTarget); Modify_GetFeedItemTargetApiCall(ref _callGetFeedItemTarget); _callMutateFeedItemTargets = clientHelper.BuildApiCall<MutateFeedItemTargetsRequest, MutateFeedItemTargetsResponse>(grpcClient.MutateFeedItemTargetsAsync, grpcClient.MutateFeedItemTargets, effectiveSettings.MutateFeedItemTargetsSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callMutateFeedItemTargets); Modify_MutateFeedItemTargetsApiCall(ref _callMutateFeedItemTargets); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetFeedItemTargetApiCall(ref gaxgrpc::ApiCall<GetFeedItemTargetRequest, gagvr::FeedItemTarget> call); partial void Modify_MutateFeedItemTargetsApiCall(ref gaxgrpc::ApiCall<MutateFeedItemTargetsRequest, MutateFeedItemTargetsResponse> call); partial void OnConstruction(FeedItemTargetService.FeedItemTargetServiceClient grpcClient, FeedItemTargetServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC FeedItemTargetService client</summary> public override FeedItemTargetService.FeedItemTargetServiceClient GrpcClient { get; } partial void Modify_GetFeedItemTargetRequest(ref GetFeedItemTargetRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_MutateFeedItemTargetsRequest(ref MutateFeedItemTargetsRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::FeedItemTarget GetFeedItemTarget(GetFeedItemTargetRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetFeedItemTargetRequest(ref request, ref callSettings); return _callGetFeedItemTarget.Sync(request, callSettings); } /// <summary> /// Returns the requested feed item targets in full detail. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::FeedItemTarget> GetFeedItemTargetAsync(GetFeedItemTargetRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetFeedItemTargetRequest(ref request, ref callSettings); return _callGetFeedItemTarget.Async(request, callSettings); } /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override MutateFeedItemTargetsResponse MutateFeedItemTargets(MutateFeedItemTargetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateFeedItemTargetsRequest(ref request, ref callSettings); return _callMutateFeedItemTargets.Sync(request, callSettings); } /// <summary> /// Creates or removes feed item targets. Operation statuses are returned. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [CriterionError]() /// [DatabaseError]() /// [DistinctError]() /// [FeedItemTargetError]() /// [FieldError]() /// [HeaderError]() /// [IdError]() /// [InternalError]() /// [MutateError]() /// [NotEmptyError]() /// [OperatorError]() /// [QuotaError]() /// [RangeError]() /// [RequestError]() /// [SizeLimitError]() /// [StringFormatError]() /// [StringLengthError]() /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<MutateFeedItemTargetsResponse> MutateFeedItemTargetsAsync(MutateFeedItemTargetsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_MutateFeedItemTargetsRequest(ref request, ref callSettings); return _callMutateFeedItemTargets.Async(request, callSettings); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using NDesk.Options; using Sep.Git.Tfs.Core; using Sep.Git.Tfs.Util; using StructureMap; namespace Sep.Git.Tfs.Commands { [Pluggable("rcheckin")] [RequiresValidGitRepository] public class Rcheckin : GitTfsCommand { private readonly TextWriter _stdout; private readonly CheckinOptions _checkinOptions; private readonly CommitSpecificCheckinOptionsFactory _checkinOptionsFactory; private readonly TfsWriter _writer; private readonly Globals _globals; private readonly AuthorsFile _authors; private bool AutoRebase { get; set; } private bool ForceCheckin { get; set; } public Rcheckin(TextWriter stdout, CheckinOptions checkinOptions, TfsWriter writer, Globals globals, AuthorsFile authors) { _stdout = stdout; _checkinOptions = checkinOptions; _checkinOptionsFactory = new CommitSpecificCheckinOptionsFactory(_stdout, globals, authors); _writer = writer; _globals = globals; _authors = authors; } public OptionSet OptionSet { get { return new OptionSet { {"a|autorebase", "Continue and rebase if new TFS changesets found", v => AutoRebase = v != null}, {"ignore-merge", "Force check in ignoring parent tfs branches in merge commits", v => ForceCheckin = v != null}, }.Merge(_checkinOptions.OptionSet); } } // uses rebase and works only with HEAD public int Run() { _globals.WarnOnGitVersion(_stdout); if (_globals.Repository.IsBare) throw new GitTfsException("error: you should specify the local branch to checkin for a bare repository."); return _writer.Write("HEAD", PerformRCheckin); } // uses rebase and works only with HEAD in a none bare repository public int Run(string localBranch) { _globals.WarnOnGitVersion(_stdout); if (!_globals.Repository.IsBare) throw new GitTfsException("error: This syntax with one parameter is only allowed in bare repository."); _authors.Parse(null, _globals.GitDir); return _writer.Write(GitRepository.ShortToLocalName(localBranch), PerformRCheckin); } private int PerformRCheckin(TfsChangesetInfo parentChangeset, string refToCheckin) { if (_globals.Repository.IsBare) AutoRebase = false; if (_globals.Repository.WorkingCopyHasUnstagedOrUncommitedChanges) { throw new GitTfsException("error: You have local changes; rebase-workflow checkin only possible with clean working directory.") .WithRecommendation("Try 'git stash' to stash your local changes and checkin again."); } // get latest changes from TFS to minimize possibility of late conflict _stdout.WriteLine("Fetching changes from TFS to minimize possibility of late conflict..."); parentChangeset.Remote.Fetch(); if (parentChangeset.ChangesetId != parentChangeset.Remote.MaxChangesetId) { if (AutoRebase) { _globals.Repository.CommandNoisy("rebase", "--preserve-merges", parentChangeset.Remote.RemoteRef); parentChangeset = _globals.Repository.GetTfsCommit(parentChangeset.Remote.MaxCommitHash); } else { if (_globals.Repository.IsBare) _globals.Repository.UpdateRef(refToCheckin, parentChangeset.Remote.MaxCommitHash); throw new GitTfsException("error: New TFS changesets were found.") .WithRecommendation("Try to rebase HEAD onto latest TFS checkin and repeat rcheckin or alternatively checkins"); } } IEnumerable<GitCommit> commitsToCheckin = _globals.Repository.FindParentCommits(refToCheckin, parentChangeset.Remote.MaxCommitHash); Trace.WriteLine("Commit to checkin count:" + commitsToCheckin.Count()); if (!commitsToCheckin.Any()) throw new GitTfsException("error: latest TFS commit should be parent of commits being checked in"); SetupMetadataExport(parentChangeset.Remote); return _PerformRCheckinQuick(parentChangeset, refToCheckin, commitsToCheckin); } private void SetupMetadataExport(IGitTfsRemote remote) { var exportInitializer = new ExportMetadatasInitializer(_globals); var shouldExport = _globals.Repository.GetConfig(GitTfsConstants.ExportMetadatasConfigKey) == "true"; exportInitializer.InitializeRemote(remote, shouldExport); } private int _PerformRCheckinQuick(TfsChangesetInfo parentChangeset, string refToCheckin, IEnumerable<GitCommit> commitsToCheckin) { var tfsRemote = parentChangeset.Remote; string currentParent = parentChangeset.Remote.MaxCommitHash; long newChangesetId = 0; foreach (var commit in commitsToCheckin) { var message = BuildCommitMessage(commit, !_checkinOptions.NoGenerateCheckinComment, currentParent); string target = commit.Sha; var parents = commit.Parents.Where(c => c.Sha != currentParent).ToArray(); string tfsRepositoryPathOfMergedBranch = FindTfsRepositoryPathOfMergedBranch(tfsRemote, parents, target); var commitSpecificCheckinOptions = _checkinOptionsFactory.BuildCommitSpecificCheckinOptions(_checkinOptions, message, commit); _stdout.WriteLine("Starting checkin of {0} '{1}'", target.Substring(0, 8), commitSpecificCheckinOptions.CheckinComment); try { newChangesetId = tfsRemote.Checkin(target, currentParent, parentChangeset, commitSpecificCheckinOptions, tfsRepositoryPathOfMergedBranch); var fetchResult = tfsRemote.FetchWithMerge(newChangesetId, false, parents.Select(c=>c.Sha).ToArray()); if (fetchResult.NewChangesetCount != 1) { var lastCommit = _globals.Repository.FindCommitHashByChangesetId(newChangesetId); RebaseOnto(lastCommit, target); if (AutoRebase) tfsRemote.Repository.CommandNoisy("rebase", "--preserve-merges", tfsRemote.RemoteRef); else throw new GitTfsException("error: New TFS changesets were found. Rcheckin was not finished."); } currentParent = target; parentChangeset = new TfsChangesetInfo {ChangesetId = newChangesetId, GitCommit = tfsRemote.MaxCommitHash, Remote = tfsRemote}; _stdout.WriteLine("Done with {0}.", target); } catch (Exception) { if (newChangesetId != 0) { var lastCommit = _globals.Repository.FindCommitHashByChangesetId(newChangesetId); RebaseOnto(lastCommit, currentParent); } throw; } } if (_globals.Repository.IsBare) _globals.Repository.UpdateRef(refToCheckin, tfsRemote.MaxCommitHash); else _globals.Repository.ResetHard(tfsRemote.MaxCommitHash); _stdout.WriteLine("No more to rcheckin."); Trace.WriteLine("Cleaning..."); tfsRemote.CleanupWorkspaceDirectory(); return GitTfsExitCodes.OK; } public string BuildCommitMessage(GitCommit commit, bool generateCheckinComment, string latest) { return generateCheckinComment ? _globals.Repository.GetCommitMessage(commit.Sha, latest) : _globals.Repository.GetCommit(commit.Sha).Message; } private string FindTfsRepositoryPathOfMergedBranch(IGitTfsRemote remoteToCheckin, GitCommit[] gitParents, string target) { if (gitParents.Length != 0) { _stdout.WriteLine("Working on the merge commit: " + target); if (gitParents.Length > 1) _stdout.WriteLine("warning: only 1 parent is supported by TFS for a merge changeset. The other parents won't be materialized in the TFS merge!"); foreach (var gitParent in gitParents) { var tfsCommit = _globals.Repository.GetTfsCommit(gitParent); if (tfsCommit != null) return tfsCommit.Remote.TfsRepositoryPath; var lastCheckinCommit = _globals.Repository.GetLastParentTfsCommits(gitParent.Sha).FirstOrDefault(); if (lastCheckinCommit != null) { if(!ForceCheckin && lastCheckinCommit.Remote.Id != remoteToCheckin.Id) throw new GitTfsException("error: the merged branch '" + lastCheckinCommit.Remote.Id + "' is a TFS tracked branch ("+lastCheckinCommit.Remote.TfsRepositoryPath + ") with some commits not checked in.\nIn this case, the local merge won't be materialized as a merge in tfs...") .WithRecommendation("check in all the commits of the tfs merged branch in TFS before trying to check in a merge commit", "use --ignore-merge option to ignore merged TFS branch and check in commit as a normal changeset (not a merge)."); } else { _stdout.WriteLine("warning: the parent " + gitParent + " does not belong to a TFS tracked branch (not checked in TFS) and will be ignored!"); } } } return null; } public void RebaseOnto(string newBaseCommit, string oldBaseCommit) { _globals.Repository.CommandNoisy("rebase", "--preserve-merges", "--onto", newBaseCommit, oldBaseCommit); } } }
// Copyright 2020 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 // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace YetiCommon.Util { /// <summary> /// Utility class to visualize an object graph in DOT graph format. /// /// Based on Jackson Dunstan, https://JacksonDunstan.com/articles/5034 /// </summary> /// /// <license> /// MIT /// </license> public class ObjectGraphVisualizer { /// <summary> /// Callback used to determine preemptive stopping conditions when traversing the object /// graph. /// </summary> /// /// <param name="ctx">The current traversal context.</param> /// /// <returns>True if graph traversal should continue.</returns> public delegate bool InspectObjectDelegate(InspectObjectContext ctx); /// <summary> /// Context used by InspectObject delegate. /// </summary> public class InspectObjectContext { public InspectObjectContext(object obj) { Object = obj; } /// <summary> /// The current object being inspected. /// </summary> public readonly object Object; } /// <summary> /// Analyzed graph data output from Visualize(). /// </summary> public interface IData { object RootObject { get; } List<object> AllNodes { get; } List<object> InternalNodes { get; } List<object> TruncatedNodes { get; } List<object> LeafNodes { get; } /// <summary> /// Returns the number of objects that have a reference to a given object. /// </summary> int GetInLinkCount(object obj); int GetOutLinkCount(object obj); /// <summary> /// Get a dictionary that maps all the types found in the graph all the object instances /// that are of that type, or some derivative of it. /// </summary> Dictionary<Type, List<object>> GetMultiInstances(); /// <summary> /// Get the list of objects that are of a given type or derive from it. /// </summary> List<object> GetInstances(Type type); } class DataImpl : IData { object rootObject = null; List<object> internalNodes = new List<object>(); List<object> truncatedNodes = new List<object>(); List<object> leafNodes = new List<object>(); public DataImpl(object rootObject) { DataNodes = new Dictionary<object, Node>(1024); this.rootObject = rootObject; } #region IData public Dictionary<object, Node> DataNodes; public object RootObject => rootObject; public List<object> AllNodes => DataNodes.Keys.ToList(); public List<object> InternalNodes => internalNodes; public List<object> TruncatedNodes => truncatedNodes; public List<object> LeafNodes => leafNodes; public int GetInLinkCount(object obj) { Node node; if (!DataNodes.TryGetValue(obj, out node)) { throw new ArgumentException($"{nameof(obj)} does not exist in the graph."); } return node.InLinks.Count(); } public int GetOutLinkCount(object obj) { Node node; if (!DataNodes.TryGetValue(obj, out node)) { throw new ArgumentException($"{nameof(obj)} does not exist in the graph."); } return node.OutLinks.Count(); } public Dictionary<Type, List<object>> GetMultiInstances() { var multiInstances = new Dictionary<Type, List<object>>(); var distinctTypes = DataNodes.Keys.Select(o => o.GetType()) .Where(t => t != typeof(object)).Distinct(); foreach (var type in distinctTypes) { var instances = GetInstances(type); if (instances.Count > 1) { multiInstances[type] = instances; } } return multiInstances; } public List<object> GetInstances(Type type) { return AllNodes.FindAll(o => type.IsAssignableFrom(o.GetType())).ToList(); } #endregion } /// <summary> /// Defines the traversal stopping conditions. /// </summary> private readonly InspectObjectDelegate inspectObj; /// <summary> /// Constructs a new object graph visualizer that will traverse the entire object graph. /// </summary> public ObjectGraphVisualizer() : this(null) { } /// <summary> /// Constructs a new object graph visualizer. /// </summary> /// /// <param name="inspectObj"> /// Callback used to determine when to stop traversing the object graph. The entire graph /// will be traversed when null. /// </param> public ObjectGraphVisualizer(InspectObjectDelegate inspectObj) { if (inspectObj == null) { inspectObj = o => { return true; }; } this.inspectObj = inspectObj; } /// <summary> /// A node of the graph /// </summary> private sealed class Node { /// <summary> /// The object the node represents /// </summary> public readonly object Object; /// <summary> /// Links from other nodes to the node. Keys are field names. Values are node IDs. /// </summary> public readonly Dictionary<string, int> InLinks; /// <summary> /// Links from the node to other nodes. Keys are field names. Values are node IDs. /// </summary> public readonly Dictionary<string, int> OutLinks; /// <summary> /// ID of the node. Unique to its graph. /// </summary> public readonly int Id; /// <summary> /// True if this node is root of the graph. /// </summary> public readonly bool IsRoot; /// <summary> /// True if the graph traversal stopped on this node based on the |inpsectObj| callback. /// </summary> public bool WasTruncated = false; /// <summary> /// Create a node /// </summary> /// /// <param name="obj"> /// The object the node represents. /// </param> /// /// <param name="id"> /// ID of the node. Must be unique to its graph. /// </param> public Node(object obj, int id, bool isRoot = false) { Object = obj; InLinks = new Dictionary<string, int>(16); OutLinks = new Dictionary<string, int>(16); Id = id; IsRoot = isRoot; } } /// <summary> /// Add a node to a graph to represent an object /// </summary> /// /// <returns> /// The added node or the existing node if one already exists for the object /// </returns> /// /// <param name="nodes"> /// Graph to add to /// </param> /// /// <param name="obj"> /// Object to add a node for /// </param> /// /// <param name="tempBuilder"> /// String builder to use only temporarily /// </param> /// /// <param name="nextNodeId"> /// ID to assign to the next node. Incremented after assignment. /// </param> /// /// <param name="isRoot"> /// True when the node represents the object graphs root. /// </param> private Node AddObject( Dictionary<object, Node> nodes, object obj, StringBuilder tempBuilder, ref int nextNodeId, bool isRoot = false) { // Check if there is already a node for the object Node node; if (nodes.TryGetValue(obj, out node)) { return node; } // Add a node for the object Type objType = obj.GetType(); node = new Node(obj, nextNodeId, isRoot); nextNodeId++; nodes.Add(obj, node); if (!inspectObj(new InspectObjectContext(obj))) { node.WasTruncated = true; return node; } // Add linked nodes for all fields foreach (FieldInfo fieldInfo in EnumerateInstanceFieldInfos(objType)) { // Only add reference types Type fieldType = fieldInfo.FieldType; if (!fieldType.IsPointer && !IsUnmanagedType(fieldType)) { object field = fieldInfo.GetValue(obj); if (fieldType.IsArray) { LinkArray( nodes, node, (Array)field, fieldInfo.Name, tempBuilder, ref nextNodeId); } else { LinkNode( nodes, node, field, fieldInfo.Name, tempBuilder, ref nextNodeId); } } } return node; } /// <summary> /// Add new linked nodes for the elements of an array /// </summary> /// /// <param name="nodes"> /// Graph to add to /// </param> /// /// <param name="node"> /// Node to link from /// </param> /// /// <param name="array"> /// Array whose elements should be linked /// </param> /// /// <param name="arrayName"> /// Name of the array field /// </param> /// /// <param name="tempBuilder"> /// String builder to use only temporarily /// </param> /// /// <param name="nextNodeId"> /// ID to assign to the next node. Incremented after assignment. /// </param> private void LinkArray( Dictionary<object, Node> nodes, Node node, Array array, string arrayName, StringBuilder tempBuilder, ref int nextNodeId) { // Don't link null arrays if (ReferenceEquals(array, null)) { return; } // Create an array of lengths of each rank int rank = array.Rank; int[] lengths = new int[rank]; for (int i = 0; i < lengths.Length; ++i) { lengths[i] = array.GetLength(i); } // Create an array of indices into each rank int[] indices = new int[rank]; indices[rank - 1] = -1; // Iterate over all elements of all ranks while (true) { // Increment the indices for (int i = rank - 1; i >= 0; --i) { indices[i]++; // No overflow, so we can link if (indices[i] < lengths[i]) { goto link; } // Overflow, so carry. indices[i] = 0; } break; link: // Build the field name: "name[1, 2, 3]" tempBuilder.Length = 0; tempBuilder.Append(arrayName); tempBuilder.Append('['); for (int i = 0; i < indices.Length; ++i) { tempBuilder.Append(indices[i]); if (i != indices.Length - 1) { tempBuilder.Append(", "); } } tempBuilder.Append(']'); // Link the element as a node object element = array.GetValue(indices); string elementName = tempBuilder.ToString(); LinkNode( nodes, node, element, elementName, tempBuilder, ref nextNodeId); } } /// <summary> /// Add a new linked node /// </summary> /// /// <param name="nodes"> /// Graph to add to /// </param> /// /// <param name="node"> /// Node to link from /// </param> /// /// <param name="obj"> /// Object to link a node for /// </param> /// /// <param name="name"> /// Name of the object /// </param> /// /// <param name="tempBuilder"> /// String builder to use only temporarily /// </param> /// /// <param name="nextNodeId"> /// ID to assign to the next node. Incremented after assignment. /// </param> private void LinkNode( Dictionary<object, Node> nodes, Node node, object obj, string name, StringBuilder tempBuilder, ref int nextNodeId) { // Don't link null objects if (ReferenceEquals(obj, null)) { return; } // Add a node for the object Node linkedNode = AddObject(nodes, obj, tempBuilder, ref nextNodeId); node.OutLinks[name] = linkedNode.Id; linkedNode.InLinks[name] = node.Id; } /// <summary> /// Check if a type is unmanaged, i.e. isn't and contains no managed types at any level of /// nesting. /// </summary> /// /// <returns> /// Whether the given type is unmanaged or not /// </returns> /// /// <param name="type"> /// Type to check /// </param> private bool IsUnmanagedType(Type type) { if (!type.IsValueType) { return false; } if (type.IsPrimitive || type.IsEnum) { return true; } foreach (FieldInfo field in EnumerateInstanceFieldInfos(type)) { if (!IsUnmanagedType(field.FieldType)) { return false; } } return true; } /// <summary> /// Enumerate the instance fields of a type and all its base types /// </summary> /// /// <returns> /// The fields of the given type and all its base types /// </returns> /// /// <param name="type"> /// Type to enumerate /// </param> private IEnumerable<FieldInfo> EnumerateInstanceFieldInfos(Type type) { const BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; while (type != null) { foreach (FieldInfo fieldInfo in type.GetFields(bindingFlags)) { yield return fieldInfo; } type = type.BaseType; } } /// <summary> /// Visualize the given object by generating DOT which can be rendered with GraphViz. /// </summary> /// /// <example> /// /// // 1) Generate a DOT file for an object /// File.WriteAllText("object.dot", new ObjectGraphVisualizer().Visualize(obj)); /// /// // 2) Render a graph for the using (internal). /// /// <returns> /// DOT, which can be rendered with GraphViz /// </returns> /// /// <param name="obj"> /// Object to visualize /// </param> /// /// <param name="data"> /// Analyzed graph data. /// </param> public string Visualize(object obj, out IData data) { // Build the graph DataImpl dataImpl = new DataImpl(obj); data = dataImpl; int nextNodeId = 1; StringBuilder tempBuilder = new StringBuilder(64); AddObject(dataImpl.DataNodes, obj, tempBuilder, ref nextNodeId, true); return CreateDOT(dataImpl.DataNodes, dataImpl); } /// <summary> /// Generates DOT graph serialization for a graph. /// </summary> /// <param name="nodes">The node graph.</param> /// <param name="data">Output data to populate</param> /// <returns>DOT graph string.</returns> private string CreateDOT(Dictionary<object, Node> nodes, DataImpl data) { StringBuilder output = new StringBuilder(1024 * 64); // Write the header output.Append("digraph\n"); output.Append("{\n"); output.Append(" graph [splines=ortho]\n"); output.Append(" node [shape=box style=rounded]\n"); // Write the mappings from ID to label foreach (Node node in nodes.Values) { output.Append(" "); output.Append(node.Id); output.Append(" [ label=\""); output.Append($"{node.Object.GetType().Namespace}.{node.Object.GetType().Name}"); output.Append("\""); if (node.WasTruncated) { data.TruncatedNodes.Add(node.Object); output.Append(" id=\"googlered\""); } else if (node.IsRoot) { if (node.OutLinks.Any()) { data.InternalNodes.Add(node.Object); } else { data.LeafNodes.Add(node.Object); } output.Append(" id=\"dark googlegreen\""); } else if (!node.OutLinks.Any()) { data.LeafNodes.Add(node.Object); output.Append(" id=\"dark googlered\""); } else { data.InternalNodes.Add(node.Object); } output.Append(" ];\n"); } // Write the node connections foreach (Node node in nodes.Values) { foreach (KeyValuePair<string, int> pair in node.OutLinks) { output.Append(" "); output.Append(node.Id); output.Append(" -> "); output.Append(pair.Value); output.Append(" [ label=\""); output.Append(pair.Key); output.Append("\" ];\n"); } } // Write the footer output.Append("}\n"); return output.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. #if ENABLEDATABINDING using System; using Microsoft.Xml; using Microsoft.Xml.Schema; using Microsoft.Xml.XPath; using System.Collections; using System.Diagnostics; using System.ComponentModel; using System.Text; namespace Microsoft.Xml.XPath.DataBinding { internal enum BindingType { Text, Element, Attribute, ElementNested, Repeat, Sequence, Choice, All } internal sealed class Shape { string name; BindingType bindingType; ArrayList particles; // XmlSchemaElement or XmlSchemaAttribute ArrayList subShapes; Shape nestedShape; PropertyDescriptor[] propertyDescriptors; XmlSchemaElement containerDecl; static object[] emptyIList = new object[0]; public Shape(string name, BindingType bindingType) { this.name = name; this.bindingType = bindingType; } public string Name { get { return this.name; } set { this.name = value; } } public BindingType BindingType { get { return this.bindingType; } set { this.bindingType = value; } } public XmlSchemaElement ContainerDecl { get { return this.containerDecl; } set { this.containerDecl = value; } } public bool IsNestedTable { get { switch (this.BindingType) { case BindingType.ElementNested: case BindingType.Repeat: case BindingType.Sequence: case BindingType.Choice: case BindingType.All: return true; default: return false; } } } public bool IsGroup { get { switch (this.BindingType) { case BindingType.Sequence: case BindingType.Choice: case BindingType.All: return true; default: return false; } } } public XmlSchemaType SchemaType { get { switch (this.bindingType) { case BindingType.Text: case BindingType.Element: case BindingType.ElementNested: { Debug.Assert(this.particles.Count == 1); XmlSchemaElement xse = (XmlSchemaElement)this.particles[0]; return xse.ElementSchemaType; } case BindingType.Attribute: { Debug.Assert(this.particles.Count == 1); XmlSchemaAttribute xsa = (XmlSchemaAttribute)this.particles[0]; return xsa.AttributeSchemaType; } default: return null; } } } public XmlSchemaElement XmlSchemaElement { get { switch (this.bindingType) { case BindingType.Text: case BindingType.Element: case BindingType.ElementNested: { Debug.Assert(this.particles.Count == 1); return (XmlSchemaElement)this.particles[0]; } default: return this.containerDecl; } } } public IList Particles { get { if (null == this.particles) return emptyIList; return this.particles; } } public IList SubShapes { get { if (null == this.subShapes) return emptyIList; return this.subShapes; } } public Shape SubShape(int i) { return (Shape)SubShapes[i]; } public Shape NestedShape { get { //Debug.Assert(this.bindingType == BindingType.ElementNested); return this.nestedShape; } set { this.nestedShape = value; } } public XmlQualifiedName AttributeName { get { Debug.Assert(this.bindingType == BindingType.Attribute); XmlSchemaAttribute xsa = (XmlSchemaAttribute)this.particles[0]; return xsa.QualifiedName; } } public void Clear() { if (this.subShapes != null) { this.subShapes.Clear(); this.subShapes = null; } if (this.particles != null) { this.particles.Clear(); this.particles = null; } } public void AddParticle(XmlSchemaElement elem) { if (null == this.particles) this.particles = new ArrayList(); Debug.Assert(this.bindingType != BindingType.Attribute); this.particles.Add(elem); } public void AddParticle(XmlSchemaAttribute elem) { Debug.Assert(this.bindingType == BindingType.Attribute); Debug.Assert(this.particles == null); this.particles = new ArrayList(); this.particles.Add(elem); } public void AddSubShape(Shape shape) { if (null == this.subShapes) this.subShapes = new ArrayList(); this.subShapes.Add(shape); foreach (object p in shape.Particles) { XmlSchemaElement xse = p as XmlSchemaElement; if (null != xse) AddParticle(xse); } } public void AddAttrShapeAt(Shape shape, int pos) { if (null == this.subShapes) this.subShapes = new ArrayList(); this.subShapes.Insert(pos, shape); } public string[] SubShapeNames() { string[] names = new string[SubShapes.Count]; for (int i=0; i<SubShapes.Count; i++) names[i] = this.SubShape(i).Name; return names; } public PropertyDescriptor[] PropertyDescriptors { get { if (null == this.propertyDescriptors) { PropertyDescriptor[] descs; switch (this.BindingType) { case BindingType.Element: case BindingType.Text: case BindingType.Attribute: case BindingType.Repeat: descs = new PropertyDescriptor[1]; descs[0] = new XPathNodeViewPropertyDescriptor(this); break; case BindingType.ElementNested: descs = this.nestedShape.PropertyDescriptors; break; case BindingType.Sequence: case BindingType.Choice: case BindingType.All: descs = new PropertyDescriptor[SubShapes.Count]; for (int i=0; i < descs.Length; i++) { descs[i] = new XPathNodeViewPropertyDescriptor(this, this.SubShape(i), i); } break; default: throw new NotSupportedException(); } this.propertyDescriptors = descs; } return this.propertyDescriptors; } } public int FindNamedSubShape(string name) { for (int i=0; i<SubShapes.Count; i++) { Shape shape = SubShape(i); if (shape.Name == name) return i; } return -1; } public int FindMatchingSubShape(object particle) { for (int i=0; i<SubShapes.Count; i++) { Shape shape = SubShape(i); if (shape.IsParticleMatch(particle)) return i; } return -1; } public bool IsParticleMatch(object particle) { for (int i=0; i<this.particles.Count; i++) { if (particle == this.particles[i]) return true; } return false; } #if DEBUG public string DebugDump() { StringBuilder sb = new StringBuilder(); DebugDump(sb,""); return sb.ToString(); } void DebugDump(StringBuilder sb, String indent) { sb.AppendFormat("{0}{1} '{2}'", indent, this.BindingType.ToString(), this.Name); if (this.subShapes != null) { sb.AppendLine(" {"); string subindent = String.Concat(indent, " "); foreach (Shape s in this.SubShapes) { s.DebugDump(sb, subindent); } sb.Append(indent); sb.Append('}'); } sb.AppendLine(); } #endif } } #endif
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System.Collections.Generic; using System.ServiceModel.Description; using System.Text; using System.Runtime.Serialization; using System.ServiceModel.Channels; using System.ServiceModel; using System.Xml; using System.ComponentModel; public sealed class TextMessageEncodingBindingElement : MessageEncodingBindingElement, IWsdlExportExtension, IPolicyExportExtension { int maxReadPoolSize; int maxWritePoolSize; XmlDictionaryReaderQuotas readerQuotas; MessageVersion messageVersion; Encoding writeEncoding; public TextMessageEncodingBindingElement() : this(MessageVersion.Default, TextEncoderDefaults.Encoding) { } public TextMessageEncodingBindingElement(MessageVersion messageVersion, Encoding writeEncoding) { if (messageVersion == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageVersion"); if (writeEncoding == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writeEncoding"); TextEncoderDefaults.ValidateEncoding(writeEncoding); this.maxReadPoolSize = EncoderDefaults.MaxReadPoolSize; this.maxWritePoolSize = EncoderDefaults.MaxWritePoolSize; this.readerQuotas = new XmlDictionaryReaderQuotas(); EncoderDefaults.ReaderQuotas.CopyTo(this.readerQuotas); this.messageVersion = messageVersion; this.writeEncoding = writeEncoding; } TextMessageEncodingBindingElement(TextMessageEncodingBindingElement elementToBeCloned) : base(elementToBeCloned) { this.maxReadPoolSize = elementToBeCloned.maxReadPoolSize; this.maxWritePoolSize = elementToBeCloned.maxWritePoolSize; this.readerQuotas = new XmlDictionaryReaderQuotas(); elementToBeCloned.readerQuotas.CopyTo(this.readerQuotas); this.writeEncoding = elementToBeCloned.writeEncoding; this.messageVersion = elementToBeCloned.messageVersion; } [DefaultValue(EncoderDefaults.MaxReadPoolSize)] public int MaxReadPoolSize { get { return this.maxReadPoolSize; } set { if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.ValueMustBePositive))); } this.maxReadPoolSize = value; } } [DefaultValue(EncoderDefaults.MaxWritePoolSize)] public int MaxWritePoolSize { get { return this.maxWritePoolSize; } set { if (value <= 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException("value", value, SR.GetString(SR.ValueMustBePositive))); } this.maxWritePoolSize = value; } } public XmlDictionaryReaderQuotas ReaderQuotas { get { return this.readerQuotas; } set { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); value.CopyTo(this.readerQuotas); } } public override MessageVersion MessageVersion { get { return this.messageVersion; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } this.messageVersion = value; } } [TypeConverter(typeof(System.ServiceModel.Configuration.EncodingConverter))] public Encoding WriteEncoding { get { return this.writeEncoding; } set { if (value == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); } TextEncoderDefaults.ValidateEncoding(value); this.writeEncoding = value; } } public override IChannelFactory<TChannel> BuildChannelFactory<TChannel>(BindingContext context) { return InternalBuildChannelFactory<TChannel>(context); } public override IChannelListener<TChannel> BuildChannelListener<TChannel>(BindingContext context) { return InternalBuildChannelListener<TChannel>(context); } public override bool CanBuildChannelListener<TChannel>(BindingContext context) { return InternalCanBuildChannelListener<TChannel>(context); } public override BindingElement Clone() { return new TextMessageEncodingBindingElement(this); } public override MessageEncoderFactory CreateMessageEncoderFactory() { return new TextMessageEncoderFactory(MessageVersion, WriteEncoding, this.MaxReadPoolSize, this.MaxWritePoolSize, this.ReaderQuotas); } public override T GetProperty<T>(BindingContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } if (typeof(T) == typeof(XmlDictionaryReaderQuotas)) { return (T)(object)this.readerQuotas; } else { return base.GetProperty<T>(context); } } void IPolicyExportExtension.ExportPolicy(MetadataExporter exporter, PolicyConversionContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } } void IWsdlExportExtension.ExportContract(WsdlExporter exporter, WsdlContractConversionContext context) { } void IWsdlExportExtension.ExportEndpoint(WsdlExporter exporter, WsdlEndpointConversionContext context) { if (context == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context"); } SoapHelper.SetSoapVersion(context, exporter, this.messageVersion.Envelope); } internal override bool CheckEncodingVersion(EnvelopeVersion version) { return messageVersion.Envelope == version; } internal override bool IsMatch(BindingElement b) { if (!base.IsMatch(b)) return false; TextMessageEncodingBindingElement text = b as TextMessageEncodingBindingElement; if (text == null) return false; if (this.maxReadPoolSize != text.MaxReadPoolSize) return false; if (this.maxWritePoolSize != text.MaxWritePoolSize) return false; // compare XmlDictionaryReaderQuotas if (this.readerQuotas.MaxStringContentLength != text.ReaderQuotas.MaxStringContentLength) return false; if (this.readerQuotas.MaxArrayLength != text.ReaderQuotas.MaxArrayLength) return false; if (this.readerQuotas.MaxBytesPerRead != text.ReaderQuotas.MaxBytesPerRead) return false; if (this.readerQuotas.MaxDepth != text.ReaderQuotas.MaxDepth) return false; if (this.readerQuotas.MaxNameTableCharCount != text.ReaderQuotas.MaxNameTableCharCount) return false; if (this.WriteEncoding.EncodingName != text.WriteEncoding.EncodingName) return false; if (!this.MessageVersion.IsMatch(text.MessageVersion)) return false; return true; } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeReaderQuotas() { return (!EncoderDefaults.IsDefaultReaderQuotas(this.ReaderQuotas)); } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeWriteEncoding() { return (this.WriteEncoding != TextEncoderDefaults.Encoding); } } }
using System.Collections; using System.Collections.Generic; using System.Runtime.CompilerServices; namespace Db1K.PriorityQueueBenchmark.BlueRaja { /// <summary> /// An implementation of a min-Priority Queue using a heap. Has O(1) .Contains()! /// See https://bitbucket.org/BlueRaja/high-speed-priority-queue-for-c/wiki/Getting%20Started for more information /// </summary> /// <typeparam name="T">The values in the queue. Must implement the PriorityQueueNode interface</typeparam> public sealed class HeapPriorityQueue<T> : IPriorityQueue<T> where T : PriorityQueueNode { private int _numNodes; private readonly T[] _nodes; private long _numNodesEverEnqueued; /// <summary> /// Instantiate a new Priority Queue /// </summary> /// <param name="maxNodes">The max nodes ever allowed to be enqueued (going over this will cause an exception)</param> public HeapPriorityQueue(int maxNodes) { _numNodes = 0; _nodes = new T[maxNodes + 1]; _numNodesEverEnqueued = 0; } /// <summary> /// Returns the number of nodes in the queue. O(1) /// </summary> public int Count { get { return _numNodes; } } /// <summary> /// Returns the maximum number of items that can be enqueued at once in this queue. Once you hit this number (ie. once Count == MaxSize), /// attempting to enqueue another item will throw an exception. O(1) /// </summary> public int MaxSize { get { return _nodes.Length - 1; } } /// <summary> /// Removes every node from the queue. O(n) (So, don't do this often!) /// </summary> #if NET_VERSION_4_5 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void Clear() { for (int i = 1; i < _nodes.Length; i++) _nodes[i] = null; _numNodes = 0; } /// <summary> /// Returns (in O(1)!) whether the given node is in the queue. O(1) /// </summary> #if NET_VERSION_4_5 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public bool Contains(T node) { return (_nodes[node.QueueIndex] == node); } /// <summary> /// Enqueue a node - .Priority must be set beforehand! O(log n) /// </summary> #if NET_VERSION_4_5 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void Enqueue(T node, double priority) { node.Priority = priority; _numNodes++; _nodes[_numNodes] = node; node.QueueIndex = _numNodes; node.InsertionIndex = _numNodesEverEnqueued++; CascadeUp(_nodes[_numNodes]); } #if NET_VERSION_4_5 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif private void Swap(T node1, T node2) { //Swap the nodes _nodes[node1.QueueIndex] = node2; _nodes[node2.QueueIndex] = node1; //Swap their indicies int temp = node1.QueueIndex; node1.QueueIndex = node2.QueueIndex; node2.QueueIndex = temp; } //Performance appears to be slightly better when this is NOT inlined o_O private void CascadeUp(T node) { //aka Heapify-up int parent = node.QueueIndex / 2; while (parent >= 1) { T parentNode = _nodes[parent]; if (HasHigherPriority(parentNode, node)) break; //Node has lower priority value, so move it up the heap Swap(node, parentNode); //For some reason, this is faster with Swap() rather than (less..?) individual operations, like in CascadeDown() parent = node.QueueIndex / 2; } } #if NET_VERSION_4_5 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif private void CascadeDown(T node) { //aka Heapify-down T newParent; int finalQueueIndex = node.QueueIndex; while (true) { newParent = node; int childLeftIndex = 2 * finalQueueIndex; //Check if the left-child is higher-priority than the current node if (childLeftIndex > _numNodes) { //This could be placed outside the loop, but then we'd have to check newParent != node twice node.QueueIndex = finalQueueIndex; _nodes[finalQueueIndex] = node; break; } T childLeft = _nodes[childLeftIndex]; if (HasHigherPriority(childLeft, newParent)) { newParent = childLeft; } //Check if the right-child is higher-priority than either the current node or the left child int childRightIndex = childLeftIndex + 1; if (childRightIndex <= _numNodes) { T childRight = _nodes[childRightIndex]; if (HasHigherPriority(childRight, newParent)) { newParent = childRight; } } //If either of the children has higher (smaller) priority, swap and continue cascading if (newParent != node) { //Move new parent to its new index. node will be moved once, at the end //Doing it this way is one less assignment operation than calling Swap() _nodes[finalQueueIndex] = newParent; int temp = newParent.QueueIndex; newParent.QueueIndex = finalQueueIndex; finalQueueIndex = temp; } else { //See note above node.QueueIndex = finalQueueIndex; _nodes[finalQueueIndex] = node; break; } } } /// <summary> /// Returns true if 'higher' has higher priority than 'lower', false otherwise. /// Note that calling HasHigherPriority(node, node) (ie. both arguments the same node) will return false /// </summary> #if NET_VERSION_4_5 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif private bool HasHigherPriority(T higher, T lower) { return (higher.Priority < lower.Priority || (higher.Priority == lower.Priority && higher.InsertionIndex < lower.InsertionIndex)); } /// <summary> /// Removes the head of the queue (node with highest priority; ties are broken by order of insertion), and returns it. O(log n) /// </summary> public T Dequeue() { T returnMe = _nodes[1]; Remove(returnMe); return returnMe; } /// <summary> /// Returns the head of the queue, without removing it (use Dequeue() for that). O(1) /// </summary> public T First { get { return _nodes[1]; } } /// <summary> /// This method must be called on a node every time its priority changes while it is in the queue. /// <b>Forgetting to call this method will result in a corrupted queue!</b> /// O(log n) /// </summary> #if NET_VERSION_4_5 [MethodImpl(MethodImplOptions.AggressiveInlining)] #endif public void UpdatePriority(T node, double priority) { node.Priority = priority; OnNodeUpdated(node); } private void OnNodeUpdated(T node) { //Bubble the updated node up or down as appropriate int parentIndex = node.QueueIndex / 2; T parentNode = _nodes[parentIndex]; if (parentIndex > 0 && HasHigherPriority(node, parentNode)) { CascadeUp(node); } else { //Note that CascadeDown will be called if parentNode == node (that is, node is the root) CascadeDown(node); } } /// <summary> /// Removes a node from the queue. Note that the node does not need to be the head of the queue. O(log n) /// </summary> public void Remove(T node) { if (!Contains(node)) { return; } if (_numNodes <= 1) { _nodes[1] = null; _numNodes = 0; return; } //Make sure the node is the last node in the queue bool wasSwapped = false; T formerLastNode = _nodes[_numNodes]; if (node.QueueIndex != _numNodes) { //Swap the node with the last node Swap(node, formerLastNode); wasSwapped = true; } _numNodes--; _nodes[node.QueueIndex] = null; if (wasSwapped) { //Now bubble formerLastNode (which is no longer the last node) up or down as appropriate OnNodeUpdated(formerLastNode); } } public IEnumerator<T> GetEnumerator() { for (int i = 1; i <= _numNodes; i++) yield return _nodes[i]; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// <b>Should not be called in production code.</b> /// Checks to make sure the queue is still in a valid state. Used for testing/debugging the queue. /// </summary> public bool IsValidQueue() { for (int i = 1; i < _nodes.Length; i++) { if (_nodes[i] != null) { int childLeftIndex = 2 * i; if (childLeftIndex < _nodes.Length && _nodes[childLeftIndex] != null && HasHigherPriority(_nodes[childLeftIndex], _nodes[i])) return false; int childRightIndex = childLeftIndex + 1; if (childRightIndex < _nodes.Length && _nodes[childRightIndex] != null && HasHigherPriority(_nodes[childRightIndex], _nodes[i])) return false; } } return true; } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Data; using System.Globalization; using System.Text; using System.Windows.Forms; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Extensibility.BlogClient; using OpenLiveWriter.HtmlParser.Parser; using OpenLiveWriter.Interop.Windows; using OpenLiveWriter.Localization; namespace OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl { internal partial class TreeCategorySelector : UserControl, ICategorySelector { private readonly CategoryContext ctx; private TreeNode[] nodes = new TreeNode[0]; private string lastQuery = ""; private bool initMode = false; internal class DoubleClicklessTreeView : TreeView { public DoubleClicklessTreeView() { SetStyle(ControlStyles.DoubleBuffer, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); } protected override void WndProc(ref Message m) { if (m.Msg == WM.LBUTTONDBLCLK) { m.Msg = (int)WM.LBUTTONDOWN; } base.WndProc(ref m); } } public TreeCategorySelector() { Debug.Assert(DesignMode); InitializeComponent(); } public TreeCategorySelector(CategoryContext ctx) { this.ctx = ctx; InitializeComponent(); // TODO: Whoops, missed UI Freeze... add this later //treeView.AccessibleName = Res.Get(StringId.CategorySelector); // On Windows XP, checkboxes and images seem to be mutually exclusive. Vista works fine though. if (Environment.OSVersion.Version.Major >= 6) { imageList.Images.Add(new Bitmap(imageList.ImageSize.Width, imageList.ImageSize.Height)); treeView.ImageList = imageList; treeView.ImageIndex = 0; } LoadCategories(); treeView.BeforeCollapse += delegate (object sender, TreeViewCancelEventArgs e) { e.Cancel = true; }; treeView.AfterCheck += treeView1_AfterCheck; treeView.LostFocus += delegate { treeView.Invalidate(); }; } private delegate void Walker(TreeNode n); void WalkNodes(TreeNodeCollection nodes, Walker walker) { foreach (TreeNode n in nodes) { walker(n); WalkNodes(n.Nodes, walker); } } public override Size GetPreferredSize(Size proposedSize) { int width = 0; int height = 0; WalkNodes(treeView.Nodes, delegate (TreeNode n) { width = Math.Max(width, n.Bounds.Right); height = Math.Max(height, n.Bounds.Bottom); }); width += Padding.Left + Padding.Right; height += Padding.Top + Padding.Bottom; return new Size(width, height); } void treeView1_AfterCheck(object sender, TreeViewEventArgs e) { if (initMode) return; List<BlogPostCategory> categories = new List<BlogPostCategory>(ctx.SelectedCategories); TreeNode realTreeNode = (TreeNode)e.Node.Tag; realTreeNode.Checked = e.Node.Checked; BlogPostCategory category = (BlogPostCategory)(realTreeNode.Tag); if (e.Node.Checked) { // Fix bug 587012: Category control can display one category repeatedly if // checked category is added from search box after refresh categories.Remove(category); categories.Add(category); } else categories.Remove(category); ctx.SelectedCategories = categories.ToArray(); } public static TreeNode[] CategoriesToNodes(BlogPostCategory[] categories) { Array.Sort(categories); Dictionary<string, TreeNode> catToNode = new Dictionary<string, TreeNode>(); TreeNode[] allNodes = new TreeNode[categories.Length]; for (int i = 0; i < categories.Length; i++) { // TODO: This will need to be rewritten to deal with the fact that // ID doesn't work effectively in the face of hierarchy and new categories allNodes[i] = new TreeNode(HtmlUtils.UnEscapeEntities(categories[i].Name, HtmlUtils.UnEscapeMode.Default)); allNodes[i].Tag = categories[i]; // TODO: // This is necessary due to bug in categories, where multiple // new categories with the same name (but different parents) // have the same ID. When that bug is fixed this check should be // replaced with an assertion. if (!catToNode.ContainsKey(categories[i].Id)) catToNode.Add(categories[i].Id, allNodes[i]); } for (int i = 0; i < allNodes.Length; i++) { TreeNode node = allNodes[i]; string parent = ((BlogPostCategory)node.Tag).Parent; if (!string.IsNullOrEmpty(parent) && catToNode.ContainsKey(parent)) { catToNode[parent].Nodes.Add(node); allNodes[i] = null; } } return (TreeNode[])ArrayHelper.Compact(allNodes); } private TreeNode[] RealNodes { get { return nodes; } } private static TreeNode[] FilteredNodes(IEnumerable nodes, Predicate<TreeNode> predicate) { List<TreeNode> results = null; foreach (TreeNode node in nodes) { TreeNode[] filteredChildNodes = FilteredNodes(node.Nodes, predicate); if (filteredChildNodes.Length > 0 || predicate(node)) { if (results == null) results = new List<TreeNode>(); TreeNode newNode = new TreeNode(node.Text, filteredChildNodes); newNode.Tag = node; newNode.Checked = node.Checked; results.Add(newNode); } } if (results == null) return new TreeNode[0]; else return results.ToArray(); } private TreeNode FindFirstMatch(TreeNodeCollection nodes, Predicate<TreeNode> predicate) { foreach (TreeNode node in nodes) { if (predicate(node)) return node; TreeNode child = FindFirstMatch(node.Nodes, predicate); if (child != null) return child; } return null; } private TreeNode SelectLastNode(TreeNodeCollection nodes) { if (nodes.Count == 0) return null; TreeNode lastNode = nodes[nodes.Count - 1]; return SelectLastNode(lastNode.Nodes) ?? lastNode; } private bool KeepNodes(ICollection nodes, Predicate<TreeNode> predicate) { bool keptAny = false; // The ArrayList wrapper is to prevent changing the enumerator while // still enumerating, which causes bugs foreach (TreeNode node in new ArrayList(nodes)) { if (KeepNodes(node.Nodes, predicate) || predicate(node)) keptAny = true; else node.Remove(); } return keptAny; } public void LoadCategories() { initMode = true; try { nodes = CategoriesToNodes(ctx.Categories); treeView.Nodes.Clear(); treeView.Nodes.AddRange(FilteredNodes(RealNodes, delegate { return true; })); HashSet selectedCategories = new HashSet(); selectedCategories.AddAll(ctx.SelectedCategories); if (selectedCategories.Count > 0) WalkNodes(treeView.Nodes, delegate (TreeNode n) { n.Checked = selectedCategories.Contains(((TreeNode)n.Tag).Tag as BlogPostCategory); }); treeView.ExpandAll(); } finally { initMode = false; } } public void Filter(string criteria) { treeView.BeginUpdate(); try { Predicate<TreeNode> prefixPredicate = delegate (TreeNode node) { return node.Text.ToLower(CultureInfo.CurrentCulture).StartsWith(criteria); }; if (criteria.Length > 0 && criteria.StartsWith(lastQuery)) { KeepNodes(treeView.Nodes, prefixPredicate); } else { treeView.Nodes.Clear(); if (criteria.Length == 0) treeView.Nodes.AddRange(FilteredNodes(RealNodes, delegate { return true; })); else { treeView.Nodes.AddRange(FilteredNodes(RealNodes, prefixPredicate)); } } treeView.ExpandAll(); if (treeView.Nodes.Count > 0) treeView.Nodes[0].EnsureVisible(); Predicate<TreeNode> equalityPredicate = delegate (TreeNode n) { return n.Text.ToLower(CultureInfo.CurrentCulture) == criteria; }; if (treeView.SelectedNode == null || !equalityPredicate(treeView.SelectedNode)) { TreeNode firstMatch = FindFirstMatch(treeView.Nodes, equalityPredicate); if (firstMatch != null) treeView.SelectedNode = firstMatch; else if (treeView.SelectedNode == null || !prefixPredicate(treeView.SelectedNode)) { firstMatch = FindFirstMatch(treeView.Nodes, prefixPredicate); if (firstMatch != null) treeView.SelectedNode = firstMatch; } } } finally { treeView.EndUpdate(); } lastQuery = criteria; } public void SelectCategory(BlogPostCategory category) { WalkNodes(treeView.Nodes, delegate (TreeNode n) { if (category.Equals(((TreeNode)n.Tag).Tag)) { if (!n.Checked) n.Checked = true; treeView.SelectedNode = n; n.EnsureVisible(); } }); } public void UpArrow() { TreeNode selectedNode = treeView.SelectedNode; if (selectedNode == null) { if (treeView.Nodes.Count > 0) { treeView.SelectedNode = SelectLastNode(treeView.Nodes); } } else { TreeNode nextNode = selectedNode.PrevVisibleNode; if (nextNode != null) treeView.SelectedNode = nextNode; } if (treeView.SelectedNode != null) treeView.SelectedNode.EnsureVisible(); treeView.Focus(); } public void DownArrow() { TreeNode selectedNode = treeView.SelectedNode; if (selectedNode == null) { if (treeView.Nodes.Count > 0) { treeView.SelectedNode = treeView.Nodes[0]; } } else { TreeNode nextNode = selectedNode.NextVisibleNode; if (nextNode != null) treeView.SelectedNode = nextNode; } if (treeView.SelectedNode != null) treeView.SelectedNode.EnsureVisible(); treeView.Focus(); } void ICategorySelector.Enter() { if (treeView.SelectedNode != null) treeView.SelectedNode.Checked = !treeView.SelectedNode.Checked; } void ICategorySelector.CtrlEnter() { if (treeView.SelectedNode != null && !treeView.SelectedNode.Checked) treeView.SelectedNode.Checked = true; FindForm().Close(); } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // namespace DiscUtils.Ntfs { using System; using System.IO; using System.Security.AccessControl; using System.Security.Principal; internal class NtfsFormatter { private int _clusterSize; private int _mftRecordSize; private int _indexBufferSize; private long _bitmapCluster; private long _mftMirrorCluster; private long _mftCluster; private NtfsContext _context; public string Label { get; set; } public Geometry DiskGeometry { get; set; } public long FirstSector { get; set; } public long SectorCount { get; set; } public byte[] BootCode { get; set; } public SecurityIdentifier ComputerAccount { get; set; } public NtfsFileSystem Format(Stream stream) { _context = new NtfsContext(); _context.Options = new NtfsOptions(); _context.RawStream = stream; _context.AttributeDefinitions = new AttributeDefinitions(); string localAdminString = (ComputerAccount == null) ? "LA" : new SecurityIdentifier(WellKnownSidType.AccountAdministratorSid, ComputerAccount).ToString(); using (new NtfsTransaction()) { _clusterSize = 4096; _mftRecordSize = 1024; _indexBufferSize = 4096; long totalClusters = ((SectorCount - 1) * Sizes.Sector) / _clusterSize; // Allocate a minimum of 8KB for the boot loader, but allow for more int numBootClusters = Utilities.Ceil(Math.Max((int)(8 * Sizes.OneKiB), BootCode == null ? 0 : BootCode.Length), _clusterSize); // Place MFT mirror in the middle of the volume _mftMirrorCluster = totalClusters / 2; uint numMftMirrorClusters = 1; // The bitmap is also near the middle _bitmapCluster = _mftMirrorCluster + 13; int numBitmapClusters = (int)Utilities.Ceil((totalClusters / 8), _clusterSize); // The MFT bitmap goes 'near' the start - approx 10% in - but ensure we avoid the bootloader long mftBitmapCluster = Math.Max(3 + (totalClusters / 10), numBootClusters); int numMftBitmapClusters = 1; // The MFT follows it's bitmap _mftCluster = mftBitmapCluster + numMftBitmapClusters; int numMftClusters = 8; if (_mftCluster + numMftClusters > _mftMirrorCluster || _bitmapCluster + numBitmapClusters >= totalClusters) { throw new IOException("Unable to determine initial layout of NTFS metadata - disk may be too small"); } CreateBiosParameterBlock(stream, numBootClusters * _clusterSize); _context.Mft = new MasterFileTable(_context); File mftFile = _context.Mft.InitializeNew(_context, mftBitmapCluster, (ulong)numMftBitmapClusters, (long)_mftCluster, (ulong)numMftClusters); File bitmapFile = CreateFixedSystemFile(MasterFileTable.BitmapIndex, _bitmapCluster, (ulong)numBitmapClusters, true); _context.ClusterBitmap = new ClusterBitmap(bitmapFile); _context.ClusterBitmap.MarkAllocated(0, numBootClusters); _context.ClusterBitmap.MarkAllocated(_bitmapCluster, numBitmapClusters); _context.ClusterBitmap.MarkAllocated(mftBitmapCluster, numMftBitmapClusters); _context.ClusterBitmap.MarkAllocated(_mftCluster, numMftClusters); _context.ClusterBitmap.SetTotalClusters(totalClusters); bitmapFile.UpdateRecordInMft(); File mftMirrorFile = CreateFixedSystemFile(MasterFileTable.MftMirrorIndex, _mftMirrorCluster, numMftMirrorClusters, true); File logFile = CreateSystemFile(MasterFileTable.LogFileIndex); using (Stream s = logFile.OpenStream(AttributeType.Data, null, FileAccess.ReadWrite)) { s.SetLength(Math.Min(Math.Max(2 * Sizes.OneMiB, (totalClusters / 500) * (long)_clusterSize), 64 * Sizes.OneMiB)); byte[] buffer = new byte[1024 * 1024]; for (int i = 0; i < buffer.Length; ++i) { buffer[i] = 0xFF; } long totalWritten = 0; while (totalWritten < s.Length) { int toWrite = (int)Math.Min(s.Length - totalWritten, buffer.Length); s.Write(buffer, 0, toWrite); totalWritten += toWrite; } } File volumeFile = CreateSystemFile(MasterFileTable.VolumeIndex); NtfsStream volNameStream = volumeFile.CreateStream(AttributeType.VolumeName, null); volNameStream.SetContent(new VolumeName(Label ?? "New Volume")); NtfsStream volInfoStream = volumeFile.CreateStream(AttributeType.VolumeInformation, null); volInfoStream.SetContent(new VolumeInformation(3, 1, VolumeInformationFlags.None)); SetSecurityAttribute(volumeFile, "O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)"); volumeFile.UpdateRecordInMft(); _context.GetFileByIndex = delegate(long index) { return new File(_context, _context.Mft.GetRecord(index, false)); }; _context.AllocateFile = delegate(FileRecordFlags frf) { return new File(_context, _context.Mft.AllocateRecord(frf, false)); }; File attrDefFile = CreateSystemFile(MasterFileTable.AttrDefIndex); _context.AttributeDefinitions.WriteTo(attrDefFile); SetSecurityAttribute(attrDefFile, "O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)"); attrDefFile.UpdateRecordInMft(); File bootFile = CreateFixedSystemFile(MasterFileTable.BootIndex, 0, (uint)numBootClusters, false); SetSecurityAttribute(bootFile, "O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)"); bootFile.UpdateRecordInMft(); File badClusFile = CreateSystemFile(MasterFileTable.BadClusIndex); badClusFile.CreateStream(AttributeType.Data, "$Bad"); badClusFile.UpdateRecordInMft(); File secureFile = CreateSystemFile(MasterFileTable.SecureIndex, FileRecordFlags.HasViewIndex); secureFile.RemoveStream(secureFile.GetStream(AttributeType.Data, null)); _context.SecurityDescriptors = SecurityDescriptors.Initialize(secureFile); secureFile.UpdateRecordInMft(); File upcaseFile = CreateSystemFile(MasterFileTable.UpCaseIndex); _context.UpperCase = UpperCase.Initialize(upcaseFile); upcaseFile.UpdateRecordInMft(); File objIdFile = File.CreateNew(_context, FileRecordFlags.IsMetaFile | FileRecordFlags.HasViewIndex, FileAttributeFlags.None); objIdFile.RemoveStream(objIdFile.GetStream(AttributeType.Data, null)); objIdFile.CreateIndex("$O", (AttributeType)0, AttributeCollationRule.MultipleUnsignedLongs); objIdFile.UpdateRecordInMft(); File reparseFile = File.CreateNew(_context, FileRecordFlags.IsMetaFile | FileRecordFlags.HasViewIndex, FileAttributeFlags.None); reparseFile.CreateIndex("$R", (AttributeType)0, AttributeCollationRule.MultipleUnsignedLongs); reparseFile.UpdateRecordInMft(); File quotaFile = File.CreateNew(_context, FileRecordFlags.IsMetaFile | FileRecordFlags.HasViewIndex, FileAttributeFlags.None); Quotas.Initialize(quotaFile); Directory extendDir = CreateSystemDirectory(MasterFileTable.ExtendIndex); extendDir.AddEntry(objIdFile, "$ObjId", FileNameNamespace.Win32AndDos); extendDir.AddEntry(reparseFile, "$Reparse", FileNameNamespace.Win32AndDos); extendDir.AddEntry(quotaFile, "$Quota", FileNameNamespace.Win32AndDos); extendDir.UpdateRecordInMft(); Directory rootDir = CreateSystemDirectory(MasterFileTable.RootDirIndex); rootDir.AddEntry(mftFile, "$MFT", FileNameNamespace.Win32AndDos); rootDir.AddEntry(mftMirrorFile, "$MFTMirr", FileNameNamespace.Win32AndDos); rootDir.AddEntry(logFile, "$LogFile", FileNameNamespace.Win32AndDos); rootDir.AddEntry(volumeFile, "$Volume", FileNameNamespace.Win32AndDos); rootDir.AddEntry(attrDefFile, "$AttrDef", FileNameNamespace.Win32AndDos); rootDir.AddEntry(rootDir, ".", FileNameNamespace.Win32AndDos); rootDir.AddEntry(bitmapFile, "$Bitmap", FileNameNamespace.Win32AndDos); rootDir.AddEntry(bootFile, "$Boot", FileNameNamespace.Win32AndDos); rootDir.AddEntry(badClusFile, "$BadClus", FileNameNamespace.Win32AndDos); rootDir.AddEntry(secureFile, "$Secure", FileNameNamespace.Win32AndDos); rootDir.AddEntry(upcaseFile, "$UpCase", FileNameNamespace.Win32AndDos); rootDir.AddEntry(extendDir, "$Extend", FileNameNamespace.Win32AndDos); SetSecurityAttribute(rootDir, "O:" + localAdminString + "G:BUD:(A;OICI;FA;;;BA)(A;OICI;FA;;;SY)(A;OICIIO;GA;;;CO)(A;OICI;0x1200a9;;;BU)(A;CI;LC;;;BU)(A;CIIO;DC;;;BU)(A;;0x1200a9;;;WD)"); rootDir.UpdateRecordInMft(); // A number of records are effectively 'reserved' for (long i = MasterFileTable.ExtendIndex + 1; i <= 15; i++) { File f = CreateSystemFile(i); SetSecurityAttribute(f, "O:S-1-5-21-1708537768-746137067-1060284298-1003G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)"); f.UpdateRecordInMft(); } } // XP-style security permissions setup NtfsFileSystem ntfs = new NtfsFileSystem(stream); ntfs.SetSecurity(@"$MFT", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)")); ntfs.SetSecurity(@"$MFTMirr", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)")); ntfs.SetSecurity(@"$LogFile", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)")); ntfs.SetSecurity(@"$Bitmap", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)")); ntfs.SetSecurity(@"$BadClus", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)")); ntfs.SetSecurity(@"$UpCase", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;FR;;;SY)(A;;FR;;;BA)")); ntfs.SetSecurity(@"$Secure", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)")); ntfs.SetSecurity(@"$Extend", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)")); ntfs.SetSecurity(@"$Extend\$Quota", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)")); ntfs.SetSecurity(@"$Extend\$ObjId", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)")); ntfs.SetSecurity(@"$Extend\$Reparse", new RawSecurityDescriptor("O:" + localAdminString + "G:BAD:(A;;0x12019f;;;SY)(A;;0x12019f;;;BA)")); ntfs.CreateDirectory("System Volume Information"); ntfs.SetAttributes("System Volume Information", FileAttributes.Hidden | FileAttributes.System | FileAttributes.Directory); ntfs.SetSecurity("System Volume Information", new RawSecurityDescriptor("O:BAG:SYD:(A;OICI;FA;;;SY)")); using (Stream s = ntfs.OpenFile(@"System Volume Information\MountPointManagerRemoteDatabase", FileMode.Create)) { } ntfs.SetAttributes(@"System Volume Information\MountPointManagerRemoteDatabase", FileAttributes.Hidden | FileAttributes.System | FileAttributes.Archive); ntfs.SetSecurity(@"System Volume Information\MountPointManagerRemoteDatabase", new RawSecurityDescriptor("O:BAG:SYD:(A;;FA;;;SY)")); return ntfs; } private static void SetSecurityAttribute(File file, string secDesc) { NtfsStream rootSecurityStream = file.CreateStream(AttributeType.SecurityDescriptor, null); SecurityDescriptor sd = new SecurityDescriptor(); sd.Descriptor = new RawSecurityDescriptor(secDesc); rootSecurityStream.SetContent(sd); } private File CreateFixedSystemFile(long mftIndex, long firstCluster, ulong numClusters, bool wipe) { BiosParameterBlock bpb = _context.BiosParameterBlock; if (wipe) { byte[] wipeBuffer = new byte[bpb.BytesPerCluster]; _context.RawStream.Position = firstCluster * bpb.BytesPerCluster; for (ulong i = 0; i < numClusters; ++i) { _context.RawStream.Write(wipeBuffer, 0, wipeBuffer.Length); } } FileRecord fileRec = _context.Mft.AllocateRecord((uint)mftIndex, FileRecordFlags.None); fileRec.Flags = FileRecordFlags.InUse; fileRec.SequenceNumber = (ushort)mftIndex; File file = new File(_context, fileRec); StandardInformation.InitializeNewFile(file, FileAttributeFlags.Hidden | FileAttributeFlags.System); file.CreateStream(AttributeType.Data, null, firstCluster, numClusters, (uint)bpb.BytesPerCluster); file.UpdateRecordInMft(); if (_context.ClusterBitmap != null) { _context.ClusterBitmap.MarkAllocated(firstCluster, (long)numClusters); } return file; } private File CreateSystemFile(long mftIndex) { return CreateSystemFile(mftIndex, FileRecordFlags.None); } private File CreateSystemFile(long mftIndex, FileRecordFlags flags) { FileRecord fileRec = _context.Mft.AllocateRecord((uint)mftIndex, flags); fileRec.SequenceNumber = (ushort)mftIndex; File file = new File(_context, fileRec); StandardInformation.InitializeNewFile(file, FileAttributeFlags.Hidden | FileAttributeFlags.System | FileRecord.ConvertFlags(flags)); file.CreateStream(AttributeType.Data, null); file.UpdateRecordInMft(); return file; } private Directory CreateSystemDirectory(long mftIndex) { FileRecord fileRec = _context.Mft.AllocateRecord((uint)mftIndex, FileRecordFlags.None); fileRec.Flags = FileRecordFlags.InUse | FileRecordFlags.IsDirectory; fileRec.SequenceNumber = (ushort)mftIndex; Directory dir = new Directory(_context, fileRec); StandardInformation.InitializeNewFile(dir, FileAttributeFlags.Hidden | FileAttributeFlags.System); dir.CreateIndex("$I30", AttributeType.FileName, AttributeCollationRule.Filename); dir.UpdateRecordInMft(); return dir; } private void CreateBiosParameterBlock(Stream stream, int bootFileSize) { byte[] bootSectors = new byte[bootFileSize]; if (BootCode != null) { Array.Copy(BootCode, 0, bootSectors, 0, BootCode.Length); } BiosParameterBlock bpb = BiosParameterBlock.Initialized(DiskGeometry, _clusterSize, (uint)FirstSector, SectorCount, _mftRecordSize, _indexBufferSize); bpb.MftCluster = _mftCluster; bpb.MftMirrorCluster = _mftMirrorCluster; bpb.ToBytes(bootSectors, 0); // Primary goes at the start of the partition stream.Position = 0; stream.Write(bootSectors, 0, bootSectors.Length); // Backup goes at the end of the data in the partition stream.Position = (SectorCount - 1) * Sizes.Sector; stream.Write(bootSectors, 0, Sizes.Sector); _context.BiosParameterBlock = bpb; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void InsertVector128UInt161() { var test = new ImmBinaryOpTest__InsertVector128UInt161(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmBinaryOpTest__InsertVector128UInt161 { private struct TestStruct { public Vector256<UInt16> _fld1; public Vector128<UInt16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); return testStruct; } public void RunStructFldScenario(ImmBinaryOpTest__InsertVector128UInt161 testClass) { var result = Avx.InsertVector128(_fld1, _fld2, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16); private static UInt16[] _data1 = new UInt16[Op1ElementCount]; private static UInt16[] _data2 = new UInt16[Op2ElementCount]; private static Vector256<UInt16> _clsVar1; private static Vector128<UInt16> _clsVar2; private Vector256<UInt16> _fld1; private Vector128<UInt16> _fld2; private SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16> _dataTable; static ImmBinaryOpTest__InsertVector128UInt161() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public ImmBinaryOpTest__InsertVector128UInt161() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); } _dataTable = new SimpleBinaryOpTest__DataTable<UInt16, UInt16, UInt16>(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Avx.InsertVector128( Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Avx.InsertVector128( Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)), Avx.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Avx.InsertVector128( Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<UInt16>), typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<UInt16>), typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)), Avx.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Avx).GetMethod(nameof(Avx.InsertVector128), new Type[] { typeof(Vector256<UInt16>), typeof(Vector128<UInt16>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Avx.InsertVector128( _clsVar1, _clsVar2, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var left = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr); var result = Avx.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var left = Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Avx.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var left = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr)); var result = Avx.InsertVector128(left, right, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmBinaryOpTest__InsertVector128UInt161(); var result = Avx.InsertVector128(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Avx.InsertVector128(_fld1, _fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Avx.InsertVector128(test._fld1, test._fld2, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector256<UInt16> left, Vector128<UInt16> right, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), left); Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { UInt16[] inArray1 = new UInt16[Op1ElementCount]; UInt16[] inArray2 = new UInt16[Op2ElementCount]; UInt16[] outArray = new UInt16[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != left[0]) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != (i < 8 ? left[i] : right[i-8])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx)}.{nameof(Avx.InsertVector128)}<UInt16>(Vector256<UInt16>.1, Vector128<UInt16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
#region License /* * Copyright 2009- Marko Lahma * * 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 #if REMOTING using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Remoting; using System.Runtime.Remoting.Channels; using System.Runtime.Remoting.Channels.Http; using System.Runtime.Remoting.Channels.Tcp; using System.Runtime.Serialization.Formatters; using System.Security; using Quartz.Logging; using Quartz.Spi; namespace Quartz.Simpl { /// <summary> /// Scheduler exporter that exports scheduler to remoting context. /// </summary> /// <author>Marko Lahma</author> public class RemotingSchedulerExporter : ISchedulerExporter { public const string ChannelTypeTcp = "tcp"; public const string ChannelTypeHttp = "http"; private const string DefaultBindName = "QuartzScheduler"; private const string DefaultChannelName = "http"; /// <summary> /// BinaryServerFormatterSinkProvider allowed properties. /// </summary> private static string[] formatProviderAllowedProperties = new string[] { "includeVersions", "strictBinding", "typeFilterLevel" }; private static readonly Dictionary<string, object> registeredChannels = new Dictionary<string, object>(); public RemotingSchedulerExporter() { ChannelType = ChannelTypeTcp; #if REMOTING TypeFilterLevel = TypeFilterLevel.Full; #endif // REMOTING ChannelName = DefaultChannelName; BindName = DefaultBindName; Log = LogProvider.GetLogger(GetType()); } public virtual void Bind(IRemotableQuartzScheduler scheduler) { if (scheduler == null) { throw new ArgumentNullException(nameof(scheduler)); } #if REMOTING if (!(scheduler is MarshalByRefObject)) { throw new ArgumentException("Exported scheduler must be of type MarshallByRefObject", nameof(scheduler)); } RegisterRemotingChannelIfNeeded(); try { RemotingServices.Marshal((MarshalByRefObject)scheduler, BindName); Log.Info($"Successfully marshalled remotable scheduler under name '{BindName}'"); } catch (RemotingException ex) { Log.ErrorException("RemotingException during Bind", ex); } catch (SecurityException ex) { Log.ErrorException("SecurityException during Bind", ex); } catch (Exception ex) { Log.ErrorException("Exception during Bind", ex); } #else // REMOTING // TODO (NetCore Port): Replace with HTTP communication #endif // REMOTING } /// <summary> /// Registers remoting channel if needed. This is determined /// by checking whether there is a positive value for port. /// </summary> protected virtual void RegisterRemotingChannelIfNeeded() { if (Port > 0 && ChannelType != null) { // try remoting bind var props = CreateConfiguration(); #if REMOTING // use binary formatter var formatProviderProps = ExtractFormatProviderConfiguration(props); var formatprovider = new BinaryServerFormatterSinkProvider(formatProviderProps, null); formatprovider.TypeFilterLevel = TypeFilterLevel; string channelRegistrationKey = ChannelType + "_" + Port; if (registeredChannels.ContainsKey(channelRegistrationKey)) { Log.Warn($"Channel '{ChannelType}' already registered for port {Port}, not registering again"); return; } IChannel chan; if (ChannelType == ChannelTypeHttp) { chan = new HttpChannel(props, null, formatprovider); } else if (ChannelType == ChannelTypeTcp) { chan = new TcpChannel(props, null, formatprovider); } else { throw new ArgumentException("Unknown remoting channel type '" + ChannelType + "'"); } if (RejectRemoteRequests) { Log.Info("Remoting is NOT accepting remote calls"); } else { Log.Info("Remoting is allowing remote calls"); } Log.Info($"Registering remoting channel of type '{chan.GetType()}' to port ({Port}) with name ({chan.ChannelName})"); ChannelServices.RegisterChannel(chan, false); registeredChannels.Add(channelRegistrationKey, new object()); #else // REMOTING // TODO (NetCore Port): Replace with HTTP communication #endif // REMOTING Log.Info("Remoting channel registered successfully"); } else { Log.Error("Cannot register remoting if port or channel type not specified"); } } protected virtual IDictionary CreateConfiguration() { IDictionary props = new Hashtable(); props["port"] = Port; props["name"] = ChannelName; if (RejectRemoteRequests) { props["rejectRemoteRequests"] = "true"; } return props; } /// <summary> /// Extract BinaryServerFormatterSinkProvider allowed properties from configuration properties. /// </summary> /// <param name="props">Configuration properties.</param> /// <returns>BinaryServerFormatterSinkProvider allowed properties from configuration.</returns> protected virtual IDictionary ExtractFormatProviderConfiguration(IDictionary props) { IDictionary formatProviderAllowedProps = new Hashtable(); foreach (var allowedProperty in formatProviderAllowedProps) { if (allowedProperty != null && props.Contains(allowedProperty)) { formatProviderAllowedProps[allowedProperty] = props[allowedProperty]; } } return formatProviderAllowedProps; } public virtual void UnBind(IRemotableQuartzScheduler scheduler) { if (scheduler == null) { throw new ArgumentNullException(nameof(scheduler)); } #if REMOTING if (!(scheduler is MarshalByRefObject)) { throw new ArgumentException("Exported scheduler must be of type MarshallByRefObject", nameof(scheduler)); } #endif // REMOTING try { #if REMOTING RemotingServices.Disconnect((MarshalByRefObject)scheduler); Log.Info("Successfully disconnected remotable scheduler"); #else // REMOTING // TODO (NetCore Port): Replace with HTTP communication #endif // REMOTING } catch (ArgumentException ex) { Log.ErrorException("ArgumentException during Unbind", ex); } catch (SecurityException ex) { Log.ErrorException("SecurityException during Unbind", ex); } catch (Exception ex) { Log.ErrorException("Exception during Unbind", ex); } } internal ILog Log { get; } /// <summary> /// Gets or sets the port used for remoting. /// </summary> public int Port { get; set; } /// <summary> /// Gets or sets the name to use when exporting /// scheduler to remoting context. /// </summary> public string BindName { get; set; } /// <summary> /// Gets or sets the name to use when binding to /// tcp channel. /// </summary> public string ChannelName { get; set; } /// <summary> /// Sets the channel type when registering remoting. /// </summary> public string ChannelType { get; set; } /// <summary> /// Sets the <see cref="TypeFilterLevel" /> used when /// exporting to remoting context. Defaults to /// <see cref="System.Runtime.Serialization.Formatters.TypeFilterLevel.Full" />. /// </summary> public TypeFilterLevel TypeFilterLevel { get; set; } /// <summary> /// A Boolean value (true or false) that specifies whether to refuse requests from other computers. /// Specifying true allows only remoting calls from the local computer. The default is false. /// </summary> public bool RejectRemoteRequests { get; set; } } } #endif // REMOTING
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Security.Cryptography.Encoding.Tests { public static class OidTests { [Fact] public static void EmptyOid() { Oid oid = new Oid(""); Assert.Equal("", oid.Value); Assert.Null(oid.FriendlyName); } [Theory] [MemberData(nameof(ValidOidFriendlyNamePairs))] public static void LookupOidByValue_Ctor(string oidValue, string friendlyName) { Oid oid = new Oid(oidValue); Assert.Equal(oidValue, oid.Value); Assert.Equal(friendlyName, oid.FriendlyName); } [Theory] [MemberData(nameof(ValidOidFriendlyNamePairs))] public static void LookupOidByFriendlyName_Ctor(string oidValue, string friendlyName) { Oid oid = new Oid(friendlyName); Assert.Equal(oidValue, oid.Value); Assert.Equal(friendlyName, oid.FriendlyName); } [Fact] public static void LookupNullOid() { Assert.Throws<ArgumentNullException>(() => new Oid((string)null)); } [Fact] public static void LookupUnknownOid() { Oid oid = new Oid(Bogus_Name); Assert.Equal(Bogus_Name, oid.Value); Assert.Null(oid.FriendlyName); } [Fact] public static void Oid_StringString_BothNull() { // No validation at all. Oid oid = new Oid(null, null); Assert.Null(oid.Value); Assert.Null(oid.FriendlyName); } [Theory] [MemberData(nameof(ValidOidFriendlyNamePairs))] public static void Oid_StringString_NullFriendlyName(string oidValue, string expectedFriendlyName) { // Can omit friendly-name - FriendlyName property demand-computes it. Oid oid = new Oid(oidValue, null); Assert.Equal(oidValue, oid.Value); Assert.Equal(expectedFriendlyName, oid.FriendlyName); } [Theory] [InlineData(SHA1_Name)] [InlineData(SHA256_Name)] [InlineData(Bogus_Name)] public static void Oid_StringString_NullValue(string friendlyName) { // Can omit oid, Value property does no on-demand conversion. Oid oid = new Oid(null, friendlyName); Assert.Null(oid.Value); Assert.Equal(friendlyName, oid.FriendlyName); } [Theory] [InlineData(SHA1_Oid, SHA256_Name)] [InlineData(SHA256_Oid, SHA1_Name)] [InlineData(SHA256_Name, SHA1_Name)] [InlineData(SHA256_Name, Bogus_Name)] [InlineData(Bogus_Name, SHA256_Oid)] public static void Oid_StringString_BothSpecified(string oidValue, string friendlyName) { // The values are taken as true, not verified at all. // The data for this test series should be mismatched OID-FriendlyName pairs, and // sometimes the OID isn't a legal OID. Oid oid = new Oid(oidValue, friendlyName); Assert.Equal(oidValue, oid.Value); Assert.Equal(friendlyName, oid.FriendlyName); } [Fact] public static void TestValueProperty() { Oid oid = new Oid(null, null); // Value property is just a field exposed as a property - no extra policy at all. oid.Value = "BOGUS"; Assert.Equal("BOGUS", oid.Value); oid.Value = null; Assert.Equal(null, oid.Value); } [Fact] public static void TestFriendlyNameProperty() { Oid oid; oid = new Oid(null, null); // Friendly name property can initialize itself from the Value (but only // if it was originally null.) oid.Value = SHA1_Oid; Assert.Equal(SHA1_Name, oid.FriendlyName); oid.Value = SHA256_Oid; Assert.Equal(SHA1_Name, oid.FriendlyName); oid.Value = null; Assert.Equal(SHA1_Name, oid.FriendlyName); oid.Value = Bogus_Name; Assert.Equal(SHA1_Name, oid.FriendlyName); // Setting the FriendlyName can also updates the value if there a valid OID for the new name. oid.FriendlyName = Bogus_Name; Assert.Equal(Bogus_Name, oid.FriendlyName); Assert.Equal(Bogus_Name, oid.Value); oid.FriendlyName = SHA1_Name; Assert.Equal(SHA1_Name, oid.FriendlyName); Assert.Equal(SHA1_Oid, oid.Value); oid.FriendlyName = SHA256_Name; Assert.Equal(SHA256_Name, oid.FriendlyName); Assert.Equal(SHA256_Oid, oid.Value); } [Theory] [MemberData(nameof(ValidOidFriendlyNameHashAlgorithmPairs))] public static void LookupOidByValue_Method_HashAlgorithm(string oidValue, string friendlyName) { Oid oid = Oid.FromOidValue(oidValue, OidGroup.HashAlgorithm); Assert.Equal(oidValue, oid.Value); Assert.Equal(friendlyName, oid.FriendlyName); } [Theory] [MemberData(nameof(ValidOidFriendlyNameEncryptionAlgorithmPairs))] public static void LookupOidByValue_Method_EncryptionAlgorithm(string oidValue, string friendlyName) { Oid oid = Oid.FromOidValue(oidValue, OidGroup.EncryptionAlgorithm); Assert.Equal(oidValue, oid.Value); Assert.Equal(friendlyName, oid.FriendlyName); } [Theory] [MemberData(nameof(ValidOidFriendlyNameHashAlgorithmPairs))] [PlatformSpecific(PlatformID.Windows)] public static void LookupOidByValue_Method_WrongGroup(string oidValue, string friendlyName) { // Oid group is implemented strictly - no fallback to OidGroup.All as with many other parts of Crypto. Assert.Throws<CryptographicException>(() => Oid.FromOidValue(oidValue, OidGroup.EncryptionAlgorithm)); } [Fact] public static void LookupOidByValue_Method_NullInput() { Assert.Throws<ArgumentNullException>(() => Oid.FromOidValue(null, OidGroup.HashAlgorithm)); } [Theory] [InlineData(SHA1_Name)] // Friendly names are not coerced into OID values from the method. [InlineData(Bogus_Name)] public static void LookupOidByValue_Method_BadInput(string badInput) { Assert.Throws<CryptographicException>(() => Oid.FromOidValue(badInput, OidGroup.HashAlgorithm)); } [Theory] [MemberData(nameof(ValidOidFriendlyNameHashAlgorithmPairs))] public static void LookupOidByFriendlyName_Method_HashAlgorithm(string oidValue, string friendlyName) { Oid oid = Oid.FromFriendlyName(friendlyName, OidGroup.HashAlgorithm); Assert.Equal(oidValue, oid.Value); Assert.Equal(friendlyName, oid.FriendlyName); } [Theory] [MemberData(nameof(ValidOidFriendlyNameEncryptionAlgorithmPairs))] public static void LookupOidByFriendlyName_Method_EncryptionAlgorithm(string oidValue, string friendlyName) { Oid oid = Oid.FromFriendlyName(friendlyName, OidGroup.EncryptionAlgorithm); Assert.Equal(oidValue, oid.Value); Assert.Equal(friendlyName, oid.FriendlyName); } [Theory] [MemberData(nameof(ValidOidFriendlyNamePairs))] public static void LookupOidByFriendlyName_Method_InverseCase(string oidValue, string friendlyName) { // Note that oid lookup is case-insensitive, and we store the name in the form it was // input to the constructor (rather than "normalizing" it to the official casing.) string inverseCasedName = InvertCase(friendlyName); Oid oid = Oid.FromFriendlyName(inverseCasedName, OidGroup.All); Assert.Equal(oidValue, oid.Value); Assert.Equal(inverseCasedName, oid.FriendlyName); } [Theory] [MemberData(nameof(ValidOidFriendlyNameHashAlgorithmPairs))] [PlatformSpecific(PlatformID.Windows)] public static void LookupOidByFriendlyName_Method_WrongGroup(string oidValue, string friendlyName) { // Oid group is implemented strictly - no fallback to OidGroup.All as with many other parts of Crypto. Assert.Throws<CryptographicException>(() => Oid.FromFriendlyName(friendlyName, OidGroup.EncryptionAlgorithm)); } [Fact] public static void LookupOidByFriendlyName_Method_NullInput() { Assert.Throws<ArgumentNullException>(() => Oid.FromFriendlyName(null, OidGroup.HashAlgorithm)); } [Theory] [InlineData(SHA1_Oid)] // OIDs are not coerced into friendly names values from the method. [InlineData(Bogus_Name)] public static void LookupOidByFriendlyName_Method_BadInput(string badInput) { Assert.Throws<CryptographicException>(() => Oid.FromFriendlyName(badInput, OidGroup.HashAlgorithm)); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public static void LookupOidByValue_Method_UnixOnly() { // This needs to be an OID not in the static lookup table. The purpose is to verify the // NativeOidToFriendlyName fallback for Unix. For Windows this is accomplished by // using FromOidValue with an OidGroup other than OidGroup.All. Oid oid = Oid.FromOidValue(ObsoleteSmime3desWrap_Oid, OidGroup.All); Assert.Equal(ObsoleteSmime3desWrap_Oid, oid.Value); Assert.Equal(ObsoleteSmime3desWrap_Name, oid.FriendlyName); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public static void LookupOidByFriendlyName_Method_UnixOnly() { // This needs to be a name not in the static lookup table. The purpose is to verify the // NativeFriendlyNameToOid fallback for Unix. For Windows this is accomplished by // using FromOidValue with an OidGroup other than OidGroup.All. Oid oid = Oid.FromFriendlyName(ObsoleteSmime3desWrap_Name, OidGroup.All); Assert.Equal(ObsoleteSmime3desWrap_Oid, oid.Value); Assert.Equal(ObsoleteSmime3desWrap_Name, oid.FriendlyName); } public static IEnumerable<string[]> ValidOidFriendlyNamePairs { get { List<string[]> data = new List<string[]>(ValidOidFriendlyNameHashAlgorithmPairs); data.AddRange(ValidOidFriendlyNameEncryptionAlgorithmPairs); return data; } } public static IEnumerable<string[]> ValidOidFriendlyNameHashAlgorithmPairs { get { return new[] { new[] { SHA1_Oid, SHA1_Name }, new[] { SHA256_Oid, SHA256_Name }, new[] { "1.2.840.113549.2.5", "md5" }, new[] { "2.16.840.1.101.3.4.2.2", "sha384" }, new[] { "2.16.840.1.101.3.4.2.3", "sha512" }, }; } } public static IEnumerable<string[]> ValidOidFriendlyNameEncryptionAlgorithmPairs { get { return new[] { new[] { "1.2.840.113549.3.7", "3des" }, }; } } private static string InvertCase(string existing) { char[] chars = existing.ToCharArray(); for (int i = 0; i < chars.Length; i++) { if (char.IsUpper(chars[i])) { chars[i] = char.ToLowerInvariant(chars[i]); } else if (char.IsLower(chars[i])) { chars[i] = char.ToUpperInvariant(chars[i]); } } return new string(chars); } private const string SHA1_Name = "sha1"; private const string SHA1_Oid = "1.3.14.3.2.26"; private const string SHA256_Name = "sha256"; private const string SHA256_Oid = "2.16.840.1.101.3.4.2.1"; private const string Bogus_Name = "BOGUS_BOGUS_BOGUS_BOGUS"; private const string ObsoleteSmime3desWrap_Oid = "1.2.840.113549.1.9.16.3.3"; private const string ObsoleteSmime3desWrap_Name = "id-smime-alg-3DESwrap"; } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.Text; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { internal interface ICodeModelService : ICodeModelNavigationPointService { /// <summary> /// Retrieves the Option nodes (i.e. VB Option statements) parented /// by the given node. /// </summary> IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent); /// <summary> /// Retrieves the import nodes (e.g. using/Import directives) parented /// by the given node. /// </summary> IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent); /// <summary> /// Retrieves the attributes parented or owned by the given node. /// </summary> IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent); /// <summary> /// Retrieves the attribute arguments parented by the given node. /// </summary> IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent); /// <summary> /// Retrieves the Inherits nodes (i.e. VB Inherits statements) parented /// or owned by the given node. /// </summary> IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent); /// <summary> /// Retrieves the Implements nodes (i.e. VB Implements statements) parented /// or owned by the given node. /// </summary> IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent); /// <summary> /// Retrieves the members of a specified <paramref name="container"/> node. The members that are /// returned can be controlled by passing various parameters. /// </summary> /// <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param> /// <param name="includeSelf">If true, the container is returned as well.</param> /// <param name="recursive">If true, members are recursed to return descendant members as well /// as immediate children. For example, a namespace would return the namespaces and types within. /// However, if <paramref name="recursive"/> is true, members with the namespaces and types would /// also be returned.</param> /// <param name="logicalFields">If true, field declarations are broken into their respective declarators. /// For example, the field "int x, y" would return two declarators, one for x and one for y in place /// of the field.</param> /// <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param> IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes); IEnumerable<SyntaxNode> GetLogicalSupportedMemberNodes(SyntaxNode container); SyntaxNodeKey GetNodeKey(SyntaxNode node); SyntaxNodeKey TryGetNodeKey(SyntaxNode node); SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree); bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node); bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope); string Language { get; } string AssemblyAttributeString { get; } /// <summary> /// Do not use this method directly! Instead, go through <see cref="FileCodeModel.GetOrCreateCodeElement{T}(SyntaxNode)"/> /// </summary> EnvDTE.CodeElement CreateInternalCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol); EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node); EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel); EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol); /// <summary> /// Used by RootCodeModel.CreateCodeTypeRef to create an EnvDTE.CodeTypeRef. /// </summary> EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type); EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol); string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol); string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol); bool IsParameterNode(SyntaxNode node); bool IsAttributeNode(SyntaxNode node); bool IsAttributeArgumentNode(SyntaxNode node); bool IsOptionNode(SyntaxNode node); bool IsImportNode(SyntaxNode node); ISymbol ResolveSymbol(Workspace workspace, ProjectId projectId, SymbolKey symbolId); string GetUnescapedName(string name); /// <summary> /// Retrieves the value to be returned from the EnvDTE.CodeElement.Name property. /// </summary> string GetName(SyntaxNode node); SyntaxNode GetNodeWithName(SyntaxNode node); SyntaxNode SetName(SyntaxNode node, string name); /// <summary> /// Retrieves the value to be returned from the EnvDTE.CodeElement.FullName property. /// </summary> string GetFullName(SyntaxNode node, SemanticModel semanticModel); /// <summary> /// Retrieves the value to be returned from the EnvDTE.CodeElement.FullName property for external code elements /// </summary> string GetFullName(ISymbol symbol); /// <summary> /// Given a name, attempts to convert it to a fully qualified name. /// </summary> string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel); void Rename(ISymbol symbol, string newName, Solution solution); SyntaxNode GetNodeWithModifiers(SyntaxNode node); SyntaxNode GetNodeWithType(SyntaxNode node); SyntaxNode GetNodeWithInitializer(SyntaxNode node); EnvDTE.vsCMAccess GetAccess(ISymbol symbol); EnvDTE.vsCMAccess GetAccess(SyntaxNode node); SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access); EnvDTE.vsCMElement GetElementKind(SyntaxNode node); bool IsAccessorNode(SyntaxNode node); MethodKind GetAccessorKind(SyntaxNode node); bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode); bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode); bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode); bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode); bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode); bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode); bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode); bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode); void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal); void GetInheritsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode inheritsNode, out string namespaceName, out int ordinal); void GetImplementsNamespaceAndOrdinal(SyntaxNode parentNode, SyntaxNode implementsNode, out string namespaceName, out int ordinal); void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index); void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal); SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode); string GetAttributeTarget(SyntaxNode attributeNode); string GetAttributeValue(SyntaxNode attributeNode); SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value); SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value); /// <summary> /// Given a node, finds the related node that holds on to the attribute information. /// Generally, this will be an ancestor node. For example, given a C# VariableDeclarator, /// looks up the syntax tree to find the FieldDeclaration. /// </summary> SyntaxNode GetNodeWithAttributes(SyntaxNode node); /// <summary> /// Given node for an attribute, returns a node that can represent the parent. /// For example, an attribute on a C# field cannot use the FieldDeclaration (as it is /// not keyed) but instead must use one of the FieldDeclaration's VariableDeclarators. /// </summary> SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node); SyntaxNode CreateAttributeNode(string name, string value, string target = null); SyntaxNode CreateAttributeArgumentNode(string name, string value); SyntaxNode CreateImportNode(string name, string alias = null); SyntaxNode CreateParameterNode(string name, string type); string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode); string GetImportAlias(SyntaxNode node); string GetImportNamespaceOrType(SyntaxNode node); string GetParameterName(SyntaxNode node); string GetParameterFullName(SyntaxNode node); EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node); SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind); IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parent); EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name); bool SupportsEventThrower { get; } bool GetCanOverride(SyntaxNode memberNode); SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value); EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind); string GetComment(SyntaxNode node); SyntaxNode SetComment(SyntaxNode node, string value); EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode); SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind); EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol); SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind); string GetDocComment(SyntaxNode node); SyntaxNode SetDocComment(SyntaxNode node, string value); EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol); EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol); SyntaxNode SetInheritanceKind(SyntaxNode node, EnvDTE80.vsCMInheritanceKind kind); bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol); SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value); bool GetIsConstant(SyntaxNode memberNode); SyntaxNode SetIsConstant(SyntaxNode memberNode, bool value); bool GetIsDefault(SyntaxNode propertyNode); SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value); bool GetIsGeneric(SyntaxNode memberNode); bool GetIsPropertyStyleEvent(SyntaxNode eventNode); bool GetIsShared(SyntaxNode memberNode, ISymbol symbol); SyntaxNode SetIsShared(SyntaxNode memberNode, bool value); bool GetMustImplement(SyntaxNode memberNode); SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value); EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode); SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind); EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode); SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol); Document Delete(Document document, SyntaxNode node); string GetMethodXml(SyntaxNode node, SemanticModel semanticModel); string GetInitExpression(SyntaxNode node); SyntaxNode AddInitExpression(SyntaxNode node, string value); CodeGenerationDestination GetDestination(SyntaxNode containerNode); /// <summary> /// Retrieves the Accessibility for an EnvDTE.vsCMAccess. If the specified value is /// EnvDTE.vsCMAccess.vsCMAccessDefault, then the SymbolKind and CodeGenerationDestination hints /// will be used to retrieve the correct Accessibility for the current language. /// </summary> Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified); bool GetWithEvents(EnvDTE.vsCMAccess access); /// <summary> /// Given an "type" argument received from a CodeModel client, converts it to an ITypeSymbol. Note that /// this parameter is a VARIANT and could be an EnvDTE.vsCMTypeRef, a string representing a fully-qualified /// type name, or an EnvDTE.CodeTypeRef. /// </summary> ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position); ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation); SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type); int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel); SyntaxNode InsertAttribute( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertAttributeArgument( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode attributeArgumentNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertImport( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode importNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertMember( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode newMemberNode, CancellationToken cancellationToken, out Document newDocument); SyntaxNode InsertParameter( Document document, bool batchMode, int insertionIndex, SyntaxNode containerNode, SyntaxNode parameterNode, CancellationToken cancellationToken, out Document newDocument); Document UpdateNode( Document document, SyntaxNode node, SyntaxNode newNode, CancellationToken cancellationToken); Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree); bool IsNamespace(SyntaxNode node); bool IsType(SyntaxNode node); IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel); bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel); Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken); Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken); string[] GetFunctionExtenderNames(); object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol); string[] GetPropertyExtenderNames(); object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol); string[] GetExternalTypeExtenderNames(); object GetExternalTypeExtender(string name, string externalLocation); string[] GetTypeExtenderNames(); object GetTypeExtender(string name, AbstractCodeType codeType); bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol); SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol); SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position); SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel); string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags); void AttachFormatTrackingToBuffer(ITextBuffer buffer); void DetachFormatTrackingToBuffer(ITextBuffer buffer); void EnsureBufferFormatted(ITextBuffer buffer); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; namespace System.Linq.Expressions { /// <summary> /// Represents an expression that applies a delegate or lambda expression to a list of argument expressions. /// </summary> [DebuggerTypeProxy(typeof(Expression.InvocationExpressionProxy))] public class InvocationExpression : Expression, IArgumentProvider { private readonly Expression _lambda; private readonly Type _returnType; internal InvocationExpression(Expression lambda, Type returnType) { _lambda = lambda; _returnType = returnType; } /// <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 sealed override Type Type { get { return _returnType; } } /// <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.Invoke; } } /// <summary> /// Gets the delegate or lambda expression to be applied. /// </summary> public Expression Expression { get { return _lambda; } } /// <summary> /// Gets the arguments that the delegate or lambda expression is applied to. /// </summary> public ReadOnlyCollection<Expression> Arguments { get { return GetOrMakeArguments(); } } /// <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="expression">The <see cref="Expression" /> property of the result.</param> /// <param name="arguments">The <see cref="Arguments" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public InvocationExpression Update(Expression expression, IEnumerable<Expression> arguments) { if (expression == Expression && arguments == Arguments) { return this; } return Expression.Invoke(expression, arguments); } internal virtual ReadOnlyCollection<Expression> GetOrMakeArguments() { throw ContractUtils.Unreachable; } public virtual Expression GetArgument(int index) { throw ContractUtils.Unreachable; } public virtual int ArgumentCount { get { throw ContractUtils.Unreachable; } } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitInvocation(this); } internal virtual InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { throw ContractUtils.Unreachable; } internal LambdaExpression LambdaOperand { get { return (_lambda.NodeType == ExpressionType.Quote) ? (LambdaExpression)((UnaryExpression)_lambda).Operand : (_lambda as LambdaExpression); } } } #region Specialized Subclasses internal class InvocationExpressionN : InvocationExpression { private IList<Expression> _arguments; public InvocationExpressionN(Expression lambda, IList<Expression> arguments, Type returnType) : base(lambda, returnType) { _arguments = arguments; } internal override ReadOnlyCollection<Expression> GetOrMakeArguments() { return ReturnReadOnly(ref _arguments); } public override Expression GetArgument(int index) { return _arguments[index]; } public override int ArgumentCount { get { return _arguments.Count; } } internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { Debug.Assert(lambda != null); Debug.Assert(arguments == null || arguments.Length == _arguments.Count); return Expression.Invoke(lambda, arguments ?? _arguments); } } internal class InvocationExpression0 : InvocationExpression { public InvocationExpression0(Expression lambda, Type returnType) : base(lambda, returnType) { } internal override ReadOnlyCollection<Expression> GetOrMakeArguments() { return EmptyReadOnlyCollection<Expression>.Instance; } public override Expression GetArgument(int index) { throw new InvalidOperationException(); } public override int ArgumentCount { get { return 0; } } internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { Debug.Assert(lambda != null); Debug.Assert(arguments == null || arguments.Length == 0); return Expression.Invoke(lambda); } } internal class InvocationExpression1 : InvocationExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider public InvocationExpression1(Expression lambda, Type returnType, Expression arg0) : base(lambda, returnType) { _arg0 = arg0; } internal override ReadOnlyCollection<Expression> GetOrMakeArguments() { return ReturnReadOnly(this, ref _arg0); } public override Expression GetArgument(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); default: throw new InvalidOperationException(); } } public override int ArgumentCount { get { return 1; } } internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { Debug.Assert(lambda != null); Debug.Assert(arguments == null || arguments.Length == 1); if (arguments != null) { return Expression.Invoke(lambda, arguments[0]); } return Expression.Invoke(lambda, ReturnObject<Expression>(_arg0)); } } internal class InvocationExpression2 : InvocationExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1; // storage for the 2nd arg public InvocationExpression2(Expression lambda, Type returnType, Expression arg0, Expression arg1) : base(lambda, returnType) { _arg0 = arg0; _arg1 = arg1; } internal override ReadOnlyCollection<Expression> GetOrMakeArguments() { return ReturnReadOnly(this, ref _arg0); } public override Expression GetArgument(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); case 1: return _arg1; default: throw new InvalidOperationException(); } } public override int ArgumentCount { get { return 2; } } internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { Debug.Assert(lambda != null); Debug.Assert(arguments == null || arguments.Length == 2); if (arguments != null) { return Expression.Invoke(lambda, arguments[0], arguments[1]); } return Expression.Invoke(lambda, ReturnObject<Expression>(_arg0), _arg1); } } internal class InvocationExpression3 : InvocationExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1; // storage for the 2nd arg private readonly Expression _arg2; // storage for the 3rd arg public InvocationExpression3(Expression lambda, Type returnType, Expression arg0, Expression arg1, Expression arg2) : base(lambda, returnType) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; } internal override ReadOnlyCollection<Expression> GetOrMakeArguments() { return ReturnReadOnly(this, ref _arg0); } public override Expression GetArgument(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); case 1: return _arg1; case 2: return _arg2; default: throw new InvalidOperationException(); } } public override int ArgumentCount { get { return 3; } } internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { Debug.Assert(lambda != null); Debug.Assert(arguments == null || arguments.Length == 3); if (arguments != null) { return Expression.Invoke(lambda, arguments[0], arguments[1], arguments[2]); } return Expression.Invoke(lambda, ReturnObject<Expression>(_arg0), _arg1, _arg2); } } internal class InvocationExpression4 : InvocationExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1; // storage for the 2nd arg private readonly Expression _arg2; // storage for the 3rd arg private readonly Expression _arg3; // storage for the 4th arg public InvocationExpression4(Expression lambda, Type returnType, Expression arg0, Expression arg1, Expression arg2, Expression arg3) : base(lambda, returnType) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; } internal override ReadOnlyCollection<Expression> GetOrMakeArguments() { return ReturnReadOnly(this, ref _arg0); } public override Expression GetArgument(int index) { switch (index) { case 0: return ReturnObject<Expression>(_arg0); case 1: return _arg1; case 2: return _arg2; case 3: return _arg3; default: throw new InvalidOperationException(); } } public override int ArgumentCount { get { return 4; } } internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { Debug.Assert(lambda != null); Debug.Assert(arguments == null || arguments.Length == 4); if (arguments != null) { return Expression.Invoke(lambda, arguments[0], arguments[1], arguments[2], arguments[3]); } return Expression.Invoke(lambda, ReturnObject<Expression>(_arg0), _arg1, _arg2, _arg3); } } internal class InvocationExpression5 : InvocationExpression { private object _arg0; // storage for the 1st argument or a readonly collection. See IArgumentProvider private readonly Expression _arg1; // storage for the 2nd arg private readonly Expression _arg2; // storage for the 3rd arg private readonly Expression _arg3; // storage for the 4th arg private readonly Expression _arg4; // storage for the 5th arg public InvocationExpression5(Expression lambda, Type returnType, Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) : base(lambda, returnType) { _arg0 = arg0; _arg1 = arg1; _arg2 = arg2; _arg3 = arg3; _arg4 = arg4; } internal override ReadOnlyCollection<Expression> GetOrMakeArguments() { return ReturnReadOnly(this, ref _arg0); } public override Expression GetArgument(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 new InvalidOperationException(); } } public override int ArgumentCount { get { return 5; } } internal override InvocationExpression Rewrite(Expression lambda, Expression[] arguments) { Debug.Assert(lambda != null); Debug.Assert(arguments == null || arguments.Length == 5); if (arguments != null) { return Expression.Invoke(lambda, arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]); } return Expression.Invoke(lambda, ReturnObject<Expression>(_arg0), _arg1, _arg2, _arg3, _arg4); } } #endregion public partial class Expression { ///<summary> ///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies a delegate or lambda expression with no arguments. ///</summary> ///<returns> ///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies the specified delegate or lambda expression. ///</returns> ///<param name="expression"> ///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate ///or lambda expression to be applied. ///</param> ///<exception cref="T:System.ArgumentNullException"> ///<paramref name="expression" /> is null.</exception> ///<exception cref="T:System.ArgumentException"> ///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.</exception> ///<exception cref="T:System.InvalidOperationException"> ///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception> internal static InvocationExpression Invoke(Expression expression) { // COMPAT: This method is marked as non-public to avoid a gap between a 0-ary and 2-ary overload (see remark for the unary case below). RequiresCanRead(expression, "expression"); var method = GetInvokeMethod(expression); var pis = GetParametersForValidation(method, ExpressionType.Invoke); ValidateArgumentCount(method, ExpressionType.Invoke, 0, pis); return new InvocationExpression0(expression, method.ReturnType); } ///<summary> ///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies a delegate or lambda expression to one argument expression. ///</summary> ///<returns> ///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies the specified delegate or lambda expression to the provided arguments. ///</returns> ///<param name="expression"> ///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate ///or lambda expression to be applied. ///</param> ///<param name="arg0"> ///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the first argument. ///</param> ///<exception cref="T:System.ArgumentNullException"> ///<paramref name="expression" /> is null.</exception> ///<exception cref="T:System.ArgumentException"> ///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an arugment expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception> ///<exception cref="T:System.InvalidOperationException"> ///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception> internal static InvocationExpression Invoke(Expression expression, Expression arg0) { // COMPAT: This method is marked as non-public to ensure compile-time compatibility for Expression.Invoke(e, null). RequiresCanRead(expression, "expression"); var method = GetInvokeMethod(expression); var pis = GetParametersForValidation(method, ExpressionType.Invoke); ValidateArgumentCount(method, ExpressionType.Invoke, 1, pis); arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0]); return new InvocationExpression1(expression, method.ReturnType, arg0); } ///<summary> ///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies a delegate or lambda expression to two argument expressions. ///</summary> ///<returns> ///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies the specified delegate or lambda expression to the provided arguments. ///</returns> ///<param name="expression"> ///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate ///or lambda expression to be applied. ///</param> ///<param name="arg0"> ///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the first argument. ///</param> ///<param name="arg1"> ///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the second argument. ///</param> ///<exception cref="T:System.ArgumentNullException"> ///<paramref name="expression" /> is null.</exception> ///<exception cref="T:System.ArgumentException"> ///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an arugment expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception> ///<exception cref="T:System.InvalidOperationException"> ///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception> internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1) { // NB: This method is marked as non-public to avoid public API additions at this point. RequiresCanRead(expression, "expression"); var method = GetInvokeMethod(expression); var pis = GetParametersForValidation(method, ExpressionType.Invoke); ValidateArgumentCount(method, ExpressionType.Invoke, 2, pis); arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0]); arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1]); return new InvocationExpression2(expression, method.ReturnType, arg0, arg1); } ///<summary> ///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies a delegate or lambda expression to three argument expressions. ///</summary> ///<returns> ///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies the specified delegate or lambda expression to the provided arguments. ///</returns> ///<param name="expression"> ///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate ///or lambda expression to be applied. ///</param> ///<param name="arg0"> ///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the first argument. ///</param> ///<param name="arg1"> ///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the second argument. ///</param> ///<param name="arg2"> ///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the third argument. ///</param> ///<exception cref="T:System.ArgumentNullException"> ///<paramref name="expression" /> is null.</exception> ///<exception cref="T:System.ArgumentException"> ///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an arugment expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception> ///<exception cref="T:System.InvalidOperationException"> ///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception> internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1, Expression arg2) { // NB: This method is marked as non-public to avoid public API additions at this point. RequiresCanRead(expression, "expression"); var method = GetInvokeMethod(expression); var pis = GetParametersForValidation(method, ExpressionType.Invoke); ValidateArgumentCount(method, ExpressionType.Invoke, 3, pis); arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0]); arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1]); arg2 = ValidateOneArgument(method, ExpressionType.Invoke, arg2, pis[2]); return new InvocationExpression3(expression, method.ReturnType, arg0, arg1, arg2); } ///<summary> ///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies a delegate or lambda expression to four argument expressions. ///</summary> ///<returns> ///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies the specified delegate or lambda expression to the provided arguments. ///</returns> ///<param name="expression"> ///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate ///or lambda expression to be applied. ///</param> ///<param name="arg0"> ///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the first argument. ///</param> ///<param name="arg1"> ///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the second argument. ///</param> ///<param name="arg2"> ///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the third argument. ///</param> ///<param name="arg3"> ///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the fourth argument. ///</param> ///<exception cref="T:System.ArgumentNullException"> ///<paramref name="expression" /> is null.</exception> ///<exception cref="T:System.ArgumentException"> ///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an arugment expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception> ///<exception cref="T:System.InvalidOperationException"> ///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception> internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1, Expression arg2, Expression arg3) { // NB: This method is marked as non-public to avoid public API additions at this point. RequiresCanRead(expression, "expression"); var method = GetInvokeMethod(expression); var pis = GetParametersForValidation(method, ExpressionType.Invoke); ValidateArgumentCount(method, ExpressionType.Invoke, 4, pis); arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0]); arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1]); arg2 = ValidateOneArgument(method, ExpressionType.Invoke, arg2, pis[2]); arg3 = ValidateOneArgument(method, ExpressionType.Invoke, arg3, pis[3]); return new InvocationExpression4(expression, method.ReturnType, arg0, arg1, arg2, arg3); } ///<summary> ///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies a delegate or lambda expression to five argument expressions. ///</summary> ///<returns> ///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies the specified delegate or lambda expression to the provided arguments. ///</returns> ///<param name="expression"> ///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate ///or lambda expression to be applied. ///</param> ///<param name="arg0"> ///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the first argument. ///</param> ///<param name="arg1"> ///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the second argument. ///</param> ///<param name="arg2"> ///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the third argument. ///</param> ///<param name="arg3"> ///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the fourth argument. ///</param> ///<param name="arg4"> ///The <see cref="T:System.Linq.Expressions.Expression" /> that represents the fifth argument. ///</param> ///<exception cref="T:System.ArgumentNullException"> ///<paramref name="expression" /> is null.</exception> ///<exception cref="T:System.ArgumentException"> ///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an arugment expression is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception> ///<exception cref="T:System.InvalidOperationException"> ///The number of arguments does not contain match the number of parameters for the delegate represented by <paramref name="expression" />.</exception> internal static InvocationExpression Invoke(Expression expression, Expression arg0, Expression arg1, Expression arg2, Expression arg3, Expression arg4) { // NB: This method is marked as non-public to avoid public API additions at this point. RequiresCanRead(expression, "expression"); var method = GetInvokeMethod(expression); var pis = GetParametersForValidation(method, ExpressionType.Invoke); ValidateArgumentCount(method, ExpressionType.Invoke, 5, pis); arg0 = ValidateOneArgument(method, ExpressionType.Invoke, arg0, pis[0]); arg1 = ValidateOneArgument(method, ExpressionType.Invoke, arg1, pis[1]); arg2 = ValidateOneArgument(method, ExpressionType.Invoke, arg2, pis[2]); arg3 = ValidateOneArgument(method, ExpressionType.Invoke, arg3, pis[3]); arg4 = ValidateOneArgument(method, ExpressionType.Invoke, arg4, pis[4]); return new InvocationExpression5(expression, method.ReturnType, arg0, arg1, arg2, arg3, arg4); } ///<summary> ///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies a delegate or lambda expression to a list of argument expressions. ///</summary> ///<returns> ///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies the specified delegate or lambda expression to the provided arguments. ///</returns> ///<param name="expression"> ///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate ///or lambda expression to be applied. ///</param> ///<param name="arguments"> ///An array of <see cref="T:System.Linq.Expressions.Expression" /> objects ///that represent the arguments that the delegate or lambda expression is applied to. ///</param> ///<exception cref="T:System.ArgumentNullException"> ///<paramref name="expression" /> is null.</exception> ///<exception cref="T:System.ArgumentException"> ///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an element of <paramref name="arguments" /> is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception> ///<exception cref="T:System.InvalidOperationException"> ///<paramref name="arguments" /> does not contain the same number of elements as the list of parameters for the delegate represented by <paramref name="expression" />.</exception> public static InvocationExpression Invoke(Expression expression, params Expression[] arguments) { return Invoke(expression, (IEnumerable<Expression>)arguments); } ///<summary> ///Creates an <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies a delegate or lambda expression to a list of argument expressions. ///</summary> ///<returns> ///An <see cref="T:System.Linq.Expressions.InvocationExpression" /> that ///applies the specified delegate or lambda expression to the provided arguments. ///</returns> ///<param name="expression"> ///An <see cref="T:System.Linq.Expressions.Expression" /> that represents the delegate ///or lambda expression to be applied. ///</param> ///<param name="arguments"> ///An <see cref="T:System.Collections.Generic.IEnumerable`1" /> of <see cref="T:System.Linq.Expressions.Expression" /> objects ///that represent the arguments that the delegate or lambda expression is applied to. ///</param> ///<exception cref="T:System.ArgumentNullException"> ///<paramref name="expression" /> is null.</exception> ///<exception cref="T:System.ArgumentException"> ///<paramref name="expression" />.Type does not represent a delegate type or an <see cref="T:System.Linq.Expressions.Expression`1" />.-or-The <see cref="P:System.Linq.Expressions.Expression.Type" /> property of an element of <paramref name="arguments" /> is not assignable to the type of the corresponding parameter of the delegate represented by <paramref name="expression" />.</exception> ///<exception cref="T:System.InvalidOperationException"> ///<paramref name="arguments" /> does not contain the same number of elements as the list of parameters for the delegate represented by <paramref name="expression" />.</exception> public static InvocationExpression Invoke(Expression expression, IEnumerable<Expression> arguments) { var argumentList = arguments as IReadOnlyList<Expression>; if (argumentList != null) { switch (argumentList.Count) { case 0: return Invoke(expression); case 1: return Invoke(expression, argumentList[0]); case 2: return Invoke(expression, argumentList[0], argumentList[1]); case 3: return Invoke(expression, argumentList[0], argumentList[1], argumentList[2]); case 4: return Invoke(expression, argumentList[0], argumentList[1], argumentList[2], argumentList[3]); case 5: return Invoke(expression, argumentList[0], argumentList[1], argumentList[2], argumentList[3], argumentList[4]); } } RequiresCanRead(expression, "expression"); var args = arguments.ToReadOnly(); var mi = GetInvokeMethod(expression); ValidateArgumentTypes(mi, ExpressionType.Invoke, ref args); return new InvocationExpressionN(expression, args, mi.ReturnType); } /// <summary> /// Gets the delegate's Invoke method; used by InvocationExpression. /// </summary> /// <param name="expression">The expression to be invoked.</param> internal static MethodInfo GetInvokeMethod(Expression expression) { Type delegateType = expression.Type; if (!expression.Type.IsSubclassOf(typeof(MulticastDelegate))) { Type exprType = TypeUtils.FindGenericType(typeof(Expression<>), expression.Type); if (exprType == null) { throw Error.ExpressionTypeNotInvocable(expression.Type); } delegateType = exprType.GetGenericArguments()[0]; } return delegateType.GetMethod("Invoke"); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // //TODO: Figure out why USE_EMIT is not working //#define TRANSFORMATIONCONTEXT__USE_EMIT //#define TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER namespace Microsoft.Zelig.CodeGeneration.IR { using System; using System.Collections.Generic; #if TRANSFORMATIONCONTEXT__USE_EMIT using System.Reflection; using System.Reflection.Emit; #endif using Microsoft.Zelig.Runtime.TypeSystem; public abstract class TransformationContextForCodeTransformation : TransformationContextForIR { // // State // #if !TRANSFORMATIONCONTEXT__USE_EMIT private GrowOnlyHashTable< Type, System.Reflection.MethodInfo > m_handlers; #endif // // Helper Methods // public abstract void Transform( ref TypeSystemForCodeTransformation typeSystem ); public abstract void Transform( ref StackLocationExpression.Placement val ); public abstract void Transform( ref ConditionCodeExpression.Comparison val ); public abstract void Transform( ref PiOperator.Relation val ); public abstract void Transform( ref DataManager dataManager ); public abstract void Transform( ref DataManager.Attributes val ); public abstract void Transform( ref DataManager.ObjectDescriptor od ); public abstract void Transform( ref DataManager.ArrayDescriptor ad ); public abstract void Transform( ref ImageBuilders.Core imageBuilder ); public abstract void Transform( ref ImageBuilders.CompilationState cs ); public abstract void Transform( ref ImageBuilders.SequentialRegion reg ); public abstract void Transform( ref ImageBuilders.ImageAnnotation an ); public abstract void Transform( ref ImageBuilders.CodeConstant cc ); public abstract void Transform( ref ImageBuilders.SequentialRegion[] regArray ); public abstract void Transform( ref List< ImageBuilders.SequentialRegion > regLst ); public abstract void Transform( ref List< ImageBuilders.ImageAnnotation > anLst ); public abstract void Transform( ref List< ImageBuilders.CodeConstant > ccLst ); public abstract void Transform( ref List< Runtime.Memory.Range > mrLst ); public abstract void Transform( ref Runtime.MemoryAttributes val ); public abstract void Transform( ref Runtime.MemoryAttributes[] maArray ); public abstract void Transform( ref Runtime.MemoryUsage val ); public abstract void Transform( ref Runtime.MemoryUsage[] muArray ); public abstract void Transform( ref Abstractions.PlacementRequirements pr ); public abstract void Transform( ref Abstractions.RegisterDescriptor regDesc ); public abstract void Transform( ref Abstractions.RegisterDescriptor[] regDescArray ); public abstract void Transform( ref Abstractions.RegisterClass val ); public abstract void Transform( ref Abstractions.CallingConvention.Direction val ); //--// public void Transform( ref GrowOnlyHashTable< string, object > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< Expression, Expression[] > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< object, ConstantExpression > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< TypeRepresentation, GrowOnlyHashTable< object, ConstantExpression > > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< TypeRepresentation, List< ConstantExpression > > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< BaseRepresentation, InstanceFieldRepresentation > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< TypeRepresentation, CustomAttributeRepresentation > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< FieldRepresentation, CustomAttributeRepresentation > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< MethodRepresentation, CustomAttributeRepresentation > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< TypeRepresentation, TypeRepresentation > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< object, DataManager.DataDescriptor > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< ControlFlowGraphStateForCodeTransformation, ImageBuilders.CompilationState > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< object, List< ImageBuilders.CodeConstant > > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable<ExternalDataDescriptor.IExternalDataContext, ImageBuilders.SequentialRegion> ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable<DataManager.DataDescriptor, ImageBuilders.SequentialRegion> ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< BaseRepresentation, Abstractions.PlacementRequirements > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< object, int > ht ) { TransformValueTypeContents( ht ); } public void Transform( ref GrowOnlyHashTable< string, SourceCodeTracker.SourceCode > ht ) { TransformContents( ht ); } public void Transform( ref GrowOnlyHashTable< FieldRepresentation, BitFieldDefinition > ht ) { TransformContents( ht ); } //--// #if !TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER [System.Diagnostics.DebuggerHidden] #endif protected override object TransformGenericReference( object obj ) { if(obj is TypeSystemForCodeTransformation) { TypeSystemForCodeTransformation target = (TypeSystemForCodeTransformation)obj; Transform( ref target ); return target; } return base.TransformGenericReference( obj ); } //--// protected override DynamicTransform BuildDynamicTransform() { if(m_dynamicTransform == null) { #if TRANSFORMATIONCONTEXT__USE_EMIT GrowOnlyHashTable< Type, System.Reflection.MethodInfo > ht = GetMethodInfoTable(); List< Type > lst = new List< Type >(); TreeNode tnClassType = new TreeNode( typeof(object ) ); TreeNode tnValueType = new TreeNode( typeof(ValueType) ); foreach(var t in ht.Keys) { TreeNode node = new TreeNode( t ); node.m_method = ht[t]; if(t.IsValueType) { tnValueType.Insert( node ); } else { tnClassType.Insert( node ); } } tnClassType.Normalize(); tnValueType.Normalize(); //--// DynamicMethod methodBuilder = new DynamicMethod( "TransformDecoder", typeof(object), new Type[] { typeof(TransformationContext), typeof(object), typeof(Type) }, true ); ILGenerator il = methodBuilder.GetILGenerator( 256 ); //// il.EmitWriteLine( "Starting check:" ); if(tnValueType.GetNumberOfTerminalNodes() > 0) { tnValueType.Emit( il, true ); } if(tnClassType.GetNumberOfTerminalNodes() > 0) { tnClassType.Emit( il, false ); } m_dynamicTransform = (DynamicTransform)methodBuilder.CreateDelegate( typeof(DynamicTransform) ); #else m_dynamicTransform = TransformThroughInvoke; #endif } return m_dynamicTransform; } //--// #if TRANSFORMATIONCONTEXT__USE_EMIT class TreeNode { // // State // internal Type m_type; internal System.Reflection.MethodInfo m_method; internal List< TreeNode > m_children = new List< TreeNode >(); // // Constructor Methods // internal TreeNode( Type t ) { m_type = t; } // // Helper Methods // internal bool IsSubclassOf( TreeNode node ) { return m_type.IsSubclassOf( node.m_type ); } internal void Insert( TreeNode newNode ) { // // First, relocate all the node that are subclasses of the new node under it. // for(int i = 0; i < m_children.Count; i++) { var child = m_children[i]; if(child.IsSubclassOf( newNode )) { newNode.m_children.Add( child ); m_children.RemoveAt( i-- ); return; } } // // Then, add the node here. // m_children.Add( newNode ); } internal void Normalize() { for(int i = 0; i < m_children.Count; i++) { var child = m_children[i]; var parent = child.m_type.BaseType; if(parent != null && parent != m_type) { foreach(var child2 in m_children) { if(child2.m_type == parent) { child2.m_children.Add( child ); m_children.RemoveAt( i-- ); child = null; break; } } if(child != null) { TreeNode sub = new TreeNode( parent ); m_children[i] = sub; sub.m_children.Add( child ); } } } } internal int GetNumberOfTerminalNodes() { int num = m_method != null ? 1 : 0; foreach(var child in m_children) { num += child.GetNumberOfTerminalNodes(); } return num; } internal delegate Type GetTypeFromHandleDlg( RuntimeTypeHandle handle ); internal void Emit( ILGenerator il , bool fPerformCheck ) { if(fPerformCheck) { if(m_children.Count == 1) { m_children[0].Emit( il, true ); return; } } Label label = il.DefineLabel(); if(fPerformCheck) { //// il.EmitWriteLine( "Checking for: " + m_type.FullName ); if(m_type.IsArray || m_type == typeof(Array)) { GetTypeFromHandleDlg dlg = Type.GetTypeFromHandle; il.Emit( OpCodes.Ldtoken, m_type ); il.Emit( OpCodes.Call, dlg.Method ); il.Emit( OpCodes.Ldarg_2 ); il.Emit( OpCodes.Bne_Un, label ); } else { il.Emit( OpCodes.Ldarg_1 ); il.Emit( OpCodes.Isinst , m_type ); il.Emit( OpCodes.Brfalse, label ); } } foreach(var child in m_children) { child.Emit( il, true ); } if(m_method != null) { System.Reflection.ParameterInfo[] parameters = m_method.GetParameters(); System.Reflection.ParameterInfo paramInfo = parameters[0]; Type paramType = paramInfo.ParameterType; Type elementType = paramType.GetElementType(); LocalBuilder objectRef = il.DeclareLocal( elementType ); il.Emit( OpCodes.Ldarg_1 ); il.Emit( OpCodes.Unbox_Any, elementType ); il.Emit( OpCodes.Stloc, objectRef ); if(m_method.IsStatic == false) { il.Emit( OpCodes.Ldarg_0 ); il.Emit( OpCodes.Castclass, m_method.DeclaringType ); } il.Emit( OpCodes.Ldloca, objectRef ); il.EmitCall( OpCodes.Callvirt, m_method, null ); il.Emit( OpCodes.Ldloc, objectRef ); if(elementType.IsValueType) { il.Emit( OpCodes.Box, elementType ); } } else { //il.EmitWriteLine( "No method for: " + m_type.FullName ); // // In case of failure to find a target transform, return the transform context, so the caller will know nothing got selected. // il.Emit( OpCodes.Ldarg_0 ); } il.Emit( OpCodes.Ret ); if(fPerformCheck) { il.MarkLabel( label ); //// il.EmitWriteLine( "Check failed" ); } } } #else private static object TransformThroughInvoke( TransformationContext context , object obj , Type t ) { TransformationContextForCodeTransformation pThis = (TransformationContextForCodeTransformation)context; System.Reflection.MethodInfo mi; mi = pThis.GetAssociatedTransform( obj, true ); if(mi != null) { return pThis.CallTransformMethod( mi, obj ); } if(obj is Array) { Array array = (Array)obj; pThis.TransformArray( ref array ); return array; } mi = pThis.GetAssociatedTransform( obj, false ); if(mi != null) { return pThis.CallTransformMethod( mi, obj ); } return context; } #if !TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER [System.Diagnostics.DebuggerHidden] #endif protected System.Reflection.MethodInfo GetAssociatedTransform( object obj , bool fExact ) { if(m_handlers == null) { m_handlers = GetMethodInfoTable(); } System.Reflection.MethodInfo res; Type src = obj != null ? obj.GetType() : typeof(object); while(src != null) { if(m_handlers.TryGetValue( src, out res )) { return res; } if(fExact) break; src = src.BaseType; } return null; } #if !TRANSFORMATIONCONTEXT_SHOWALLMETHODSTODEBUGGER [System.Diagnostics.DebuggerHidden] #endif protected object CallTransformMethod( System.Reflection.MethodInfo mi , object obj ) { object[] parameters = new object[] { obj }; mi.Invoke( this, parameters ); return parameters[0]; } #endif } }