context
stringlengths
2.52k
185k
gt
stringclasses
1 value
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Web; using Adxstudio.Xrm.Cms; using Adxstudio.Xrm.Core.Flighting; using Adxstudio.Xrm.Feedback; using Adxstudio.Xrm.Resources; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Security; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; using Adxstudio.Xrm.Text; using Microsoft.Xrm.Client.Messages; using Microsoft.Xrm.Portal.Web; namespace Adxstudio.Xrm.Issues { /// <summary> /// Provides methods to get and set data for an Adxstudio Portals Issue such as comments. /// </summary> public class IssueDataAdapter : IIssueDataAdapter, ICommentDataAdapter { private bool? _hasCommentModerationPermission; /// <summary> /// Constructor. /// </summary> /// <param name="issue">The issue to get and set data for.</param> /// <param name="dependencies">The dependencies to use for getting and setting data.</param> public IssueDataAdapter(EntityReference issue, IDataAdapterDependencies dependencies) { issue.ThrowOnNull("issue"); issue.AssertLogicalName("adx_issue"); dependencies.ThrowOnNull("dependencies"); Issue = issue; Dependencies = dependencies; } /// <summary> /// Constructor. /// </summary> /// <param name="issue">The issue to get and set data for.</param> /// <param name="dependencies">The dependencies to use for getting and setting data.</param> public IssueDataAdapter(Entity issue, IDataAdapterDependencies dependencies) : this(issue.ToEntityReference(), dependencies) { } /// <summary> /// Constructor. /// </summary> /// <param name="issue">The issue to get and set data for.</param> /// <param name="dependencies">The dependencies to use for getting and setting data.</param> public IssueDataAdapter(IIssue issue, IDataAdapterDependencies dependencies) : this(issue.Entity, dependencies) { } /// <summary> /// Constructor. /// </summary> /// <param name="issue">The issue to get and set data for.</param> /// <param name="portalName">The configured name of the portal to get and set data for.</param> public IssueDataAdapter(EntityReference issue, string portalName = null) : this(issue, new PortalConfigurationDataAdapterDependencies(portalName)) { } /// <summary> /// Constructor. /// </summary> /// <param name="issue">The issue to get and set data for.</param> /// <param name="portalName">The configured name of the portal to get and set data for.</param> public IssueDataAdapter(Entity issue, string portalName = null) : this(issue.ToEntityReference(), portalName) { } /// <summary> /// Constructor. /// </summary> /// <param name="issue">The issue to get and set data for.</param> /// <param name="portalName">The configured name of the portal to get and set data for.</param> public IssueDataAdapter(IIssue issue, string portalName = null) : this(issue.Entity, portalName) { } protected EntityReference Issue { get; private set; } protected IDataAdapterDependencies Dependencies { get; private set; } /// <summary> /// Gets or sets whether or not comments should be in chronological order (default false [reverse chronological]). /// </summary> public bool? ChronologicalComments { get; set; } /// <summary> /// Create an issue alert entity (subscription) for the user. /// </summary> /// <param name="user">The user to create an issue alert entity (subsciption) for.</param> public void CreateAlert(EntityReference user) { user.ThrowOnNull("user"); if (user.LogicalName != "contact") { throw new ArgumentException(string.Format("Value must have logical name {0}.", user.LogicalName), "user"); } var serviceContext = Dependencies.GetServiceContextForWrite(); var existingAlert = GetIssueAlertEntity(serviceContext, user); if (existingAlert != null) { return; } var alert = new Entity("adx_issuealert"); alert["adx_subscriberid"] = user; alert["adx_issueid"] = Issue; serviceContext.AddObject(alert); serviceContext.SaveChanges(); } /// <summary> /// Post a comment for the issue this adapter applies to. /// </summary> /// <param name="content">The comment copy.</param> /// <param name="authorName">The name of the author for this comment (ignored if user is authenticated).</param> /// <param name="authorEmail">The email of the author for this comment (ignored if user is authenticated).</param> public virtual void CreateComment(string content, string authorName = null, string authorEmail = null) { content.ThrowOnNullOrWhitespace("content"); var httpContext = Dependencies.GetHttpContext(); var author = Dependencies.GetPortalUser(); if (!httpContext.Request.IsAuthenticated || author == null) { authorName.ThrowOnNullOrWhitespace("authorName", string.Format(ResourceManager.GetString("Error_Creating_IdeaAndIssue_Comment_WithNullOrWhitespace"), "issue comment")); authorEmail.ThrowOnNullOrWhitespace("authorEmail", string.Format(ResourceManager.GetString("Error_Creating_IdeaAndIssue_Comment_WithNullOrWhitespace"), "issue comment")); } var context = Dependencies.GetServiceContext(); var issue = Select(); if (!issue.CurrentUserCanComment) { throw new InvalidOperationException("An issue comment can't be created with the current issue comment policy."); } var comment = new Entity("feedback"); comment["title"] = StringHelper.GetCommentTitleFromContent(content); comment["comments"] = content; comment["regardingobjectid"] = Issue; comment["createdon"] = DateTime.UtcNow; comment["adx_approved"] = issue.CommentPolicy != IssueForumCommentPolicy.Moderated; comment["adx_createdbycontact"] = authorName; comment["adx_contactemail"] = authorEmail; comment["source"] = new OptionSetValue((int)FeedbackSource.Portal); if (author != null && author.LogicalName == "contact") { comment[FeedbackMetadataAttributes.UserIdAttributeName] = author; } else if (context != null) { comment[FeedbackMetadataAttributes.VisitorAttributeName] = httpContext.Profile.UserName; } context.AddObject(comment); context.SaveChanges(); if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage)) { PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Issue, HttpContext.Current, "create_comment_issue", 1, comment.ToEntityReference(), "create"); } } /// <summary> /// Delete an issue alert entity (subscription) for the user. /// </summary> /// <param name="user">The user to remove an issue alert entity (subsciption) for.</param> public void DeleteAlert(EntityReference user) { user.ThrowOnNull("user"); var serviceContext = Dependencies.GetServiceContextForWrite(); var existingAlert = GetIssueAlertEntity(serviceContext, user); if (existingAlert == null) { return; } serviceContext.DeleteObject(existingAlert); serviceContext.SaveChanges(); } /// <summary> /// Gets attributes to be added to a new comment that has just been created. Likely from the CrmEntityFormView. /// </summary> public IDictionary<string, object> GetCommentAttributes(string content, string authorName = null, string authorEmail = null, string authorUrl = null, HttpContext httpContext = null) { var issue = Select(); if (issue == null) { throw new InvalidOperationException("Unable to load adx_issue entity with ID {0}. Make sure that this record exists and is accessible by the current user.".FormatWith(Issue.Id)); } var postedOn = DateTime.UtcNow; var attributes = new Dictionary<string, object> { { "regardingobjectid", Issue }, { "createdon", postedOn }, { "title", StringHelper.GetCommentTitleFromContent(content) }, { "adx_approved", issue.CommentPolicy == IssueForumCommentPolicy.Open || issue.CommentPolicy == IssueForumCommentPolicy.OpenToAuthenticatedUsers }, { "adx_createdbycontact", authorName }, { "adx_contactemail", authorEmail }, { "comments", content }, }; var portalUser = Dependencies.GetPortalUser(); if (portalUser != null && portalUser.LogicalName == "contact") { attributes[FeedbackMetadataAttributes.UserIdAttributeName] = portalUser; } else if (httpContext != null && httpContext.Profile != null) { attributes[FeedbackMetadataAttributes.VisitorAttributeName] = httpContext.Profile.UserName; } return attributes; } public string GetCommentContentAttributeName() { return "comments"; } public string GetCommentLogicalName() { return "feedback"; } public ICommentPolicyReader GetCommentPolicyReader() { var issue = Select(); return new IssueCommentPolicyReader(issue); } /// <summary> /// Returns whether or not an issue alert entity (subscription) exists for the user. /// </summary> public bool HasAlert() { var user = Dependencies.GetPortalUser(); if (user == null) { return false; } return GetIssueAlertEntity(Dependencies.GetServiceContext(), user) != null; } /// <summary> /// Returns the <see cref="IIssue"/> that this adapter applies to. /// </summary> public virtual IIssue Select() { var serviceContext = Dependencies.GetServiceContext(); var issue = GetIssueEntity(serviceContext); return new IssueFactory(serviceContext, Dependencies.GetHttpContext()).Create(new[] { issue }).FirstOrDefault(); } public virtual IEnumerable<IComment> SelectComments() { return SelectComments(0); } /// <summary> /// Returns comments that have been posted for the issue this adapter applies to. /// </summary> /// <param name="startRowIndex">The row index of the first comment to be returned.</param> /// <param name="maximumRows">The maximum number of comments to return.</param> public virtual IEnumerable<IComment> SelectComments(int startRowIndex, int maximumRows = -1) { var comments = new List<Comment>(); if (!FeatureCheckHelper.IsFeatureEnabled(FeatureNames.Feedback) || maximumRows == 0) { return comments; } var includeUnapprovedComments = TryAssertCommentModerationPermission(Dependencies.GetServiceContext()); var query = Cms.OrganizationServiceContextExtensions.SelectCommentsByPage( Cms.OrganizationServiceContextExtensions.GetPageInfo(startRowIndex, maximumRows), Issue.Id, includeUnapprovedComments); var commentsEntitiesResult = Dependencies.GetServiceContext().RetrieveMultiple(query); comments.AddRange( commentsEntitiesResult.Entities.Select( commentEntity => new Comment(commentEntity, new Lazy<ApplicationPath>(() => Dependencies.GetEditPath(commentEntity.ToEntityReference()), LazyThreadSafetyMode.None), new Lazy<ApplicationPath>(() => Dependencies.GetDeletePath(commentEntity.ToEntityReference()), LazyThreadSafetyMode.None), new Lazy<bool>(() => includeUnapprovedComments, LazyThreadSafetyMode.None)))); return comments; } /// <summary> /// Returns the number of comments that have been posted for the issue this adapter applies to. /// </summary> public virtual int SelectCommentCount() { var serviceContext = Dependencies.GetServiceContext(); var includeUnapprovedComments = TryAssertCommentModerationPermission(serviceContext); return serviceContext.FetchCount("feedback", "feedbackid", addCondition => { addCondition("regardingobjectid", "eq", Issue.Id.ToString()); if (!includeUnapprovedComments) { addCondition("adx_approved", "eq", "true"); } }); } protected virtual bool TryAssertCommentModerationPermission(OrganizationServiceContext serviceContext) { if (_hasCommentModerationPermission.HasValue) { return _hasCommentModerationPermission.Value; } var security = Dependencies.GetSecurityProvider(); _hasCommentModerationPermission = security.TryAssert(serviceContext, GetIssueEntity(serviceContext), CrmEntityRight.Change); return _hasCommentModerationPermission.Value; } private Entity GetIssueAlertEntity(OrganizationServiceContext serviceContext, EntityReference user) { serviceContext.ThrowOnNull("serviceContext"); user.ThrowOnNull("user"); return serviceContext.CreateQuery("adx_issuealert") .FirstOrDefault(e => e.GetAttributeValue<EntityReference>("adx_subscriberid") == user && e.GetAttributeValue<EntityReference>("adx_issueid") == Issue); } private Entity GetIssueEntity(OrganizationServiceContext serviceContext) { var issue = serviceContext.CreateQuery("adx_issue") .FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_issueid") == Issue.Id); if (issue == null) { throw new InvalidOperationException(string.Format("Can't find {0} having ID {1}.", "adx_issue", Issue.Id)); } return issue; } } }
using System; using System.Collections.Generic; using ProtoCore.DSASM; using ProtoCore.Utils; namespace ProtoCore { namespace Runtime { public class RuntimeMemory { public Executable Executable { get; set; } // TODO Jun: Handle classes. This is part of the classes in global scope refactor public ClassTable ClassTable { get; set; } public int FramePointer { get; set; } public List<StackValue> Stack { get; set; } public List<int> ConstructBlockIds { get; private set; } public Heap Heap { get; private set; } // Keep track of modified symbols during an execution cycle // TODO Jun: Turn this into a multi-key dictionary where the keys are: name, classindex and procindex public Dictionary<string, SymbolNode> mapModifiedSymbols { get; private set; } public RuntimeMemory() { FramePointer = 0; Executable = null; Stack = new List<StackValue>(); Heap = null; mapModifiedSymbols = new Dictionary<string, SymbolNode>(); } public RuntimeMemory(Heap heap) { FramePointer = 0; Executable = null; Stack = new List<StackValue>(); ConstructBlockIds = new List<int>(); Heap = heap; StackRestorer = new StackAlignToFramePointerRestorer(); mapModifiedSymbols = new Dictionary<string, SymbolNode>(); } private void UpdateModifiedSymbols(SymbolNode symbol) { Validity.Assert(null != symbol); Validity.Assert(!string.IsNullOrEmpty(symbol.name)); Validity.Assert(null != mapModifiedSymbols); // TODO Jun: Turn this into a multi-key dictionary where the keys are: name, classindex and procindex string key = symbol.name; if (!mapModifiedSymbols.ContainsKey(key)) { mapModifiedSymbols.Add(key, symbol); } } public void ResetModifedSymbols() { Validity.Assert(null != mapModifiedSymbols); mapModifiedSymbols.Clear(); } public List<string> GetModifiedSymbolString() { List<string> nameList = new List<string>(); foreach (KeyValuePair<string, SymbolNode> kvp in mapModifiedSymbols) { nameList.Add(kvp.Key); } return nameList; } public void ReAllocateMemory(int delta) { // // Comment Jun: // This modifies the current stack and heap to accomodate delta statements PushGlobFrame(delta); } public int GetRelative(int index) { return index >= 0 ? index : FramePointer + index; } public int GetRelative(int offset, int index) { return index >= 0 ? index : (FramePointer - offset) + index; } public void PushGlobFrame(int globsize) { for (int n = 0; n < globsize; ++n) { Stack.Add(StackUtils.BuildNull()); } } private void PushFrame(int size) { for (int n = 0; n < size; ++n) { Stack.Add(StackUtils.BuildNull()); } } private void PushFrame(List<StackValue> stackData) { if (null != stackData && stackData.Count > 0) { Stack.AddRange(stackData); } } public void PushStackFrame(int ptr, int classIndex, int funcIndex, int pc, int functionBlockDecl, int functionBlockCaller, StackFrameType callerType, StackFrameType type, int depth, int fp, List<StackValue> registers, int locsize, int executionStates) { // TODO Jun: Performance // Push frame should only require adjusting the frame index instead of pushing dummy elements PushFrame(locsize); Push(StackUtils.BuildInt(fp)); PushRegisters(registers); Push(StackUtils.BuildNode(AddressType.Int, executionStates)); Push(StackUtils.BuildNode(AddressType.Int, 0)); Push(StackUtils.BuildNode(AddressType.Int, depth)); Push(StackUtils.BuildNode(AddressType.FrameType, (int)type)); Push(StackUtils.BuildNode(AddressType.FrameType, (int)callerType)); Push(StackUtils.BuildNode(AddressType.BlockIndex, functionBlockCaller)); Push(StackUtils.BuildNode(AddressType.BlockIndex, functionBlockDecl)); Push(StackUtils.BuildInt(pc)); Push(StackUtils.BuildInt(funcIndex)); Push(StackUtils.BuildInt(classIndex)); Push(StackUtils.BuildPointer(ptr)); FramePointer = Stack.Count; } public void PushStackFrame(StackValue svThisPtr, int classIndex, int funcIndex, int pc, int functionBlockDecl, int functionBlockCaller, StackFrameType callerType, StackFrameType type, int depth, int fp, List<StackValue> registers, int locsize, int executionStates) { // TODO Jun: Performance // Push frame should only require adjusting the frame index instead of pushing dummy elements PushFrame(locsize); Push(StackUtils.BuildInt(fp)); PushRegisters(registers); Push(StackUtils.BuildNode(AddressType.Int, executionStates)); Push(StackUtils.BuildNode(AddressType.Int, 0)); Push(StackUtils.BuildNode(AddressType.Int, depth)); Push(StackUtils.BuildNode(AddressType.FrameType, (int)type)); Push(StackUtils.BuildNode(AddressType.FrameType, (int)callerType)); Push(StackUtils.BuildNode(AddressType.BlockIndex, functionBlockCaller)); Push(StackUtils.BuildNode(AddressType.BlockIndex, functionBlockDecl)); Push(StackUtils.BuildInt(pc)); Push(StackUtils.BuildInt(funcIndex)); Push(StackUtils.BuildInt(classIndex)); Push(svThisPtr); FramePointer = Stack.Count; } public void PushStackFrame(StackFrame stackFrame, int localSize, int executionStates) { // TODO Jun: Performance // Push frame should only require adjusting the frame index instead of pushing dummy elements Validity.Assert(StackFrame.kStackFrameSize == stackFrame.Frame.Length); PushFrame(localSize); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kFramePointer]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kRegisterTX]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kRegisterSX]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kRegisterRX]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kRegisterLX]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kRegisterFX]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kRegisterEX]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kRegisterDX]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kRegisterCX]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kRegisterBX]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kRegisterAX]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kExecutionStates]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kLocalVariables]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kStackFrameDepth]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kStackFrameType]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kCallerStackFrameType]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kFunctionCallerBlock]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kFunctionBlock]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kReturnAddress]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kFunction]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kClass]); Push(stackFrame.Frame[(int)StackFrame.AbsoluteIndex.kThisPtr]); FramePointer = Stack.Count; } public bool ValidateStackFrame() { bool isValid = //( AddressType.Pointer == Stack[GetRelative(StackFrame.kFrameIndexThisPtr)].optype //|| AddressType.Invalid == stack[GetRelative(ProtoCore.DSASM.StackFrame.kFrameIndexThisPtr)].optype //|| AddressType.ClassIndex == stack[GetRelative(ProtoCore.DSASM.StackFrame.kFrameIndexThisPtr)].optype //) && AddressType.Int == Stack[GetRelative(StackFrame.kFrameIndexClass)].optype && AddressType.Int == Stack[GetRelative(StackFrame.kFrameIndexFunction)].optype && AddressType.Int == Stack[GetRelative(StackFrame.kFrameIndexReturnAddress)].optype && AddressType.BlockIndex == Stack[GetRelative(StackFrame.kFrameIndexFunctionBlock)].optype && AddressType.BlockIndex == Stack[GetRelative(StackFrame.kFrameIndexFunctionCallerBlock)].optype && AddressType.FrameType == Stack[GetRelative(StackFrame.kFrameIndexCallerStackFrameType)].optype && AddressType.FrameType == Stack[GetRelative(StackFrame.kFrameIndexStackFrameType)].optype && AddressType.Int == Stack[GetRelative(StackFrame.kFrameIndexLocalVariables)].optype && AddressType.Int == Stack[GetRelative(StackFrame.kFrameIndexExecutionStates)].optype && AddressType.Int == Stack[GetRelative(StackFrame.kFrameIndexStackFrameDepth)].optype && AddressType.Int == Stack[GetRelative(StackFrame.kFrameIndexFramePointer)].optype; return isValid; } private void PushRegisters(List<StackValue> registers) { for (int i = 0; i < registers.Count; ++i) { Stack.Add(registers[registers.Count - 1 - i]); } } public void PopFrame(int size) { for (int n = 0; n < size; ++n) { int last = Stack.Count - 1; Stack.RemoveAt(last); } } public void Push(StackValue data) { Stack.Add(data); } public StackValue Pop() { int last = Stack.Count - 1; StackValue value = Stack[last]; Stack.RemoveAt(last); return value; } public void Pop(int size) { for (int n = 0; n < size; ++n) { int last = Stack.Count - 1; Stack.RemoveAt(last); } } public void SetAtRelative(int offset, StackValue data) { int n = GetRelative(offset); Stack[n] = data; } public void SetAtSymbol(SymbolNode symbol, StackValue data) { int n = GetRelative(GetStackIndex(symbol)); Stack[n] = data; } public StackValue GetAtRelative(int relativeOffset) { int n = GetRelative(relativeOffset); return Stack[n]; } public StackValue GetAtRelative(SymbolNode symbol) { int n = GetRelative(GetStackIndex(symbol)); return Stack[n]; } public StackValue GetAtRelative(int relativeOffset, int index) { int n = GetRelative(relativeOffset); return Stack[n]; } public void SetData(int blockId, int symbolindex, int scope, Object data) { MemoryRegion region = Executable.runtimeSymbols[blockId].symbolList[symbolindex].memregion; if (MemoryRegion.kMemStack == region) { SetStackData(blockId, symbolindex, scope, data); } else if (MemoryRegion.kMemHeap == region) { throw new NotImplementedException("{BEC8F306-6704-4C90-A1A2-5BD871871022}"); } else if (MemoryRegion.kMemStatic == region) { Validity.Assert(false, "static region not yet supported, {17C22575-2361-4BAE-AA9E-9076CD1E52D9}"); } else { Validity.Assert(false, "unsupported memory region, {AF92A869-6F9F-421D-84F8-BC2FC56C07F4}"); } } public int GetStackIndex(int offset) { int depth = (int)GetAtRelative(ProtoCore.DSASM.StackFrame.kFrameIndexStackFrameDepth).opdata; int blockOffset = depth * StackFrame.kStackFrameSize; offset -= blockOffset; return offset; } public int GetStackIndex(SymbolNode symbolNode) { int offset = symbolNode.index; int depth = 0; int blockOffset = 0; // TODO Jun: the property 'localFunctionIndex' must be deprecated and just use 'functionIndex'. // The GC currenlty has an issue of needing to reset 'functionIndex' at codegen bool isGlobal = Constants.kInvalidIndex == symbolNode.absoluteClassScope && Constants.kGlobalScope == symbolNode.absoluteFunctionIndex; if (!isGlobal) { depth = (int)GetAtRelative(ProtoCore.DSASM.StackFrame.kFrameIndexStackFrameDepth).opdata; blockOffset = depth * StackFrame.kStackFrameSize; } offset -= blockOffset; return offset; } public StackValue SetStackData(int blockId, int symbol, int classScope, Object data) { int offset = Constants.kInvalidIndex; SymbolNode symbolNode = null; if (Constants.kInvalidIndex == classScope) { symbolNode = Executable.runtimeSymbols[blockId].symbolList[symbol]; offset = GetStackIndex(symbolNode); } else { symbolNode = ClassTable.ClassNodes[classScope].symbols.symbolList[symbol]; offset = GetStackIndex(symbolNode); } Validity.Assert(null != symbolNode); UpdateModifiedSymbols(symbolNode); int n = GetRelative(offset); StackValue opPrev = Stack[n]; Stack[n] = (null == data) ? Pop() : (StackValue)data; return opPrev; } public void SetGlobalStackData(int globalOffset, StackValue svData) { Validity.Assert(globalOffset >= 0); Validity.Assert(Stack.Count > 0); Stack[globalOffset] = svData; } public StackValue GetData(int blockId, int symbolindex, int scope) { MemoryRegion region = DSASM.MemoryRegion.kInvalidRegion; if (Constants.kGlobalScope == scope) { region = Executable.runtimeSymbols[blockId].symbolList[symbolindex].memregion; } else { region = ClassTable.ClassNodes[scope].symbols.symbolList[symbolindex].memregion; } if (MemoryRegion.kMemStack == region) { return GetStackData(blockId, symbolindex, scope); } else if (MemoryRegion.kMemHeap == region) { //return GetHeapData(symbolindex); throw new NotImplementedException("{69604961-DE03-440A-97EB-0390B1B0E510}"); } else if (MemoryRegion.kMemStatic == region) { Validity.Assert(false, "static region not yet supported, {63EA5434-D2E2-40B6-A816-0046F573236F}"); } Validity.Assert(false, "unsupported memory region, {DCA48F13-EEE1-4374-B301-C96870D44C6B}"); return StackUtils.BuildInt(0); } public StackValue GetStackData(int blockId, int symbolindex, int classscope, int offset = 0) { SymbolNode symbolNode = null; if (Constants.kInvalidIndex == classscope) { symbolNode = Executable.runtimeSymbols[blockId].symbolList[symbolindex]; } else { symbolNode = ClassTable.ClassNodes[classscope].symbols.symbolList[symbolindex]; } Validity.Assert(null != symbolNode); int n = GetRelative(offset, GetStackIndex(symbolNode)); if (n > Stack.Count - 1) { return StackUtils.BuildNull(); } return Stack[n]; } public StackValue GetMemberData(int symbolindex, int scope) { int thisptr = (int)GetAtRelative(GetStackIndex(ProtoCore.DSASM.StackFrame.kFrameIndexThisPtr)).opdata; // Get the heapstck offset int offset = ClassTable.ClassNodes[scope].symbols.symbolList[symbolindex].index; if (null == Heap.Heaplist[thisptr].Stack || Heap.Heaplist[thisptr].Stack.Length == 0) return StackUtils.BuildNull(); StackValue sv = Heap.Heaplist[thisptr].Stack[offset]; Validity.Assert(AddressType.Pointer == sv.optype || AddressType.ArrayPointer == sv.optype || AddressType.Invalid == sv.optype); // Not initialized yet if (sv.optype == AddressType.Invalid) { sv.optype = AddressType.Null; sv.opdata_d = sv.opdata = 0; return sv; } else if (sv.optype == AddressType.ArrayPointer) { return sv; } int nextPtr = (int)sv.opdata; Validity.Assert(nextPtr >= 0); if (null != Heap.Heaplist[nextPtr].Stack && Heap.Heaplist[nextPtr].Stack.Length > 0) { bool isActualData = AddressType.Pointer != Heap.Heaplist[nextPtr].Stack[0].optype && AddressType.ArrayPointer != Heap.Heaplist[nextPtr].Stack[0].optype && AddressType.Invalid != Heap.Heaplist[nextPtr].Stack[0].optype; // Invalid is an uninitialized member if (isActualData) { return Heap.Heaplist[nextPtr].Stack[0]; } } return sv; } public StackValue GetPrimitive(StackValue op) { if (AddressType.Pointer != op.optype) { return op; } int ptr = (int)op.opdata; while (AddressType.Pointer == Heap.Heaplist[ptr].Stack[0].optype) { ptr = (int)Heap.Heaplist[ptr].Stack[0].opdata; } StackValue opres = new StackValue(); opres.optype = Heap.Heaplist[ptr].Stack[0].optype; opres.opdata = Heap.Heaplist[ptr].Stack[0].opdata; return opres; } public StackValue[] GetArrayElements(StackValue array) { int ptr = (int)array.opdata; HeapElement hs = Heap.Heaplist[ptr]; StackValue[] arrayElements = new StackValue[hs.VisibleSize]; for (int n = 0; n < hs.VisibleSize; ++n) { arrayElements[n] = hs.Stack[n]; } return arrayElements; } public int GetArraySize(StackValue array) { if (array.optype != AddressType.ArrayPointer) { return Constants.kInvalidIndex; } int ptr = (int)array.opdata; return Heap.Heaplist[ptr].Stack.Length; } public StackValue BuildArray(StackValue[] arrayElements) { int size = arrayElements.Length; lock (Heap.cslock) { int ptr = Heap.Allocate(size); for (int n = size - 1; n >= 0; --n) { StackValue sv = arrayElements[n]; Heap.IncRefCount(sv); Heap.Heaplist[ptr].Stack[n] = sv; } return StackUtils.BuildArrayPointer(ptr); } } public StackValue BuildNullArray(int size) { lock (Heap.cslock) { int ptr = Heap.Allocate(size); for (int n = 0; n < size; ++n) { Heap.Heaplist[ptr].Stack[n] = StackUtils.BuildNull(); } return StackUtils.BuildArrayPointer(ptr); } } public StackValue BuildArrayFromStack(int size) { lock (Heap.cslock) { int ptr = Heap.Allocate(size); for (int n = size - 1; n >= 0; --n) { StackValue sv = Pop(); Heap.IncRefCount(sv); Heap.Heaplist[ptr].Stack[n] = sv; } return StackUtils.BuildArrayPointer(ptr); } } public bool IsHeapActive(StackValue sv) { if (!StackUtils.IsReferenceType(sv)) { return false; } return Heap.Heaplist[(int)sv.opdata].Active; } private StackAlignToFramePointerRestorer StackRestorer { get; set; } public void AlignStackForExprInterpreter() { StackRestorer.Align(this); } public void RestoreStackForExprInterpreter() { StackRestorer.Restore(); } public void PushConstructBlockId(int id) { ConstructBlockIds.Add(id); } public void PopConstructBlockId() { if (ConstructBlockIds.Count > 0) ConstructBlockIds.RemoveAt(ConstructBlockIds.Count - 1); } public int CurrentConstructBlockId { get { if (ConstructBlockIds.Count > 0) return ConstructBlockIds[ConstructBlockIds.Count - 1]; else return DSASM.Constants.kInvalidIndex; } } } } }
namespace King.Service.ServiceBus { using Microsoft.Azure.ServiceBus; using Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Threading.Tasks; using Wrappers; /// <summary> /// Bus Message Sender /// </summary> public class BusMessageSender : IBusMessageSender { #region Members /// <summary> /// Buffered Offset (Seconds) /// </summary> public const sbyte BufferedOffset = -6; /// <summary> /// Service Bus Message Client /// </summary> protected readonly IMessageSender client = null; #endregion #region Constructors /// <summary> /// Mockable Constructor /// </summary> /// <param name="client"Client>Service Bus Message Client</param> public BusMessageSender(IMessageSender client) { if (null == client) { throw new ArgumentNullException("client"); } this.client = client; } public Task<T> GetAsync<T>() { throw new NotImplementedException(); } public Task<IEnumerable<T>> GetManyAsync<T>(int count = 5) { throw new NotImplementedException(); } public Task<IEnumerable<T>> PeekAsync<T>(int count = 1) { throw new NotImplementedException(); } #endregion #region Methods /// <summary> /// Save Message to Queue /// </summary> /// <param name="message">Message</param> /// <returns>Task</returns> public virtual async Task Send(Message message) { if (null == message) { throw new ArgumentNullException("message"); } try { await this.client.Send(message); } catch (Exception ex) { Trace.TraceError("Error: '{0}'", ex.ToString()); throw; } } /// <summary> /// Save Object to queue, as json /// </summary> /// <param name="obj">object</param> /// <returns>Task</returns> public virtual async Task Send(object obj) { await Send(obj, Encoding.Json); } /// <summary> /// Save Object to queue, as json /// </summary> /// <param name="obj">object</param> /// <param name="encoding">Encoding (Default Json)</param> /// <returns>Task</returns> public virtual async Task Send(object obj, Encoding encoding = Encoding.Json) { if (null == obj) { throw new ArgumentNullException("obj"); } if (obj is Message) { await this.Send(obj as Message); } else { byte[] data; switch (encoding) { case Encoding.Json: var j = JsonConvert.SerializeObject(obj); data = System.Text.Encoding.Default.GetBytes(j); break; default: var bf = new BinaryFormatter(); using (var ms = new MemoryStream()) { bf.Serialize(ms, obj); data = ms.ToArray(); } break; } var msg = new Message(data) { ContentType = obj.GetType().ToString(), UserProperties = { {"encoding", (byte)encoding} } }; await this.Send(msg); } } /// <summary> /// Send Message to Queue /// </summary> /// <param name="messages">Messages</param> /// <returns>Task</returns> public virtual async Task Send(IEnumerable<Message> messages) { if (null == messages) { throw new ArgumentNullException("message"); } try { await this.client.Send(messages); } catch (Exception ex) { Trace.TraceError("Error: '{0}'", ex.ToString()); throw; } } /// <summary> /// Send Object to queue, as json /// </summary> /// <param name="messages">Messages</param> /// <param name="encoding">Encoding (Default Json)</param> /// <returns>Task</returns> public virtual async Task Send(IEnumerable<object> messages, Encoding encoding = Encoding.Json) { if (null == messages) { throw new ArgumentNullException("obj"); } if (messages is IEnumerable<Message>) { await this.Send(messages as IEnumerable<Message>); } else { var Messages = new List<Message>(messages.Count()); foreach (var m in messages) { byte[] data; switch (encoding) { case Encoding.Json: var j = JsonConvert.SerializeObject(m); data = System.Text.Encoding.Default.GetBytes(j); break; default: var bf = new BinaryFormatter(); using (var ms = new MemoryStream()) { bf.Serialize(ms, m); data = ms.ToArray(); } break; } var msg = new Message(data) { ContentType = m.GetType().ToString(), UserProperties = { {"encoding", (byte)encoding} } }; } await this.Send(Messages); } } /// <summary> /// Send Message /// </summary> /// <param name="message">Message</param> /// <param name="enqueueAt">Schedule for Enqueue</param> /// <returns>Task</returns> public virtual async Task Send(object message, DateTime enqueueAt, Encoding encoding = Encoding.Json) { if (null == message) { throw new ArgumentNullException("message"); } byte[] data; switch (encoding) { case Encoding.Json: var j = JsonConvert.SerializeObject(message); data = System.Text.Encoding.Default.GetBytes(j); break; default: var bf = new BinaryFormatter(); using (var ms = new MemoryStream()) { bf.Serialize(ms, message); data = ms.ToArray(); } break; } var msg = new Message(data) { ScheduledEnqueueTimeUtc = enqueueAt, ContentType = message.GetType().ToString(), UserProperties = { {"encoding", (byte)encoding} } }; await this.Send(msg); } public Task SendAsync<T>(T message) { throw new NotImplementedException(); } /// <summary> /// Send Message for Buffer /// </summary> /// <param name="message">Message</param> /// <param name="enqueueAt">Schedule for Enqueue</param> /// <param name="offset">Offset</param> /// <returns>Task</returns> public virtual async Task SendBuffered(object data, DateTime releaseAt, sbyte offset = BufferedOffset) { var message = new BufferedMessage { Data = null == data ? null : JsonConvert.SerializeObject(data), ReleaseAt = releaseAt }; await this.Send(message, releaseAt.AddSeconds(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; using System.IO; using System.Linq; using System.Text; using System.Xml; using System.Xml.Linq; using CoreXml.Test.XLinq; using Microsoft.Test.ModuleCore; using XmlCoreTest.Common; namespace XLinqTests { public class LoadFromStream : XLinqTestCase { // Type is CoreXml.Test.XLinq.FunctionalTests+TreeManipulationTests+LoadFromStream // Test Case #region Constants private const string purchaseOrderXml = @"<PurchaseOrder><Item price='100'>Motor<![CDATA[cdata]]><elem>inner text</elem>text<?pi pi pi?></Item></PurchaseOrder>"; #endregion #region Fields private readonly XDocument _purchaseOrder = new XDocument(new XElement("PurchaseOrder", new XElement("Item", "Motor", new XAttribute("price", "100"), new XCData("cdata"), new XElement("elem", "inner text"), new XText("text"), new XProcessingInstruction("pi", "pi pi")))); #endregion #region Public Methods and Operators public override void AddChildren() { AddChild(new TestVariation(StreamStateAfterLoading) { Attribute = new VariationAttribute("Stream state after loading") { Priority = 0 } }); AddChild(new TestVariation(XDEncodings) { Attribute = new VariationAttribute("XDocument.Load() Encodings: UTF8, UTF16, UTF16BE") { Priority = 0 } }); AddChild(new TestVariation(XEEncodings) { Attribute = new VariationAttribute("XElement.Load() Encodings: UTF8, UTF16, UTF16BE") { Priority = 0 } }); AddChild(new TestVariation(LoadOptionsPWS) { Attribute = new VariationAttribute("XDocument.Load(), Load options, preserveWhitespace, Stream") { Param = "Stream", Priority = 0 } }); AddChild(new TestVariation(LoadOptionsPWS) { Attribute = new VariationAttribute("XDocument.Load(), Load options, preserveWhitespace, Uri") { Param = "Uri", Priority = 0 } }); AddChild(new TestVariation(LoadOptionsBU) { Attribute = new VariationAttribute("XDocument.Load(), Load options, BaseUri, Uri") { Param = "Uri", Priority = 0 } }); AddChild(new TestVariation(LoadOptionsLI) { Attribute = new VariationAttribute("XDocument.Load(), Load options, LineInfo, Uri") { Param = "Uri", Priority = 0 } }); AddChild(new TestVariation(LoadOptionsLI) { Attribute = new VariationAttribute("XDocument.Load(), Load options, LineInfo, Stream") { Param = "Stream", Priority = 0 } }); AddChild(new TestVariation(XE_LoadOptionsPWS) { Attribute = new VariationAttribute("XElement.Load(), Load options, preserveWhitespace, Uri") { Param = "Uri", Priority = 0 } }); AddChild(new TestVariation(XE_LoadOptionsPWS) { Attribute = new VariationAttribute("XElement.Load(), Load options, preserveWhitespace, Stream") { Param = "Stream", Priority = 0 } }); AddChild(new TestVariation(XE_LoadOptionsBU) { Attribute = new VariationAttribute("XElement.Load(), Load options, BaseUri, Uri") { Param = "Uri", Priority = 0 } }); AddChild(new TestVariation(XE_LoadOptionsLI) { Attribute = new VariationAttribute("XElement.Load(), Load options, LineInfo, Stream") { Param = "Stream", Priority = 0 } }); AddChild(new TestVariation(XE_LoadOptionsLI) { Attribute = new VariationAttribute("XElement.Load(), Load options, LineInfo, Uri") { Param = "Uri", Priority = 0 } }); AddChild(new TestVariation(SaveOptionsTests) { Attribute = new VariationAttribute("XDocument.Save(), SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces") { Param = 3, Priority = 1 } }); AddChild(new TestVariation(SaveOptionsTests) { Attribute = new VariationAttribute("XDocument.Save(), SaveOptions.OmitDuplicateNamespaces") { Param = 2, Priority = 1 } }); AddChild(new TestVariation(SaveOptionsTests) { Attribute = new VariationAttribute("XDocument.Save(), SaveOptions.None") { Param = 0, Priority = 1 } }); AddChild(new TestVariation(SaveOptionsTests) { Attribute = new VariationAttribute("XDocument.Save(), SaveOptions.DisableFormatting ") { Param = 1, Priority = 1 } }); AddChild(new TestVariation(ElementSaveOptionsTests) { Attribute = new VariationAttribute("XElement.Save(), SaveOptions.OmitDuplicateNamespaces") { Param = 2, Priority = 1 } }); AddChild(new TestVariation(ElementSaveOptionsTests) { Attribute = new VariationAttribute("XElement.Save(), SaveOptions.None") { Param = 0, Priority = 1 } }); AddChild(new TestVariation(ElementSaveOptionsTests) { Attribute = new VariationAttribute("XElement.Save(), SaveOptions.DisableFormatting ") { Param = 1, Priority = 1 } }); AddChild(new TestVariation(ElementSaveOptionsTests) { Attribute = new VariationAttribute("XElement.Save(), SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces") { Param = 3, Priority = 1 } }); AddChild(new TestVariation(SaveOptionsDefaultTests) { Attribute = new VariationAttribute("XDocument.Save(), SaveOptions - default") { Priority = 1 } }); AddChild(new TestVariation(ElementSaveOptionsDefaultTests) { Attribute = new VariationAttribute("XElement.Save(), SaveOptions - default") { Priority = 1 } }); AddChild(new TestVariation(EncodingHints) { Attribute = new VariationAttribute("XDocument.Save(), Encoding hints UTF-8") { Param = "UTF-8", Priority = 1 } }); AddChild(new TestVariation(EncodingHintsDefault) { Attribute = new VariationAttribute("XDocument.Save(), Encoding hints - No hint, Fallback to UTF8") { Priority = 1 } }); } public void ElementSaveOptionsDefaultTests() { byte[] expected, actual; var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1")))); using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms, Encoding.UTF8)) { doc.Root.Save(sw); sw.Flush(); expected = ms.ToArray(); } } // write via Stream using (var ms = new MemoryStream()) { doc.Root.Save(ms); actual = ms.ToArray(); } TestLog.Compare(actual.Length, expected.Length, "Length not the same"); for (int index = 0; index < actual.Length; index++) { TestLog.Equals(actual[index], expected[index], "Error on position " + index); } } public void ElementSaveOptionsTests() { var so = (SaveOptions)CurrentChild.Param; byte[] expected, actual; var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1")))); // write via writer using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms, Encoding.UTF8)) { doc.Root.Save(sw, so); sw.Flush(); expected = ms.ToArray(); } } // write via Stream using (var ms = new MemoryStream()) { doc.Root.Save(ms, so); actual = ms.ToArray(); } TestLog.Compare(actual.Length, expected.Length, "Length not the same"); for (int index = 0; index < actual.Length; index++) { TestLog.Equals(actual[index], expected[index], "Error on position " + index); } } public void EncodingHints() { Encoding enc = Encoding.GetEncoding(CurrentChild.Param as string); var doc = new XDocument(new XDeclaration("1.0", enc.WebName, "yes"), new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1")))); using (var ms = new MemoryStream()) { doc.Save(ms); ms.Position = 0; using (var sr = new StreamReader(ms)) { XDocument d1 = XDocument.Load(sr); TestLog.Compare(sr.CurrentEncoding.Equals(enc), "Encoding does not match"); TestLog.Compare(d1.Declaration.Encoding, enc.WebName, "declaration does not match"); } } } //[Variation(Priority = 1, Desc = "XDocument.Save(), Encoding hints - No hint, Fallback to UTF8")] public void EncodingHintsDefault() { var doc = new XDocument(new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1")))); using (var ms = new MemoryStream()) { doc.Save(ms); ms.Position = 0; using (var sr = new StreamReader(ms)) { XDocument d1 = XDocument.Load(sr); TestLog.Compare(sr.CurrentEncoding.Equals(Encoding.UTF8), "Encoding does not match"); TestLog.Compare(d1.Declaration.Encoding, Encoding.UTF8.WebName, "declaration does not match"); } } } public void LoadOptionsBU() { string fileName = @"NoExternals.xml"; var how = CurrentChild.Param as string; XDocument doc = GetXDocument(fileName, LoadOptions.SetBaseUri, how); foreach (XObject node in doc.DescendantNodes().OfType<object>().Concat2(doc.Descendants().Attributes().OfType<object>())) { string baseUri = node.BaseUri; // fail when use stream replace file if (!String.IsNullOrWhiteSpace(baseUri)) { TestLog.Compare(new Uri(baseUri), new Uri(GetFullTestPath(fileName)), "base uri failed"); } } doc = GetXDocument(fileName, LoadOptions.None, how); foreach (XObject node in doc.DescendantNodes().OfType<object>().Concat2(doc.Descendants().Attributes().OfType<object>())) { string baseUri = node.BaseUri; TestLog.Compare(baseUri, "", "base uri failed"); } } //[Variation(Priority = 0, Desc = "XDocument.Load(), Load options, LineInfo, Uri", Param = "Uri")] //[Variation(Priority = 0, Desc = "XDocument.Load(), Load options, LineInfo, Stream", Param = "Stream")] public void LoadOptionsLI() { string fileName = @"NoExternals.xml"; var how = CurrentChild.Param as string; XDocument doc = GetXDocument(fileName, LoadOptions.SetLineInfo, how); foreach (object node in doc.DescendantNodes().OfType<object>().Concat2(doc.Descendants().Attributes().OfType<object>())) { TestLog.Compare((node as IXmlLineInfo).LineNumber != 0, "LineNumber failed"); TestLog.Compare((node as IXmlLineInfo).LinePosition != 0, "LinePosition failed"); } doc = GetXDocument(fileName, LoadOptions.None, how); foreach (object node in doc.DescendantNodes().OfType<object>().Concat2(doc.Descendants().Attributes().OfType<object>())) { TestLog.Compare((node as IXmlLineInfo).LineNumber == 0, "LineNumber failed"); TestLog.Compare((node as IXmlLineInfo).LinePosition == 0, "LinePosition failed"); } } public void LoadOptionsPWS() { string fileName = @"NoExternals.xml"; var how = CurrentChild.Param as string; // PreserveWhitespace = true XDocument doc = GetXDocument(fileName, LoadOptions.PreserveWhitespace, how); TestLog.Compare(doc.Root.FirstNode.NodeType == XmlNodeType.Text, "First node in root should be whitespace"); // PreserveWhitespace = false ... default doc = GetXDocument(fileName, LoadOptions.None, how); TestLog.Compare(doc.Root.FirstNode.NodeType == XmlNodeType.Element, "First node in root should be element(no ws)"); } public void SaveOptionsDefaultTests() { byte[] expected, actual; var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1")))); using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms, Encoding.UTF8)) { doc.Save(sw); sw.Flush(); expected = ms.ToArray(); } } // write via Stream using (var ms = new MemoryStream()) { doc.Save(ms); actual = ms.ToArray(); } TestLog.Compare(actual.Length, expected.Length, "Length not the same"); for (int index = 0; index < actual.Length; index++) { TestLog.Equals(actual[index], expected[index], "Error on position " + index); } } public void SaveOptionsTests() { var so = (SaveOptions)CurrentChild.Param; byte[] expected, actual; var doc = new XDocument(new XDeclaration("1.0", "UTF-8", "yes"), new XElement("root", new XProcessingInstruction("PI", ""), new XAttribute("id", "root"), new XAttribute(XNamespace.Xmlns + "p", "ns1"), new XElement("{ns1}A", new XAttribute(XNamespace.Xmlns + "p", "ns1")))); // write via writer using (var ms = new MemoryStream()) { using (var sw = new StreamWriter(ms, Encoding.UTF8)) { doc.Save(sw, so); sw.Flush(); expected = ms.ToArray(); } } // write via Stream using (var ms = new MemoryStream()) { doc.Save(ms, so); actual = ms.ToArray(); } TestLog.Compare(actual.Length, expected.Length, "Length not the same"); for (int index = 0; index < actual.Length; index++) { TestLog.Equals(actual[index], expected[index], "Error on position " + index); } } //[Variation(Priority = 0, Desc = "Stream state after loading")] public void StreamStateAfterLoading() { MemoryStream ms = CreateStream(purchaseOrderXml, Encoding.UTF8); XDocument.Load(ms); // if stream is not closed we should be able to reset it's position and read it again ms.Position = 0; XDocument.Load(ms); } //[Variation(Priority = 0, Desc = "XDocument.Load() Encodings: UTF8, UTF16, UTF16BE")] public void XDEncodings() { foreach (Encoding enc in new[] { Encoding.UTF8, Encoding.GetEncoding("UTF-16"), Encoding.GetEncoding("UTF-16BE") }) { MemoryStream ms = CreateStream(purchaseOrderXml, enc); XDocument d = XDocument.Load(ms); TestLog.Compare(XNode.DeepEquals(d, _purchaseOrder), "Not the same"); } } //[Variation(Priority = 0, Desc = "XElement.Load() Encodings: UTF8, UTF16, UTF16BE")] public void XEEncodings() { foreach (Encoding enc in new[] { Encoding.UTF8, Encoding.GetEncoding("UTF-16"), Encoding.GetEncoding("UTF-16BE") }) { MemoryStream ms = CreateStream(purchaseOrderXml, enc); XElement e = XElement.Load(ms); TestLog.Compare(XNode.DeepEquals(e, _purchaseOrder.Root), "Not the same"); } } //[Variation(Priority = 0, Desc = "XDocument.Load(), Load options, preserveWhitespace, Uri", Param = "Uri")] //[Variation(Priority = 0, Desc = "XDocument.Load(), Load options, preserveWhitespace, Stream", Param = "Stream")] //[Variation(Priority = 0, Desc = "XElement.Load(), Load options, BaseUri, Uri", Param = "Uri")] //[Variation(Priority = 0, Desc = "XElement.Load(), Load options, BaseUri, Stream", Param = "Stream")] public void XE_LoadOptionsBU() { string fileName = @"NoExternals.xml"; var how = CurrentChild.Param as string; XElement e = GetXElement(fileName, LoadOptions.SetBaseUri, how); foreach (XObject node in e.DescendantNodesAndSelf().OfType<object>().Concat2(e.DescendantsAndSelf().Attributes().OfType<object>())) { string baseUri = node.BaseUri; if (!String.IsNullOrWhiteSpace(baseUri)) { TestLog.Compare(new Uri(baseUri), new Uri(GetFullTestPath(fileName)), "base uri failed"); } } e = GetXElement(fileName, LoadOptions.None, how); foreach (XObject node in e.DescendantNodesAndSelf().OfType<object>().Concat2(e.DescendantsAndSelf().Attributes().OfType<object>())) { string baseUri = node.BaseUri; TestLog.Compare(baseUri, "", "base uri failed"); } } //[Variation(Priority = 0, Desc = "XElement.Load(), Load options, LineInfo, Uri", Param = "Uri")] //[Variation(Priority = 0, Desc = "XElement.Load(), Load options, LineInfo, Stream", Param = "Stream")] public void XE_LoadOptionsLI() { string fileName = @"NoExternals.xml"; var how = CurrentChild.Param as string; XElement e = GetXElement(fileName, LoadOptions.SetLineInfo, how); foreach (object node in e.DescendantNodesAndSelf().OfType<object>().Concat2(e.DescendantsAndSelf().Attributes().OfType<object>())) { TestLog.Compare((node as IXmlLineInfo).LineNumber != 0, "LineNumber failed"); TestLog.Compare((node as IXmlLineInfo).LinePosition != 0, "LinePosition failed"); } e = GetXElement(fileName, LoadOptions.None, how); foreach (object node in e.DescendantNodesAndSelf().OfType<object>().Concat2(e.DescendantsAndSelf().Attributes().OfType<object>())) { TestLog.Compare((node as IXmlLineInfo).LineNumber == 0, "LineNumber failed"); TestLog.Compare((node as IXmlLineInfo).LinePosition == 0, "LinePosition failed"); } } public void XE_LoadOptionsPWS() { string fileName = @"NoExternals.xml"; var how = CurrentChild.Param as string; XElement e = GetXElement(fileName, LoadOptions.PreserveWhitespace, how); TestLog.Compare(e.FirstNode.NodeType == XmlNodeType.Text, "First node in root should be whitespace"); // PreserveWhitespace = false ... default e = GetXElement(fileName, LoadOptions.None, how); TestLog.Compare(e.FirstNode.NodeType == XmlNodeType.Element, "First node in root should be element(no ws)"); } #endregion #region Methods private static MemoryStream CreateStream(string data, Encoding enc) { var ms = new MemoryStream(); // StreamWriter is closing the memorystream when used with using ... so we keep it this way var sw = new StreamWriter(ms, enc); sw.Write(data); sw.Flush(); ms.Position = 0; return ms; } private static string GetFullTestPath(string fileName) { return Path.Combine(FilePathUtil.GetTestDataPath() + @"/XLinq", fileName); } // Save options: //[Variation(Priority = 1, Desc = "XDocument.Save(), SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces", Param = SaveOptions.DisableFormatting | SaveOptions.OmitDuplicateNamespaces)] //[Variation(Priority = 1, Desc = "XDocument.Save(), SaveOptions.DisableFormatting ", Param = SaveOptions.DisableFormatting)] //[Variation(Priority = 1, Desc = "XDocument.Save(), SaveOptions.OmitDuplicateNamespaces", Param = SaveOptions.OmitDuplicateNamespaces)] //[Variation(Priority = 1, Desc = "XDocument.Save(), SaveOptions.None", Param = SaveOptions.None)] private static XDocument GetXDocument(string fileName, LoadOptions lo, string how) { switch (how) { case "Uri": return XDocument.Load(FilePathUtil.getStream(GetFullTestPath(fileName)), lo); case "Stream": using (Stream s = FilePathUtil.getStream(GetFullTestPath(fileName))) { return XDocument.Load(s, lo); } default: throw new TestFailedException("TEST FAILED: don't know how to create XDocument"); } } private static XElement GetXElement(string fileName, LoadOptions lo, string how) { switch (how) { case "Uri": return XElement.Load(FilePathUtil.getStream(GetFullTestPath(fileName)), lo); case "Stream": using (Stream s = FilePathUtil.getStream(GetFullTestPath(fileName))) { return XElement.Load(s, lo); } default: throw new TestFailedException("TEST FAILED: don't know how to create XElement"); } } #endregion } }
using System; using System.Collections; using System.IO; using Org.BouncyCastle.Asn1; using Org.BouncyCastle.Asn1.Cms; using Org.BouncyCastle.Asn1.X509; using Org.BouncyCastle.Utilities; namespace Org.BouncyCastle.Cms { /** * Parsing class for an CMS Authenticated Data object from an input stream. * <p> * Note: that because we are in a streaming mode only one recipient can be tried and it is important * that the methods on the parser are called in the appropriate order. * </p> * <p> * Example of use - assuming the first recipient matches the private key we have. * <pre> * CMSAuthenticatedDataParser ad = new CMSAuthenticatedDataParser(inputStream); * * RecipientInformationStore recipients = ad.getRecipientInfos(); * * Collection c = recipients.getRecipients(); * Iterator it = c.iterator(); * * if (it.hasNext()) * { * RecipientInformation recipient = (RecipientInformation)it.next(); * * CMSTypedStream recData = recipient.getContentStream(privateKey, "BC"); * * processDataStream(recData.getContentStream()); * * if (!Arrays.equals(ad.getMac(), recipient.getMac()) * { * System.err.println("Data corrupted!!!!"); * } * } * </pre> * Note: this class does not introduce buffering - if you are processing large files you should create * the parser with: * <pre> * CMSAuthenticatedDataParser ep = new CMSAuthenticatedDataParser(new BufferedInputStream(inputStream, bufSize)); * </pre> * where bufSize is a suitably large buffer size. * </p> */ public class CmsAuthenticatedDataParser : CmsContentInfoParser { internal RecipientInformationStore _recipientInfoStore; internal AuthenticatedDataParser authData; private AlgorithmIdentifier macAlg; private byte[] mac; private Asn1.Cms.AttributeTable authAttrs; private Asn1.Cms.AttributeTable unauthAttrs; private bool authAttrNotRead; private bool unauthAttrNotRead; public CmsAuthenticatedDataParser( byte[] envelopedData) : this(new MemoryStream(envelopedData, false)) { } public CmsAuthenticatedDataParser( Stream envelopedData) : base(envelopedData) { this.authAttrNotRead = true; this.authData = new AuthenticatedDataParser( (Asn1SequenceParser)contentInfo.GetContent(Asn1Tags.Sequence)); // TODO Validate version? //DerInteger version = this.authData.getVersion(); // // read the recipients // Asn1Set recipientInfos = Asn1Set.GetInstance(authData.GetRecipientInfos().ToAsn1Object()); this.macAlg = authData.GetMacAlgorithm(); // // read the authenticated content info // ContentInfoParser data = authData.GetEnapsulatedContentInfo(); CmsReadable readable = new CmsProcessableInputStream( ((Asn1OctetStringParser)data.GetContent(Asn1Tags.OctetString)).GetOctetStream()); CmsSecureReadable secureReadable = new CmsEnvelopedHelper.CmsAuthenticatedSecureReadable( this.macAlg, readable); // // build the RecipientInformationStore // this._recipientInfoStore = CmsEnvelopedHelper.BuildRecipientInformationStore( recipientInfos, secureReadable); } public AlgorithmIdentifier MacAlgorithmID { get { return macAlg; } } /** * return the object identifier for the mac algorithm. */ public string MacAlgOid { get { return macAlg.ObjectID.Id; } } /** * return the ASN.1 encoded encryption algorithm parameters, or null if * there aren't any. */ public Asn1Object MacAlgParams { get { Asn1Encodable ae = macAlg.Parameters; return ae == null ? null : ae.ToAsn1Object(); } } /** * return a store of the intended recipients for this message */ public RecipientInformationStore GetRecipientInfos() { return _recipientInfoStore; } public byte[] GetMac() { if (mac == null) { GetAuthAttrs(); mac = authData.GetMac().GetOctets(); } return Arrays.Clone(mac); } /** * return a table of the unauthenticated attributes indexed by * the OID of the attribute. * @exception java.io.IOException */ public Asn1.Cms.AttributeTable GetAuthAttrs() { if (authAttrs == null && authAttrNotRead) { Asn1SetParser s = authData.GetAuthAttrs(); authAttrNotRead = false; if (s != null) { Asn1EncodableVector v = new Asn1EncodableVector(); IAsn1Convertible o; while ((o = s.ReadObject()) != null) { Asn1SequenceParser seq = (Asn1SequenceParser)o; v.Add(seq.ToAsn1Object()); } authAttrs = new Asn1.Cms.AttributeTable(new DerSet(v)); } } return authAttrs; } /** * return a table of the unauthenticated attributes indexed by * the OID of the attribute. * @exception java.io.IOException */ public Asn1.Cms.AttributeTable GetUnauthAttrs() { if (unauthAttrs == null && unauthAttrNotRead) { Asn1SetParser s = authData.GetUnauthAttrs(); unauthAttrNotRead = false; if (s != null) { Asn1EncodableVector v = new Asn1EncodableVector(); IAsn1Convertible o; while ((o = s.ReadObject()) != null) { Asn1SequenceParser seq = (Asn1SequenceParser)o; v.Add(seq.ToAsn1Object()); } unauthAttrs = new Asn1.Cms.AttributeTable(new DerSet(v)); } } return unauthAttrs; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace AddInsShare.Schema { internal class CustomType : Type { private readonly Type _baseType; private IList<CustomPropertyInfoHelper> _customProperties; public CustomType(Type delegatingType, IList<CustomPropertyInfoHelper> customProperties) { if (delegatingType == null) throw new ArgumentNullException("delegatingType"); _baseType = delegatingType; _customProperties = customProperties; } public override Assembly Assembly { get { return _baseType.Assembly; } } public override string AssemblyQualifiedName { get { return _baseType.AssemblyQualifiedName; } } public override Type BaseType { get { return _baseType.BaseType; } } public override string FullName { get { return _baseType.FullName; } } public override Guid GUID { get { return _baseType.GUID; } } protected override TypeAttributes GetAttributeFlagsImpl() { throw new NotImplementedException(); } protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { return _baseType.GetConstructor(bindingAttr, binder, callConvention, types, modifiers); } public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { return _baseType.GetConstructors(bindingAttr); } public override Type GetElementType() { return _baseType.GetElementType(); } public override EventInfo GetEvent(string name, BindingFlags bindingAttr) { return _baseType.GetEvent(name, bindingAttr); } public override EventInfo[] GetEvents(BindingFlags bindingAttr) { return _baseType.GetEvents(bindingAttr); } public override FieldInfo GetField(string name, BindingFlags bindingAttr) { return _baseType.GetField(name, bindingAttr); } public override FieldInfo[] GetFields(BindingFlags bindingAttr) { return _baseType.GetFields(bindingAttr); } public override Type GetInterface(string name, bool ignoreCase) { return _baseType.GetInterface(name, ignoreCase); } public override Type[] GetInterfaces() { return _baseType.GetInterfaces(); } public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { return _baseType.GetMembers(bindingAttr); } protected override MethodInfo GetMethodImpl(string name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotImplementedException(); } public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { return _baseType.GetMethods(bindingAttr); } public override Type GetNestedType(string name, BindingFlags bindingAttr) { return _baseType.GetNestedType(name, bindingAttr); } public override Type[] GetNestedTypes(BindingFlags bindingAttr) { return _baseType.GetNestedTypes(bindingAttr); } public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { return _baseType.GetProperties(bindingAttr).Concat(_customProperties).ToArray(); } protected override PropertyInfo GetPropertyImpl(string name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { // Look for the CLR property with this name first. return GetProperties(bindingAttr).FirstOrDefault(prop => prop.Name == name) // and then for a custom property ?? _customProperties.FirstOrDefault(prop => prop.Name == name); } protected override bool HasElementTypeImpl() { throw new NotImplementedException(); } public override object InvokeMember(string name, BindingFlags invokeAttr, Binder binder, object target, object[] args, ParameterModifier[] modifiers, System.Globalization.CultureInfo culture, string[] namedParameters) { return _baseType.InvokeMember(name, invokeAttr, binder, target, args, modifiers, culture, namedParameters); } protected override bool IsArrayImpl() { throw new NotImplementedException(); } protected override bool IsByRefImpl() { throw new NotImplementedException(); } protected override bool IsCOMObjectImpl() { throw new NotImplementedException(); } protected override bool IsPointerImpl() { throw new NotImplementedException(); } protected override bool IsPrimitiveImpl() { return _baseType.IsPrimitive; } public override Module Module { get { return _baseType.Module; } } public override string Namespace { get { return _baseType.Namespace; } } public override Type UnderlyingSystemType { get { return _baseType.UnderlyingSystemType; } } public override object[] GetCustomAttributes(Type attributeType, bool inherit) { return _baseType.GetCustomAttributes(attributeType, inherit); } public override object[] GetCustomAttributes(bool inherit) { return _baseType.GetCustomAttributes(inherit); } public override bool IsDefined(Type attributeType, bool inherit) { return _baseType.IsDefined(attributeType, inherit); } public override string Name { get { return _baseType.Name; } } public override bool ContainsGenericParameters { get { return _baseType.ContainsGenericParameters; } } public override System.Collections.Generic.IEnumerable<CustomAttributeData> CustomAttributes { get { return _baseType.CustomAttributes; } } public override MethodBase DeclaringMethod { get { return _baseType.DeclaringMethod; } } public override Type DeclaringType { get { return _baseType.DeclaringType; } } public override bool Equals(Type o) { return _baseType == o; } public override Type[] FindInterfaces(TypeFilter filter, object filterCriteria) { return _baseType.FindInterfaces(filter, filterCriteria); } public override MemberInfo[] FindMembers(MemberTypes memberType, BindingFlags bindingAttr, MemberFilter filter, object filterCriteria) { return _baseType.FindMembers(memberType, bindingAttr, filter, filterCriteria); } public override GenericParameterAttributes GenericParameterAttributes { get { return _baseType.GenericParameterAttributes; } } public override int GenericParameterPosition { get { return _baseType.GenericParameterPosition; } } public override Type[] GenericTypeArguments { get { return _baseType.GenericTypeArguments; } } public override int GetArrayRank() { return _baseType.GetArrayRank(); } public override System.Collections.Generic.IList<CustomAttributeData> GetCustomAttributesData() { return _baseType.GetCustomAttributesData(); } public override MemberInfo[] GetDefaultMembers() { return _baseType.GetDefaultMembers(); } public override string GetEnumName(object value) { return _baseType.GetEnumName(value); } public override string[] GetEnumNames() { return _baseType.GetEnumNames(); } public override Type GetEnumUnderlyingType() { return _baseType.GetEnumUnderlyingType(); } public override Array GetEnumValues() { return _baseType.GetEnumValues(); } public override EventInfo[] GetEvents() { return _baseType.GetEvents(); } public override Type[] GetGenericArguments() { return _baseType.GetGenericArguments(); } public override Type[] GetGenericParameterConstraints() { return _baseType.GetGenericParameterConstraints(); } public override Type GetGenericTypeDefinition() { return _baseType.GetGenericTypeDefinition(); } public override InterfaceMapping GetInterfaceMap(Type interfaceType) { return _baseType.GetInterfaceMap(interfaceType); } public override MemberInfo[] GetMember(string name, BindingFlags bindingAttr) { return _baseType.GetMember(name, bindingAttr); } public override MemberInfo[] GetMember(string name, MemberTypes type, BindingFlags bindingAttr) { return _baseType.GetMember(name, type, bindingAttr); } public override bool IsAssignableFrom(Type c) { return _baseType.IsAssignableFrom(c); } public override bool IsConstructedGenericType { get { return _baseType.IsConstructedGenericType; } } public override bool IsEnum { get { return _baseType.IsEnum; } } public override bool IsEnumDefined(object value) { return _baseType.IsEnumDefined(value); } public override bool IsEquivalentTo(Type other) { return _baseType.IsEquivalentTo(other); } public override bool IsGenericParameter { get { return _baseType.IsGenericParameter; } } public override bool IsGenericType { get { return _baseType.IsGenericType; } } public override bool IsGenericTypeDefinition { get { return _baseType.IsGenericTypeDefinition; } } public override bool IsInstanceOfType(object o) { return _baseType.IsInstanceOfType(o); } public override bool IsSerializable { get { return _baseType.IsSerializable; } } public override bool IsSubclassOf(Type c) { return _baseType.IsSubclassOf(c); } public override RuntimeTypeHandle TypeHandle { get { return _baseType.TypeHandle; } } public override Type MakeArrayType() { return _baseType.MakeArrayType(); } public override Type MakeArrayType(int rank) { return _baseType.MakeArrayType(rank); } public override Type MakeByRefType() { return _baseType.MakeByRefType(); } public override Type MakeGenericType(params Type[] typeArguments) { return _baseType.MakeGenericType(typeArguments); } public override Type MakePointerType() { return _baseType.MakePointerType(); } public override MemberTypes MemberType { get { return _baseType.MemberType; } } public override int MetadataToken { get { return _baseType.MetadataToken; } } public override Type ReflectedType { get { return _baseType.ReflectedType; } } public override System.Runtime.InteropServices.StructLayoutAttribute StructLayoutAttribute { get { return _baseType.StructLayoutAttribute; } } public override string ToString() { return _baseType.ToString(); } } }
//----------------------------------------------------------------------- // // Microsoft Windows Client Platform // Copyright (C) Microsoft Corporation // // File: FullTextState.cs // // Contents: Formatting state of full text // // Created: 2-25-2004 Worachai Chaoweeraprasit (wchao) // History: 1-29-2005 (wchao) refactor drawing state out, keep full text // only for formatting state // //------------------------------------------------------------------------ using System; using System.Security; using System.Globalization; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Media; using System.Windows.Media.TextFormatting; using MS.Internal.Shaping; using MS.Internal.Generic; namespace MS.Internal.TextFormatting { /// <summary> /// Formatting state of full text /// </summary> internal sealed class FullTextState { private TextStore _store; // formatting store for main text private TextStore _markerStore; // store specifically for marker private StatusFlags _statusFlags; // status flags private int _cpMeasured; // number of CP successfully measured and fit within column width private int _lscpHyphenationLookAhead; // LSCP after the last character examined by the hyphenation code. private bool _isSideways; [Flags] private enum StatusFlags { None = 0, VerticalAdjust = 0x00000001, // vertical adjustment on some runs required ForceWrap = 0x00000002, // force wrap KeepState = 0x00000040, // state should be kept in the line } /// <summary> /// A word smaller than seven characters does not require hyphenation. This is based on /// observation in real Western books and publications. Advanced research on readability /// seems to support this finding. It suggests that the 'fovea' which is the center /// point of our vision, can only see three to four letters before and after the center /// of a word. /// </summary> /// <remarks> /// "It has been known for over 100 years that when we read, our eyes don't move smoothly /// across the page, but rather make discrete jumps from word to word. We fixate on a word /// for a period of time, roughly 200-250ms, then make a ballistic movement to another word. /// These movements are called saccades and usually take 20-35ms. Most saccades are forward /// movements from 7 to 9 letters. /// ... /// During a single fixation, there is a limit to the amount of information that can be /// recognized. The fovea, which is the clear center point of our vision, can only see /// three to four letters to the left and right of fixation at normal reading distances." /// /// ["The Science of Word Recognition" by Kevin Larson; July 2004] /// </remarks> private const int MinCchWordToHyphenate = 7; /// <summary> /// Create a fulltext state object from formatting info for subsequent fulltext formatting /// e.g. fulltext line, mix/max computation, potential breakpoints for optimal paragraph formatting. /// </summary> internal static FullTextState Create( FormatSettings settings, int cpFirst, int finiteFormatWidth ) { // prepare text stores TextStore store = new TextStore( settings, cpFirst, 0, settings.GetFormatWidth(finiteFormatWidth) ); ParaProp pap = settings.Pap; TextStore markerStore = null; if( pap.FirstLineInParagraph && pap.TextMarkerProperties != null && pap.TextMarkerProperties.TextSource != null) { // create text store specifically for marker markerStore = new TextStore( // create specialized settings for marker store e.g. with marker text source new FormatSettings( settings.Formatter, pap.TextMarkerProperties.TextSource, new TextRunCacheImp(), // no cross-call run cache available for marker store pap, // marker by default use the same paragraph properties null, // not consider previousLineBreak true, // isSingleLineFormatting settings.TextFormattingMode, settings.IsSideways ), 0, // marker store always started with cp == 0 TextStore.LscpFirstMarker, // first lscp value for marker text Constants.IdealInfiniteWidth // formatWidth ); } // construct a new fulltext state object return new FullTextState(store, markerStore, settings.IsSideways); } /// <summary> /// Construct full text state for formatting /// </summary> private FullTextState( TextStore store, TextStore markerStore, bool isSideways ) { _isSideways = isSideways; _store = store; _markerStore = markerStore; } /// <summary> /// Number of client CP for which we know the nominal widths fit in the /// available margin (i.e., because we've measured them). /// </summary> internal int CpMeasured { get { return _cpMeasured; } set { _cpMeasured = value; } } /// <summary> /// LSCP immediately after the last LSCP examined by hyphenation code while being run. /// This value is used to calculate a more precise DependentLength value for the line /// ended by automatic hyphenation. /// </summary> internal int LscpHyphenationLookAhead { get { return _lscpHyphenationLookAhead; } } internal TextFormattingMode TextFormattingMode { get { return Formatter.TextFormattingMode; } } internal bool IsSideways { get { return _isSideways; } } /// <summary> /// Set tab stops /// </summary> /// <SecurityNote> /// Critical - as this calls TextFormatterContext.SetTabs which is Critical in four /// different places. /// Safe - as the buffers are all created in the same function and the count /// passed in the same as used for creating the buffer. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal void SetTabs(TextFormatterContext context) { unsafe { ParaProp pap = _store.Pap; FormatSettings settings = _store.Settings; // set up appropriate tab stops int incrementalTab = TextFormatterImp.RealToIdeal(pap.DefaultIncrementalTab); int lsTbdCount = pap.Tabs != null ? pap.Tabs.Count : 0; LsTbd[] lsTbds; if (_markerStore != null) { if (pap.Tabs != null && pap.Tabs.Count > 0) { lsTbdCount = pap.Tabs.Count + 1; lsTbds = new LsTbd[lsTbdCount]; lsTbds[0].ur = settings.TextIndent; // marker requires a tab stop at text start position fixed (LsTbd* plsTbds = &lsTbds[1]) { CreateLsTbds(pap, plsTbds, lsTbdCount - 1); context.SetTabs(incrementalTab, plsTbds - 1, lsTbdCount); } } else { LsTbd markerRequiredLsTbd = new LsTbd(); markerRequiredLsTbd.ur = settings.TextIndent; // marker requires a tab stop at text start position context.SetTabs(incrementalTab, &markerRequiredLsTbd, 1); } } else { if (pap.Tabs != null && pap.Tabs.Count > 0) { lsTbds = new LsTbd[lsTbdCount]; fixed (LsTbd* plsTbds = &lsTbds[0]) { CreateLsTbds(pap, plsTbds, lsTbdCount); context.SetTabs(incrementalTab, plsTbds, lsTbdCount); } } else { // work with only incremental tab context.SetTabs(incrementalTab, null, 0); } } } } /// <summary> /// Fill a fixed buffer of LsTbd with /// </summary> /// <SecurityNote> /// Critical - This method writes into unmanaged array. /// </SecurityNote> [SecurityCritical] private unsafe void CreateLsTbds( ParaProp pap, LsTbd* plsTbds, int lsTbdCount ) { for (int i = 0; i < lsTbdCount; i++) { TextTabProperties tab = (TextTabProperties)pap.Tabs[i]; plsTbds[i].lskt = Convert.LsKTabFromTabAlignment(tab.Alignment); plsTbds[i].ur = TextFormatterImp.RealToIdeal(tab.Location); if (tab.TabLeader != 0) { // Note: LS does not currently support surrogate character as tab leader and aligning character plsTbds[i].wchTabLeader = (char)tab.TabLeader; // tab leader requires state at display time for tab leader width fetching _statusFlags |= StatusFlags.KeepState; } plsTbds[i].wchCharTab = (char)tab.AligningCharacter; } } /// <summary> /// Get distance from the start of main text to the end of marker /// </summary> /// <remarks> /// Positive distance is filtered out. Marker overlapping the main text is not supported. /// </remarks> internal int GetMainTextToMarkerIdealDistance() { if (_markerStore != null) { return Math.Min(0, TextFormatterImp.RealToIdeal(_markerStore.Pap.TextMarkerProperties.Offset) - _store.Settings.TextIndent); } return 0; } /// <summary> /// Map LSCP to host CP, and return the last LSRun /// before the specified limit. /// </summary> internal LSRun CountText( int lscpLim, int cpFirst, out int count ) { LSRun lastRun = null; count = 0; int lsccp = lscpLim - _store.CpFirst; Debug.Assert(lsccp > 0, "Zero-length text line!"); foreach (Span span in _store.PlsrunVector) { if (lsccp <= 0) break; Plsrun plsrun = (Plsrun)span.element; // There should be no marker runs in _plsrunVector. Debug.Assert(!TextStore.IsMarker(plsrun)); // Is it a normal, non-static, LSRun? if (plsrun >= Plsrun.FormatAnchor) { // Get the run and remember the last run. lastRun = _store.GetRun(plsrun); // Accumulate the length. int cpRun = lastRun.Length; if (cpRun > 0) { if (lsccp < span.length && cpRun == span.length) { count += lsccp; break; } count += cpRun; } } lsccp -= span.length; } // make char count relative to cpFirst as the cpFirst of this metrics may not // be the same as the cpFirst of the store in optimal paragraph formatting. count = count - cpFirst + _store.CpFirst; return lastRun; } /// <summary> /// Convert the specified external CP to LSCP corresponding to a possible break position for optimal break. /// </summary> /// <remarks> /// There is a generic issue that one CP could map to multiple LSCPs when it comes to /// lsrun that occupies no actual CP. Such lsrun is generated by line layout during /// formatting to accomplsih specific purpose i.e. run representing open and close /// reverse object or a fake-linebreak lsrun. /// /// According to SergeyGe and Antons, LS will never breaks immediately after open reverse /// or immediately before close reverse. It also never break before a linebreak character. /// /// Therefore, it is safe to make an assumption here that one CP will indeed map to one /// LSCP given being the LSCP before the open reverse and the LSCP after the close reverse. /// Never the vice-versa. /// /// This is the reason why the loop inside this method may overread the PLSRUN span by /// one span at the end. The loop is designed to skip over all the lsruns with zero CP /// which is not the open reverse. /// /// This logic is exactly the same as the one used by FullTextLine.PrefetchLSRuns. Any /// attempt to change it needs to be thoroughly reviewed. The same logic is to be applied /// accordingly on PrefetchLSRuns. /// /// [Wchao, 5-24-2005] /// /// </remarks> internal int GetBreakpointInternalCp(int cp) { int ccp = cp - _store.CpFirst; int lscp = _store.CpFirst; int ccpCurrent = 0; SpanVector plsrunVector = _store.PlsrunVector; LSRun lsrun; int i = 0; int lastSpanLength = 0; int lastRunLength = 0; do { Span span = plsrunVector[i]; Plsrun plsrun = (Plsrun)span.element; lsrun = _store.GetRun(plsrun); if (ccp == ccpCurrent && lsrun.Type == Plsrun.Reverse) { break; } lastSpanLength = span.length; lastRunLength = (plsrun >= Plsrun.FormatAnchor ? lsrun.Length : 0); lscp += lastSpanLength; ccpCurrent += lastRunLength; } while ( ++i < plsrunVector.Count && lsrun.Type != Plsrun.ParaBreak && ccp >= ccpCurrent ); // Since we may overread the span vector by one span, // we need to subtract the accumulated lscp by the number of cp we may have overread. if (ccpCurrent == ccp || lastSpanLength == lastRunLength) return lscp - ccpCurrent + ccp; Invariant.Assert(ccpCurrent - ccp == lastRunLength); return lscp - lastSpanLength; } /// <summary> /// Find the hyphen break following or preceding the specified current LSCP /// </summary> /// <remarks> /// This method never checks whether the specified current LSCP is already right /// at a hyphen break. It either finds the next or the previous break regardless. /// /// A negative lscchLim param value indicates the caller finds the hyphen immediately /// before the specified character index. /// </remarks> /// <param name="lscpCurrent">the current LSCP</param> /// <param name="lscchLim">the number of LSCP to search for break</param> /// <param name="isCurrentAtWordStart">flag indicates whether lscpCurrent is the beginning of the word to hyphenate</param> /// <param name="lscpHyphen">LSCP of the hyphen</param> /// <param name="lshyph">Hyphen properties</param> internal bool FindNextHyphenBreak( int lscpCurrent, int lscchLim, bool isCurrentAtWordStart, ref int lscpHyphen, ref LsHyph lshyph ) { lshyph = new LsHyph(); // no additional hyphen properties for now if (_store.Pap.Hyphenator != null) { int lscpChunk; int lscchChunk; LexicalChunk chunk = GetChunk( _store.Pap.Hyphenator, lscpCurrent, lscchLim, isCurrentAtWordStart, out lscpChunk, out lscchChunk ); _lscpHyphenationLookAhead = lscpChunk + lscchChunk; if (!chunk.IsNoBreak) { int ichCurrent = chunk.LSCPToCharacterIndex(lscpCurrent - lscpChunk); int ichLim = chunk.LSCPToCharacterIndex(lscpCurrent + lscchLim - lscpChunk); if (lscchLim >= 0) { int ichNext = chunk.Breaks.GetNextBreak(ichCurrent); if (ichNext >= 0 && ichNext > ichCurrent && ichNext <= ichLim) { // -1 because ichNext is the character index where break occurs in front of it, // while LSCP is the position where break occurs after it. lscpHyphen = chunk.CharacterIndexToLSCP(ichNext - 1) + lscpChunk; return true; } } else { int ichPrev = chunk.Breaks.GetPreviousBreak(ichCurrent); if (ichPrev >= 0 && ichPrev <= ichCurrent && ichPrev > ichLim) { // -1 because ichPrev is the character index where break occurs in front of it, // while LSCP is the position where break occurs after it. lscpHyphen = chunk.CharacterIndexToLSCP(ichPrev - 1) + lscpChunk; return true; } } } } return false; } /// <summary> /// Get the lexical chunk the specified current LSCP is within. /// </summary> private LexicalChunk GetChunk( TextLexicalService lexicalService, int lscpCurrent, int lscchLim, bool isCurrentAtWordStart, out int lscpChunk, out int lscchChunk ) { int lscpStart = lscpCurrent; int lscpLim = lscpStart + lscchLim; int cpFirst = _store.CpFirst; if (lscpStart > lscpLim) { // Start is always before limit lscpStart = lscpLim; lscpLim = lscpCurrent; } LexicalChunk chunk = new LexicalChunk(); int cchWordMax; CultureInfo textCulture; SpanVector<int> textVector; char[] rawText = _store.CollectRawWord( lscpStart, isCurrentAtWordStart, _isSideways, out lscpChunk, out lscchChunk, out textCulture, out cchWordMax, out textVector ); if ( rawText != null && cchWordMax >= MinCchWordToHyphenate && lscpLim < lscpChunk + lscchChunk && textCulture != null && lexicalService != null && lexicalService.IsCultureSupported(textCulture) ) { // analyze the chunk and produce the lexical chunk to cache TextLexicalBreaks breaks = lexicalService.AnalyzeText( rawText, rawText.Length, textCulture ); if (breaks != null) { chunk = new LexicalChunk(breaks, textVector); } } return chunk; } /// <summary> /// Get a text store containing the specified plsrun /// </summary> internal TextStore StoreFrom(Plsrun plsrun) { return TextStore.IsMarker(plsrun) ? _markerStore : _store; } /// <summary> /// Get a text store containing the specified lscp /// </summary> internal TextStore StoreFrom(int lscp) { return lscp < 0 ? _markerStore : _store; } /// <summary> /// Flag indicating whether vertical adjustment of some runs is required /// </summary> internal bool VerticalAdjust { get { return (_statusFlags & StatusFlags.VerticalAdjust) != 0; } set { if (value) _statusFlags |= StatusFlags.VerticalAdjust; else _statusFlags &= ~StatusFlags.VerticalAdjust; } } /// <summary> /// Flag indicating whether force wrap is required /// </summary> internal bool ForceWrap { get { return (_statusFlags & StatusFlags.ForceWrap) != 0; } set { if (value) _statusFlags |= StatusFlags.ForceWrap; else _statusFlags &= ~StatusFlags.ForceWrap; } } /// <summary> /// Flag indicating whether state should be kept in the line /// </summary> internal bool KeepState { get { return (_statusFlags & StatusFlags.KeepState) != 0; } } /// <summary> /// Formatting store for main text /// </summary> internal TextStore TextStore { get { return _store; } } /// <summary> /// Formatting store for marker text /// </summary> internal TextStore TextMarkerStore { get { return _markerStore; } } /// <summary> /// Current formatter /// </summary> internal TextFormatterImp Formatter { get { return _store.Settings.Formatter; } } /// <summary> /// formattng ideal width /// </summary> internal int FormatWidth { get { return _store.FormatWidth; } } } }
/* * Copyright 2010-2014 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. */ /* * Do not modify this file. This file is generated from the config-2014-11-12.normal.json service model. */ using System; using System.Threading; using System.Threading.Tasks; using System.Collections.Generic; using Amazon.ConfigService.Model; namespace Amazon.ConfigService { /// <summary> /// Interface for accessing ConfigService /// /// AWS Config /// <para> /// AWS Config provides a way to keep track of the configurations of all the AWS resources /// associated with your AWS account. You can use AWS Config to get the current and historical /// configurations of each AWS resource and also to get information about the relationship /// between the resources. An AWS resource can be an Amazon Compute Cloud (Amazon EC2) /// instance, an Elastic Block Store (EBS) volume, an Elastic network Interface (ENI), /// or a security group. For a complete list of resources currently supported by AWS Config, /// see <a href="http://docs.aws.amazon.com/config/latest/developerguide/resource-config-reference.html#supported-resources">Supported /// AWS Resources</a>. /// </para> /// /// <para> /// You can access and manage AWS Config through the AWS Management Console, the AWS Command /// Line Interface (AWS CLI), the AWS Config API, or the AWS SDKs for AWS Config /// </para> /// /// <para> /// This reference guide contains documentation for the AWS Config API and the AWS CLI /// commands that you can use to manage AWS Config. /// </para> /// /// <para> /// The AWS Config API uses the Signature Version 4 protocol for signing requests. For /// more information about how to sign a request with this protocol, see <a href="http://docs.aws.amazon.com/general/latest/gr/signature-version-4.html">Signature /// Version 4 Signing Process</a>. /// </para> /// /// <para> /// For detailed information about AWS Config features and their associated actions or /// commands, as well as how to work with AWS Management Console, see <a href="http://docs.aws.amazon.com/config/latest/developerguide/WhatIsConfig.html">What /// Is AWS Config?</a> in the <i>AWS Config Developer Guide</i>. /// </para> /// </summary> public partial interface IAmazonConfigService : IDisposable { #region DeleteDeliveryChannel /// <summary> /// Deletes the specified delivery channel. /// /// /// <para> /// The delivery channel cannot be deleted if it is the only delivery channel and the /// configuration recorder is still running. To delete the delivery channel, stop the /// running configuration recorder using the <a>StopConfigurationRecorder</a> action. /// </para> /// </summary> /// <param name="deliveryChannelName">The name of the delivery channel to delete.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeleteDeliveryChannel service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.LastDeliveryChannelDeleteFailedException"> /// You cannot delete the delivery channel you specified because the configuration recorder /// is running. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> Task<DeleteDeliveryChannelResponse> DeleteDeliveryChannelAsync(string deliveryChannelName, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DeleteDeliveryChannel operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeleteDeliveryChannel operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeleteDeliveryChannelResponse> DeleteDeliveryChannelAsync(DeleteDeliveryChannelRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DeliverConfigSnapshot /// <summary> /// Schedules delivery of a configuration snapshot to the Amazon S3 bucket in the specified /// delivery channel. After the delivery has started, AWS Config sends following notifications /// using an Amazon SNS topic that you have specified. /// /// <ul> <li>Notification of starting the delivery.</li> <li>Notification of delivery /// completed, if the delivery was successfully completed.</li> <li>Notification of delivery /// failure, if the delivery failed to complete.</li> </ul> /// </summary> /// <param name="deliveryChannelName">The name of the delivery channel through which the snapshot is delivered.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DeliverConfigSnapshot service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoAvailableConfigurationRecorderException"> /// There are no configuration recorders available to provide the role needed to describe /// your resources. Create a configuration recorder. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoRunningConfigurationRecorderException"> /// There is no configuration recorder running. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> Task<DeliverConfigSnapshotResponse> DeliverConfigSnapshotAsync(string deliveryChannelName, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DeliverConfigSnapshot operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DeliverConfigSnapshot operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DeliverConfigSnapshotResponse> DeliverConfigSnapshotAsync(DeliverConfigSnapshotRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeConfigurationRecorders /// <summary> /// Returns the name of one or more specified configuration recorders. If the recorder /// name is not specified, this action returns the names of all the configuration recorders /// associated with the account. /// /// <note> /// <para> /// Currently, you can specify only one configuration recorder per account. /// </para> /// </note> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeConfigurationRecorders service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> Task<DescribeConfigurationRecordersResponse> DescribeConfigurationRecordersAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeConfigurationRecorders operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationRecorders operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeConfigurationRecordersResponse> DescribeConfigurationRecordersAsync(DescribeConfigurationRecordersRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeConfigurationRecorderStatus /// <summary> /// Returns the current status of the specified configuration recorder. If a configuration /// recorder is not specified, this action returns the status of all configuration recorder /// associated with the account. /// /// <note>Currently, you can specify only one configuration recorder per account.</note> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeConfigurationRecorderStatus service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> Task<DescribeConfigurationRecorderStatusResponse> DescribeConfigurationRecorderStatusAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeConfigurationRecorderStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeConfigurationRecorderStatus operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeConfigurationRecorderStatusResponse> DescribeConfigurationRecorderStatusAsync(DescribeConfigurationRecorderStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeDeliveryChannels /// <summary> /// Returns details about the specified delivery channel. If a delivery channel is not /// specified, this action returns the details of all delivery channels associated with /// the account. /// /// <note> /// <para> /// Currently, you can specify only one delivery channel per account. /// </para> /// </note> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeDeliveryChannels service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> Task<DescribeDeliveryChannelsResponse> DescribeDeliveryChannelsAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeDeliveryChannels operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeDeliveryChannels operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeDeliveryChannelsResponse> DescribeDeliveryChannelsAsync(DescribeDeliveryChannelsRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region DescribeDeliveryChannelStatus /// <summary> /// Returns the current status of the specified delivery channel. If a delivery channel /// is not specified, this action returns the current status of all delivery channels /// associated with the account. /// /// <note>Currently, you can specify only one delivery channel per account.</note> /// </summary> /// <param name="cancellationToken"> ttd1 /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the DescribeDeliveryChannelStatus service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchDeliveryChannelException"> /// You have specified a delivery channel that does not exist. /// </exception> Task<DescribeDeliveryChannelStatusResponse> DescribeDeliveryChannelStatusAsync(System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the DescribeDeliveryChannelStatus operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the DescribeDeliveryChannelStatus operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<DescribeDeliveryChannelStatusResponse> DescribeDeliveryChannelStatusAsync(DescribeDeliveryChannelStatusRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region GetResourceConfigHistory /// <summary> /// Initiates the asynchronous execution of the GetResourceConfigHistory operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the GetResourceConfigHistory operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<GetResourceConfigHistoryResponse> GetResourceConfigHistoryAsync(GetResourceConfigHistoryRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region ListDiscoveredResources /// <summary> /// Initiates the asynchronous execution of the ListDiscoveredResources operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the ListDiscoveredResources operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<ListDiscoveredResourcesResponse> ListDiscoveredResourcesAsync(ListDiscoveredResourcesRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutConfigurationRecorder /// <summary> /// Initiates the asynchronous execution of the PutConfigurationRecorder operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutConfigurationRecorder operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<PutConfigurationRecorderResponse> PutConfigurationRecorderAsync(PutConfigurationRecorderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region PutDeliveryChannel /// <summary> /// Initiates the asynchronous execution of the PutDeliveryChannel operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the PutDeliveryChannel operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<PutDeliveryChannelResponse> PutDeliveryChannelAsync(PutDeliveryChannelRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region StartConfigurationRecorder /// <summary> /// Starts recording configurations of the AWS resources you have selected to record in /// your AWS account. /// /// /// <para> /// You must have created at least one delivery channel to successfully start the configuration /// recorder. /// </para> /// </summary> /// <param name="configurationRecorderName">The name of the recorder object that records each configuration change made to the resources.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the StartConfigurationRecorder service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoAvailableDeliveryChannelException"> /// There is no delivery channel available to record configurations. /// </exception> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> Task<StartConfigurationRecorderResponse> StartConfigurationRecorderAsync(string configurationRecorderName, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the StartConfigurationRecorder operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StartConfigurationRecorder operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<StartConfigurationRecorderResponse> StartConfigurationRecorderAsync(StartConfigurationRecorderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion #region StopConfigurationRecorder /// <summary> /// Stops recording configurations of the AWS resources you have selected to record in /// your AWS account. /// </summary> /// <param name="configurationRecorderName">The name of the recorder object that records each configuration change made to the resources.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// /// <returns>The response from the StopConfigurationRecorder service method, as returned by ConfigService.</returns> /// <exception cref="Amazon.ConfigService.Model.NoSuchConfigurationRecorderException"> /// You have specified a configuration recorder that does not exist. /// </exception> Task<StopConfigurationRecorderResponse> StopConfigurationRecorderAsync(string configurationRecorderName, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Initiates the asynchronous execution of the StopConfigurationRecorder operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the StopConfigurationRecorder operation.</param> /// <param name="cancellationToken"> /// A cancellation token that can be used by other objects or threads to receive notice of cancellation. /// </param> /// <returns>The task object representing the asynchronous operation.</returns> Task<StopConfigurationRecorderResponse> StopConfigurationRecorderAsync(StopConfigurationRecorderRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)); #endregion } }
//------------------------------------------------------------------------------ // Microsoft Avalon // Copyright (c) Microsoft Corporation. All Rights Reserved. // // File: InteropBitmap.cs // //------------------------------------------------------------------------------ using System; using System.IO; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design.Serialization; using System.Reflection; using MS.Internal; using MS.Win32.PresentationCore; using System.Security; using System.Security.Permissions; using System.Diagnostics; using System.Windows.Media; using System.Globalization; using System.Runtime.InteropServices; using System.Windows.Media.Animation; using System.Windows.Media.Composition; using MS.Internal.PresentationCore; // SecurityHelper using SR=MS.Internal.PresentationCore.SR; using SRID=MS.Internal.PresentationCore.SRID; using System.Windows.Media.Imaging; namespace System.Windows.Interop { #region InteropBitmap /// <summary> /// InteropBitmap provides caching functionality for a BitmapSource. /// </summary> public sealed class InteropBitmap : BitmapSource { /// <summary> /// </summary> /// <SecurityNote> /// Critical - Indirectly sets critical resources /// TreatAsSafe - No inputs, does not touch any critical data with external input. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] private InteropBitmap() : base(true) { SecurityHelper.DemandUnmanagedCode(); } /// <summary> /// Construct a BitmapSource from an HBITMAP. /// </summary> /// <param name="hbitmap"></param> /// <param name="hpalette"></param> /// <param name="sourceRect"></param> /// <param name="sizeOptions"></param> /// <param name="alphaOptions"></param> /// <SecurityNote> /// Critical - access unsafe code, accepts handle parameters /// </SecurityNote> [SecurityCritical] internal InteropBitmap(IntPtr hbitmap, IntPtr hpalette, Int32Rect sourceRect, BitmapSizeOptions sizeOptions, WICBitmapAlphaChannelOption alphaOptions) : base(true) // Use virtuals { _bitmapInit.BeginInit(); using (FactoryMaker myFactory = new FactoryMaker()) { HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFromHBITMAP( myFactory.ImagingFactoryPtr, hbitmap, hpalette, alphaOptions, out _unmanagedSource)); Debug.Assert (_unmanagedSource != null && !_unmanagedSource.IsInvalid); } _unmanagedSource.CalculateSize(); _sizeOptions = sizeOptions; _sourceRect = sourceRect; _syncObject = _unmanagedSource; _bitmapInit.EndInit(); FinalizeCreation(); } /// <summary> /// Construct a BitmapSource from an HICON. /// </summary> /// <param name="hicon"></param> /// <param name="sourceRect"></param> /// <param name="sizeOptions"></param> /// <SecurityNote> /// Critical - access unmanaged objects/resources, accepts unmanaged handle as argument /// TreatAsSafe - demands unmanaged code permission /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal InteropBitmap(IntPtr hicon, Int32Rect sourceRect, BitmapSizeOptions sizeOptions) : base(true) // Use virtuals { SecurityHelper.DemandUnmanagedCode(); _bitmapInit.BeginInit(); using (FactoryMaker myFactory = new FactoryMaker()) { HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFromHICON( myFactory.ImagingFactoryPtr, hicon, out _unmanagedSource)); Debug.Assert (_unmanagedSource != null && !_unmanagedSource.IsInvalid); } _unmanagedSource.CalculateSize(); _sourceRect = sourceRect; _sizeOptions = sizeOptions; _syncObject = _unmanagedSource; _bitmapInit.EndInit(); FinalizeCreation(); } /// <summary> /// Construct a BitmapSource from a memory section. /// </summary> /// <param name="section"></param> /// <param name="pixelWidth"></param> /// <param name="pixelHeight"></param> /// <param name="format"></param> /// <param name="stride"></param> /// <param name="offset"></param> /// <SecurityNote> /// Critical - access unmanaged objects/resources, accepts unmanaged handle as argument /// TreatAsSafe - demands unmanaged code permission /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] internal InteropBitmap( IntPtr section, int pixelWidth, int pixelHeight, PixelFormat format, int stride, int offset) : base(true) // Use virtuals { SecurityHelper.DemandUnmanagedCode(); _bitmapInit.BeginInit(); if (pixelWidth <= 0) { throw new ArgumentOutOfRangeException("pixelWidth", SR.Get(SRID.ParameterMustBeGreaterThanZero)); } if (pixelHeight <= 0) { throw new ArgumentOutOfRangeException("pixelHeight", SR.Get(SRID.ParameterMustBeGreaterThanZero)); } Guid formatGuid = format.Guid; HRESULT.Check(UnsafeNativeMethods.WindowsCodecApi.CreateBitmapFromSection( (uint)pixelWidth, (uint)pixelHeight, ref formatGuid, section, (uint)stride, (uint)offset, out _unmanagedSource )); Debug.Assert (_unmanagedSource != null && !_unmanagedSource.IsInvalid); _unmanagedSource.CalculateSize(); _sourceRect = Int32Rect.Empty; _sizeOptions = null; _syncObject = _unmanagedSource; _bitmapInit.EndInit(); FinalizeCreation(); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>. /// </summary> /// <returns>The new Freezable.</returns> /// <SecurityNote> /// Critical - accesses critical code. /// TreatAsSafe - method only produces clone of original image. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override Freezable CreateInstanceCore() { return new InteropBitmap(); } /// <summary> /// Common Copy method used to implement CloneCore() and CloneCurrentValueCore(), /// GetAsFrozenCore(), and GetCurrentValueAsFrozenCore(). /// </summary> /// <SecurityNote> /// Critical - calls unmanaged objects /// </SecurityNote> [SecurityCritical] private void CopyCommon(InteropBitmap sourceBitmapSource) { // Avoid Animatable requesting resource updates for invalidations that occur during construction Animatable_IsResourceInvalidationNecessary = false; _unmanagedSource = sourceBitmapSource._unmanagedSource; _sourceRect = sourceBitmapSource._sourceRect; _sizeOptions = sourceBitmapSource._sizeOptions; InitFromWICSource(sourceBitmapSource.WicSourceHandle); // The next invalidation will cause Animatable to register an UpdateResource callback Animatable_IsResourceInvalidationNecessary = true; } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCore(Freezable)">Freezable.CloneCore</see>. /// </summary> /// <SecurityNote> /// Critical - accesses critical code. /// TreatAsSafe - method only produces clone of original image. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override void CloneCore(Freezable sourceFreezable) { InteropBitmap sourceBitmapSource = (InteropBitmap)sourceFreezable; base.CloneCore(sourceFreezable); CopyCommon(sourceBitmapSource); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(Freezable)">Freezable.CloneCurrentValueCore</see>. /// </summary> /// <SecurityNote> /// Critical - accesses critical code. /// TreatAsSafe - method only produces clone of original image. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override void CloneCurrentValueCore(Freezable sourceFreezable) { InteropBitmap sourceBitmapSource = (InteropBitmap)sourceFreezable; base.CloneCurrentValueCore(sourceFreezable); CopyCommon(sourceBitmapSource); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(Freezable)">Freezable.GetAsFrozenCore</see>. /// </summary> /// <SecurityNote> /// Critical - accesses critical code. /// TreatAsSafe - method only produces GetAsFrozen of original image. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override void GetAsFrozenCore(Freezable sourceFreezable) { InteropBitmap sourceBitmapSource = (InteropBitmap)sourceFreezable; base.GetAsFrozenCore(sourceFreezable); CopyCommon(sourceBitmapSource); } /// <summary> /// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>. /// </summary> /// <SecurityNote> /// Critical - accesses critical code. /// TreatAsSafe - method only produces GetCurrentValueAsFrozen of original image. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override void GetCurrentValueAsFrozenCore(Freezable sourceFreezable) { InteropBitmap sourceBitmapSource = (InteropBitmap)sourceFreezable; base.GetCurrentValueAsFrozenCore(sourceFreezable); CopyCommon(sourceBitmapSource); } /// /// Create from WICBitmapSource /// /// <SecurityNote> /// Critical - calls unmanaged objects /// </SecurityNote> [SecurityCritical] private void InitFromWICSource( SafeMILHandle wicSource ) { _bitmapInit.BeginInit(); BitmapSourceSafeMILHandle bitmapSource = null; lock (_syncObject) { using (FactoryMaker factoryMaker = new FactoryMaker()) { HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFromSource( factoryMaker.ImagingFactoryPtr, wicSource, WICBitmapCreateCacheOptions.WICBitmapCacheOnLoad, out bitmapSource)); } bitmapSource.CalculateSize(); } WicSourceHandle = bitmapSource; _isSourceCached = true; _bitmapInit.EndInit(); UpdateCachedSettings(); } /// <summary> /// Invalidates the bitmap source. /// </summary> /// <SecurityNote> /// Critical - calls critical code, access unmanaged resources /// PublicOK - demands unmanaged code permission /// </SecurityNote> [SecurityCritical] public void Invalidate() { Invalidate(null); } /// <summary> /// Invalidates the bitmap source. /// </summary> /// <SecurityNote> /// Critical - calls critical code, access unmanaged resources /// PublicOK - demands unmanaged code permission /// </SecurityNote> [SecurityCritical] public void Invalidate(Int32Rect? dirtyRect) { SecurityHelper.DemandUnmanagedCode(); // A null dirty rect indicates the entire bitmap should be // invalidated, while a value indicates that only a dirty rect // should be invalidated. if (dirtyRect.HasValue) { dirtyRect.Value.ValidateForDirtyRect("dirtyRect", _pixelWidth, _pixelHeight); if (!dirtyRect.Value.HasArea) { // Nothing needs done. return; } } WritePreamble(); if (_unmanagedSource != null) { if(UsableWithoutCache) { // For bitmap sources that do not require caching on the // UI thread, we can just add a dirty rect to the // CWICWrapperBitmap. The render thread will respond by // updating the affected realizations by copying from this // bitmap. Since this bitmap is not cached, it will get // the most current bits. unsafe { for (int i = 0, numChannels = _duceResource.GetChannelCount(); i < numChannels; ++i) { DUCE.Channel channel = _duceResource.GetChannel(i); DUCE.MILCMD_BITMAP_INVALIDATE data; data.Type = MILCMD.MilCmdBitmapInvalidate; data.Handle = _duceResource.GetHandle(channel); bool useDirtyRect = dirtyRect.HasValue; if(useDirtyRect) { data.DirtyRect.left = dirtyRect.Value.X; data.DirtyRect.top = dirtyRect.Value.Y; data.DirtyRect.right = dirtyRect.Value.X + dirtyRect.Value.Width; data.DirtyRect.bottom = dirtyRect.Value.Y + dirtyRect.Value.Height; } data.UseDirtyRect = (uint)(useDirtyRect ? 1 : 0); channel.SendCommand((byte*)&data, sizeof(DUCE.MILCMD_BITMAP_INVALIDATE)); } } } else { // For bitmap sources that require caching on the // UI thread, we can't just add a dirty rect to the // CWICWrapperBitmap because it will just read the cached // contents again. We really need a caching bitmap // implementation that understands dirty rects and will // update its cache. Unfortunately, today the caching // bitmap is a standard WIC implementation, and does not // support this functionality. // // For now, we just recreate the caching bitmap. Setting // _needsUpdate to true will cause BitmapSource to throw // away the old DUCECompatiblePtr, and create a new caching // bitmap to send to the render thread. Since the render // thread sees a brand new bitmap, it will copy the bits out. _needsUpdate = true; RegisterForAsyncUpdateResource(); } } WritePostscript(); } // ISupportInitialize /// /// Create the unmanaged resources /// /// <SecurityNote> /// Critical - access unmanaged objects/resources /// </SecurityNote> [SecurityCritical] internal override void FinalizeCreation() { BitmapSourceSafeMILHandle wicClipper = null; BitmapSourceSafeMILHandle wicTransformer = null; BitmapSourceSafeMILHandle transformedSource = _unmanagedSource; HRESULT.Check(UnsafeNativeMethods.WICBitmap.SetResolution(_unmanagedSource, 96, 96)); using (FactoryMaker factoryMaker = new FactoryMaker()) { IntPtr wicFactory = factoryMaker.ImagingFactoryPtr; if (!_sourceRect.IsEmpty) { HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapClipper( wicFactory, out wicClipper)); lock (_syncObject) { HRESULT.Check(UnsafeNativeMethods.WICBitmapClipper.Initialize( wicClipper, transformedSource, ref _sourceRect)); } transformedSource = wicClipper; } if (_sizeOptions != null) { if (_sizeOptions.DoesScale) { Debug.Assert(_sizeOptions.Rotation == Rotation.Rotate0); uint width, height; _sizeOptions.GetScaledWidthAndHeight( (uint)_sizeOptions.PixelWidth, (uint)_sizeOptions.PixelHeight, out width, out height); HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapScaler( wicFactory, out wicTransformer)); lock (_syncObject) { HRESULT.Check(UnsafeNativeMethods.WICBitmapScaler.Initialize( wicTransformer, transformedSource, width, height, WICInterpolationMode.Fant)); } } else if (_sizeOptions.Rotation != Rotation.Rotate0) { HRESULT.Check(UnsafeNativeMethods.WICImagingFactory.CreateBitmapFlipRotator( wicFactory, out wicTransformer)); lock (_syncObject) { HRESULT.Check(UnsafeNativeMethods.WICBitmapFlipRotator.Initialize( wicTransformer, transformedSource, _sizeOptions.WICTransformOptions)); } } if (wicTransformer != null) { transformedSource = wicTransformer; } } WicSourceHandle = transformedSource; // Since the original source is an HICON, HBITMAP or section, we know it's cached. // FlipRotate and Clipper do not affect our cache performance. _isSourceCached = true; } CreationCompleted = true; UpdateCachedSettings(); } /// <SecurityNote> /// Critical - unmanaged resource - not safe to hand out /// </SecurityNote> [SecurityCritical] private BitmapSourceSafeMILHandle /* IWICBitmapSource */ _unmanagedSource = null; private Int32Rect _sourceRect = Int32Rect.Empty; private BitmapSizeOptions _sizeOptions = null; } #endregion // InteropBitmap }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Threading.Tasks; using DotVVM.Framework.Compilation; using DotVVM.Framework.Configuration; using DotVVM.Framework.Controls; using DotVVM.Framework.Runtime; using DotVVM.Framework.Runtime.Filters; using DotVVM.Framework.Security; using DotVVM.Framework.Utils; using DotVVM.Framework.ViewModel; using DotVVM.Framework.ViewModel.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace DotVVM.Framework.Hosting { [NotAuthorized] // DotvvmPresenter handles authorization itself, allowing authorization on it would make [NotAuthorized] attribute useless on ViewModel, since request would be interrupted earlier that VM is found public class DotvvmPresenter : IDotvvmPresenter { /// <summary> /// Initializes a new instance of the <see cref="DotvvmPresenter" /> class. /// </summary> public DotvvmPresenter(DotvvmConfiguration configuration, IDotvvmViewBuilder viewBuilder, IViewModelLoader viewModelLoader, IViewModelSerializer viewModelSerializer, IOutputRenderer outputRender, ICsrfProtector csrfProtector) { DotvvmViewBuilder = viewBuilder; ViewModelLoader = viewModelLoader; ViewModelSerializer = viewModelSerializer; OutputRenderer = outputRender; CsrfProtector = csrfProtector; ApplicationPath = configuration.ApplicationPhysicalPath; } public IDotvvmViewBuilder DotvvmViewBuilder { get; } public IViewModelLoader ViewModelLoader { get; } public IViewModelSerializer ViewModelSerializer { get; } public IOutputRenderer OutputRenderer { get; } public ICsrfProtector CsrfProtector { get; } public string ApplicationPath { get; } /// <summary> /// Processes the request. /// </summary> public async Task ProcessRequest(IDotvvmRequestContext context) { try { await ProcessRequestCore(context); } catch (UnauthorizedAccessException) { context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized; } catch (DotvvmControlException ex) { if (ex.FileName != null) { ex.FileName = Path.Combine(ApplicationPath, ex.FileName); } throw; } } /// <summary> /// </summary> /// <param name="context"></param> /// <returns></returns> public async Task ProcessRequestCore(IDotvvmRequestContext context) { if (context.HttpContext.Request.Method != "GET" && context.HttpContext.Request.Method != "POST") { // unknown HTTP method context.HttpContext.Response.StatusCode = (int)HttpStatusCode.MethodNotAllowed; throw new DotvvmHttpException("Only GET and POST methods are supported!"); } if (context.HttpContext.Request.Headers["X-PostbackType"] == "StaticCommand") { await ProcessStaticCommandRequest(context); return; } var isPostBack = context.IsPostBack = DetermineIsPostBack(context.HttpContext); // build the page view var page = DotvvmViewBuilder.BuildView(context); page.SetValue(Internal.RequestContextProperty, context); context.View = page; // locate and create the view model context.ViewModel = ViewModelLoader.InitializeViewModel(context, page); // get action filters var viewModelFilters = ActionFilterHelper.GetActionFilters<IViewModelActionFilter>(context.ViewModel.GetType().GetTypeInfo()); viewModelFilters.AddRange(context.Configuration.Runtime.GlobalFilters.OfType<IViewModelActionFilter>()); var requestFilters = ActionFilterHelper.GetActionFilters<IRequestActionFilter>(context.ViewModel.GetType().GetTypeInfo()); foreach (var f in requestFilters) await f.OnPageLoadingAsync(context); try { // run the preinit phase in the page DotvvmControlCollection.InvokePageLifeCycleEventRecursive(page, LifeCycleEventType.PreInit); page.DataContext = context.ViewModel; // run OnViewModelCreated on action filters foreach (var filter in viewModelFilters) { await filter.OnViewModelCreatedAsync(context); } // init the view model lifecycle if (context.ViewModel is IDotvvmViewModel) { ((IDotvvmViewModel)context.ViewModel).Context = context; await ((IDotvvmViewModel)context.ViewModel).Init(); } // run the init phase in the page DotvvmControlCollection.InvokePageLifeCycleEventRecursive(page, LifeCycleEventType.Init); if (!isPostBack) { // perform standard get if (context.ViewModel is IDotvvmViewModel) { await ((IDotvvmViewModel)context.ViewModel).Load(); } // run the load phase in the page DotvvmControlCollection.InvokePageLifeCycleEventRecursive(page, LifeCycleEventType.Load); } else { // perform the postback string postData; using (var sr = new StreamReader(context.HttpContext.Request.Body)) { postData = await sr.ReadToEndAsync(); } ViewModelSerializer.PopulateViewModel(context, postData); // validate CSRF token CsrfProtector.VerifyToken(context, context.CsrfToken); if (context.ViewModel is IDotvvmViewModel) { await ((IDotvvmViewModel)context.ViewModel).Load(); } // validate CSRF token CsrfProtector.VerifyToken(context, context.CsrfToken); // run the load phase in the page DotvvmControlCollection.InvokePageLifeCycleEventRecursive(page, LifeCycleEventType.Load); // invoke the postback command ActionInfo actionInfo; ViewModelSerializer.ResolveCommand(context, page, postData, out actionInfo); if (actionInfo != null) { // get filters var methodFilters = context.Configuration.Runtime.GlobalFilters.OfType<ICommandActionFilter>() .Concat(ActionFilterHelper.GetActionFilters<ICommandActionFilter>(context.ViewModel.GetType().GetTypeInfo())); if (actionInfo.Binding.ActionFilters != null) methodFilters = methodFilters.Concat(actionInfo.Binding.ActionFilters.OfType<ICommandActionFilter>()); await ExecuteCommand(actionInfo, context, methodFilters); } } if (context.ViewModel is IDotvvmViewModel) { await ((IDotvvmViewModel)context.ViewModel).PreRender(); } // run the prerender phase in the page DotvvmControlCollection.InvokePageLifeCycleEventRecursive(page, LifeCycleEventType.PreRender); // run the prerender complete phase in the page DotvvmControlCollection.InvokePageLifeCycleEventRecursive(page, LifeCycleEventType.PreRenderComplete); // generate CSRF token if required if (string.IsNullOrEmpty(context.CsrfToken)) { context.CsrfToken = CsrfProtector.GenerateToken(context); } // run OnResponseRendering on action filters foreach (var filter in viewModelFilters) { await filter.OnResponseRenderingAsync(context); } // render the output ViewModelSerializer.BuildViewModel(context); if (!context.IsInPartialRenderingMode) { // standard get await OutputRenderer.WriteHtmlResponse(context, page); } else { // postback or SPA content OutputRenderer.RenderPostbackUpdatedControls(context, page); ViewModelSerializer.AddPostBackUpdatedControls(context); await OutputRenderer.WriteViewModelResponse(context, page); } if (context.ViewModel != null) { ViewModelLoader.DisposeViewModel(context.ViewModel); } foreach (var f in requestFilters) await f.OnPageLoadedAsync(context); } catch (DotvvmInterruptRequestExecutionException) { throw; } catch (DotvvmHttpException) { throw; } catch (Exception ex) { // run OnPageException on action filters foreach (var filter in requestFilters) { await filter.OnPageExceptionAsync(context, ex); if (context.IsPageExceptionHandled) { context.InterruptRequest(); } } throw; } } public async Task ProcessStaticCommandRequest(IDotvvmRequestContext context) { JObject postData; using (var jsonReader = new JsonTextReader(new StreamReader(context.HttpContext.Request.Body))) { postData = JObject.Load(jsonReader); } // validate csrf token context.CsrfToken = postData["$csrfToken"].Value<string>(); CsrfProtector.VerifyToken(context, context.CsrfToken); var command = postData["command"].Value<string>(); var arguments = postData["args"] as JArray; var lastDot = command.LastIndexOf('.'); var typeName = command.Remove(lastDot); var methodName = command.Substring(lastDot + 1); var methodInfo = Type.GetType(typeName).GetMethod(methodName); if (!methodInfo.IsDefined(typeof(AllowStaticCommandAttribute))) { throw new DotvvmHttpException($"This method cannot be called from the static command. If you need to call this method, add the '{nameof(AllowStaticCommandAttribute)}' to the method."); } var target = methodInfo.IsStatic ? null : arguments[0].ToObject(methodInfo.DeclaringType); var methodArguments = arguments.Skip(methodInfo.IsStatic ? 0 : 1) .Zip(methodInfo.GetParameters(), (arg, parameter) => arg.ToObject(parameter.ParameterType)) .ToArray(); var actionInfo = new ActionInfo { IsControlCommand = false, Action = () => methodInfo.Invoke(target, methodArguments) }; var filters = context.Configuration.Runtime.GlobalFilters.OfType<ICommandActionFilter>() .Concat(ActionFilterHelper.GetActionFilters<ICommandActionFilter>(methodInfo)) .ToArray(); var result = await ExecuteCommand(actionInfo, context, filters); using (var writer = new StreamWriter(context.HttpContext.Response.Body)) { writer.WriteLine(JsonConvert.SerializeObject(result)); } } protected async Task<object> ExecuteCommand(ActionInfo action, IDotvvmRequestContext context, IEnumerable<ICommandActionFilter> methodFilters) { // run OnCommandExecuting on action filters foreach (var filter in methodFilters) { await filter.OnCommandExecutingAsync(context, action); } object result = null; Task resultTask = null; try { result = action.Action(); resultTask = result as Task; } catch (Exception ex) { if (ex is TargetInvocationException) { ex = ex.InnerException; } if (ex is DotvvmInterruptRequestExecutionException) { throw new DotvvmInterruptRequestExecutionException("The request execution was interrupted in the command!", ex); } context.CommandException = ex; } // run OnCommandExecuted on action filters foreach (var filter in methodFilters.Reverse()) { await filter.OnCommandExecutedAsync(context, action, context.CommandException); } if (context.CommandException != null && !context.IsCommandExceptionHandled) { throw new Exception("Unhandled exception occured in the command!", context.CommandException); } if (resultTask != null) { await resultTask; return TaskUtils.GetResult(resultTask); } return result; } public static bool DetermineIsPostBack(IHttpContext context) { return context.Request.Method == "POST" && context.Request.Headers.ContainsKey(HostingConstants.SpaPostBackHeaderName); } public static bool DetermineSpaRequest(IHttpContext context) { return !string.IsNullOrEmpty(context.Request.Headers[HostingConstants.SpaContentPlaceHolderHeaderName]); } public static bool DeterminePartialRendering(IHttpContext context) { return DetermineIsPostBack(context) || DetermineSpaRequest(context); } public static string DetermineSpaContentPlaceHolderUniqueId(IHttpContext context) { return context.Request.Headers[HostingConstants.SpaContentPlaceHolderHeaderName]; } } }
// ==++== // // Copyright (c) Microsoft Corporation. All rights reserved. // // ==--== // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // TaskAwaiter.cs // // <OWNER>[....]</OWNER> // // Types for awaiting Task and Task<T>. These types are emitted from Task{<T>}.GetAwaiter // and Task{<T>}.ConfigureAwait. They are meant to be used only by the compiler, e.g. // // await nonGenericTask; // ===================== // var $awaiter = nonGenericTask.GetAwaiter(); // if (!$awaiter.IsCompleted) // { // SPILL: // $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this); // return; // Label: // UNSPILL; // } // $awaiter.GetResult(); // // result += await genericTask.ConfigureAwait(false); // =================================================================================== // var $awaiter = genericTask.ConfigureAwait(false).GetAwaiter(); // if (!$awaiter.IsCompleted) // { // SPILL; // $builder.AwaitUnsafeOnCompleted(ref $awaiter, ref this); // return; // Label: // UNSPILL; // } // result += $awaiter.GetResult(); // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Security; using System.Threading; using System.Threading.Tasks; using System.Security.Permissions; using System.Diagnostics.Tracing; // NOTE: For performance reasons, initialization is not verified. If a developer // incorrectly initializes a task awaiter, which should only be done by the compiler, // NullReferenceExceptions may be generated (the alternative would be for us to detect // this case and then throw a different exception instead). This is the same tradeoff // that's made with other compiler-focused value types like List<T>.Enumerator. namespace System.Runtime.CompilerServices { /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> [HostProtection(Synchronization = true, ExternalThreading = true)] public struct TaskAwaiter : ICriticalNotifyCompletion { /// <summary>The task being awaited.</summary> private readonly Task m_task; /// <summary>Initializes the <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to be awaited.</param> internal TaskAwaiter(Task task) { Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); m_task = task; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [SecuritySafeCritical] public void OnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.InvalidOperationException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [SecurityCritical] public void UnsafeOnCompleted(Action continuation) { OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> public void GetResult() { ValidateEnd(m_task); } /// <summary> /// Fast checks for the end of an await operation to determine whether more needs to be done /// prior to completing the await. /// </summary> /// <param name="task">The awaited task.</param> internal static void ValidateEnd(Task task) { // Fast checks that can be inlined. if (task.IsWaitNotificationEnabledOrNotRanToCompletion) { // If either the end await bit is set or we're not completed successfully, // fall back to the slower path. HandleNonSuccessAndDebuggerNotification(task); } } /// <summary> /// Ensures the task is completed, triggers any necessary debugger breakpoints for completing /// the await on the task, and throws an exception if the task did not complete successfully. /// </summary> /// <param name="task">The awaited task.</param> private static void HandleNonSuccessAndDebuggerNotification(Task task) { // NOTE: The JIT refuses to inline ValidateEnd when it contains the contents // of HandleNonSuccessAndDebuggerNotification, hence the separation. // Synchronously wait for the task to complete. When used by the compiler, // the task will already be complete. This code exists only for direct GetResult use, // for cases where the same exception propagation semantics used by "await" are desired, // but where for one reason or another synchronous rather than asynchronous waiting is needed. if (!task.IsCompleted) { bool taskCompleted = task.InternalWait(Timeout.Infinite, default(CancellationToken)); Contract.Assert(taskCompleted, "With an infinite timeout, the task should have always completed."); } // Now that we're done, alert the debugger if so requested task.NotifyDebuggerOfWaitCompletionIfNecessary(); // And throw an exception if the task is faulted or canceled. if (!task.IsRanToCompletion) ThrowForNonSuccess(task); } /// <summary>Throws an exception to handle a task that completed in a state other than RanToCompletion.</summary> private static void ThrowForNonSuccess(Task task) { Contract.Requires(task.IsCompleted, "Task must have been completed by now."); Contract.Requires(task.Status != TaskStatus.RanToCompletion, "Task should not be completed successfully."); // Handle whether the task has been canceled or faulted switch (task.Status) { // If the task completed in a canceled state, throw an OperationCanceledException. // This will either be the OCE that actually caused the task to cancel, or it will be a new // TaskCanceledException. TCE derives from OCE, and by throwing it we automatically pick up the // completed task's CancellationToken if it has one, including that CT in the OCE. case TaskStatus.Canceled: var oceEdi = task.GetCancellationExceptionDispatchInfo(); if (oceEdi != null) { oceEdi.Throw(); Contract.Assert(false, "Throw() should have thrown"); } throw new TaskCanceledException(task); // If the task faulted, throw its first exception, // even if it contained more than one. case TaskStatus.Faulted: var edis = task.GetExceptionDispatchInfos(); if (edis.Count > 0) { edis[0].Throw(); Contract.Assert(false, "Throw() should have thrown"); break; // Necessary to compile: non-reachable, but compiler can't determine that } else { Contract.Assert(false, "There should be exceptions if we're Faulted."); throw task.Exception; } } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="task">The task being awaited.</param> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <param name="continueOnCapturedContext">Whether to capture and marshal back to the current context.</param> /// <param name="flowExecutionContext">Whether to flow ExecutionContext across the await.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [MethodImplAttribute(MethodImplOptions.NoInlining)] // Methods containing StackCrawlMark local var have to be marked non-inlineable [SecurityCritical] internal static void OnCompletedInternal(Task task, Action continuation, bool continueOnCapturedContext, bool flowExecutionContext) { if (continuation == null) throw new ArgumentNullException("continuation"); StackCrawlMark stackMark = StackCrawlMark.LookForMyCaller; // If TaskWait* ETW events are enabled, trace a beginning event for this await // and set up an ending event to be traced when the asynchronous await completes. if ( TplEtwProvider.Log.IsEnabled() || Task.s_asyncDebuggingEnabled) { continuation = OutputWaitEtwEvents(task, continuation); } // Set the continuation onto the awaited task. task.SetContinuationForAwait(continuation, continueOnCapturedContext, flowExecutionContext, ref stackMark); } /// <summary> /// Outputs a WaitBegin ETW event, and augments the continuation action to output a WaitEnd ETW event. /// </summary> /// <param name="task">The task being awaited.</param> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <returns>The action to use as the actual continuation.</returns> private static Action OutputWaitEtwEvents(Task task, Action continuation) { Contract.Requires(task != null, "Need a task to wait on"); Contract.Requires(continuation != null, "Need a continuation to invoke when the wait completes"); if (Task.s_asyncDebuggingEnabled) { Task.AddToActiveTasks(task); } var etwLog = TplEtwProvider.Log; if (etwLog.IsEnabled()) { // ETW event for Task Wait Begin var currentTaskAtBegin = Task.InternalCurrent; // If this task's continuation is another task, get it. var continuationTask = AsyncMethodBuilderCore.TryGetContinuationTask(continuation); etwLog.TaskWaitBegin( (currentTaskAtBegin != null ? currentTaskAtBegin.m_taskScheduler.Id : TaskScheduler.Default.Id), (currentTaskAtBegin != null ? currentTaskAtBegin.Id : 0), task.Id, TplEtwProvider.TaskWaitBehavior.Asynchronous, (continuationTask != null ? continuationTask.Id : 0), System.Threading.Thread.GetDomainID()); } // Create a continuation action that outputs the end event and then invokes the user // provided delegate. This incurs the allocations for the closure/delegate, but only if the event // is enabled, and in doing so it allows us to pass the awaited task's information into the end event // in a purely pay-for-play manner (the alternatively would be to increase the size of TaskAwaiter // just for this ETW purpose, not pay-for-play, since GetResult would need to know whether a real yield occurred). return AsyncMethodBuilderCore.CreateContinuationWrapper(continuation, () => { if (Task.s_asyncDebuggingEnabled) { Task.RemoveFromActiveTasks(task.Id); } // ETW event for Task Wait End. Guid prevActivityId = new Guid(); bool bEtwLogEnabled = etwLog.IsEnabled(); if (bEtwLogEnabled) { var currentTaskAtEnd = Task.InternalCurrent; etwLog.TaskWaitEnd( (currentTaskAtEnd != null ? currentTaskAtEnd.m_taskScheduler.Id : TaskScheduler.Default.Id), (currentTaskAtEnd != null ? currentTaskAtEnd.Id : 0), task.Id); // Ensure the continuation runs under the activity ID of the task that completed for the // case the antecendent is a promise (in the other cases this is already the case). if (etwLog.TasksSetActivityIds && (task.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0) EventSource.SetCurrentThreadActivityId(TplEtwProvider.CreateGuidForTaskID(task.Id), out prevActivityId); } // Invoke the original continuation provided to OnCompleted. continuation(); if (bEtwLogEnabled) { etwLog.TaskWaitContinuationComplete(task.Id); if (etwLog.TasksSetActivityIds && (task.Options & (TaskCreationOptions)InternalTaskOptions.PromiseTask) != 0) EventSource.SetCurrentThreadActivityId(prevActivityId); } }); } } /// <summary>Provides an awaiter for awaiting a <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> [HostProtection(Synchronization = true, ExternalThreading = true)] public struct TaskAwaiter<TResult> : ICriticalNotifyCompletion { /// <summary>The task being awaited.</summary> private readonly Task<TResult> m_task; /// <summary>Initializes the <see cref="TaskAwaiter{TResult}"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task{TResult}"/> to be awaited.</param> internal TaskAwaiter(Task<TResult> task) { Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); m_task = task; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [SecuritySafeCritical] public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [SecurityCritical] public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, continueOnCapturedContext:true, flowExecutionContext:false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.ResultOnSuccess; } } /// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public struct ConfiguredTaskAwaitable { /// <summary>The task being awaited.</summary> private readonly ConfiguredTaskAwaitable.ConfiguredTaskAwaiter m_configuredTaskAwaiter; /// <summary>Initializes the <see cref="ConfiguredTaskAwaitable"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaitable(Task task, bool continueOnCapturedContext) { Contract.Requires(task != null, "Constructing an awaitable requires a task to await."); m_configuredTaskAwaiter = new ConfiguredTaskAwaitable.ConfiguredTaskAwaiter(task, continueOnCapturedContext); } /// <summary>Gets an awaiter for this awaitable.</summary> /// <returns>The awaiter.</returns> public ConfiguredTaskAwaitable.ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> [HostProtection(Synchronization = true, ExternalThreading = true)] public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion { /// <summary>The task being awaited.</summary> private readonly Task m_task; /// <summary>Whether to attempt marshaling back to the original context.</summary> private readonly bool m_continueOnCapturedContext; /// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary> /// <param name="task">The <see cref="System.Threading.Tasks.Task"/> to await.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured /// when BeginAwait is called; otherwise, false. /// </param> internal ConfiguredTaskAwaiter(Task task, bool continueOnCapturedContext) { Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [SecuritySafeCritical] public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [SecurityCritical] public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> public void GetResult() { TaskAwaiter.ValidateEnd(m_task); } } } /// <summary>Provides an awaitable object that allows for configured awaits on <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> public struct ConfiguredTaskAwaitable<TResult> { /// <summary>The underlying awaitable on whose logic this awaitable relies.</summary> private readonly ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter m_configuredTaskAwaiter; /// <summary>Initializes the <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaitable(Task<TResult> task, bool continueOnCapturedContext) { m_configuredTaskAwaiter = new ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter(task, continueOnCapturedContext); } /// <summary>Gets an awaiter for this awaitable.</summary> /// <returns>The awaiter.</returns> public ConfiguredTaskAwaitable<TResult>.ConfiguredTaskAwaiter GetAwaiter() { return m_configuredTaskAwaiter; } /// <summary>Provides an awaiter for a <see cref="ConfiguredTaskAwaitable{TResult}"/>.</summary> /// <remarks>This type is intended for compiler use only.</remarks> [HostProtection(Synchronization = true, ExternalThreading = true)] public struct ConfiguredTaskAwaiter : ICriticalNotifyCompletion { /// <summary>The task being awaited.</summary> private readonly Task<TResult> m_task; /// <summary>Whether to attempt marshaling back to the original context.</summary> private readonly bool m_continueOnCapturedContext; /// <summary>Initializes the <see cref="ConfiguredTaskAwaiter"/>.</summary> /// <param name="task">The awaitable <see cref="System.Threading.Tasks.Task{TResult}"/>.</param> /// <param name="continueOnCapturedContext"> /// true to attempt to marshal the continuation back to the original context captured; otherwise, false. /// </param> internal ConfiguredTaskAwaiter(Task<TResult> task, bool continueOnCapturedContext) { Contract.Requires(task != null, "Constructing an awaiter requires a task to await."); m_task = task; m_continueOnCapturedContext = continueOnCapturedContext; } /// <summary>Gets whether the task being awaited is completed.</summary> /// <remarks>This property is intended for compiler user rather than use directly in code.</remarks> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> public bool IsCompleted { get { return m_task.IsCompleted; } } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [SecuritySafeCritical] public void OnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:true); } /// <summary>Schedules the continuation onto the <see cref="System.Threading.Tasks.Task"/> associated with this <see cref="TaskAwaiter"/>.</summary> /// <param name="continuation">The action to invoke when the await operation completes.</param> /// <exception cref="System.ArgumentNullException">The <paramref name="continuation"/> argument is null (Nothing in Visual Basic).</exception> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <remarks>This method is intended for compiler user rather than use directly in code.</remarks> [SecurityCritical] public void UnsafeOnCompleted(Action continuation) { TaskAwaiter.OnCompletedInternal(m_task, continuation, m_continueOnCapturedContext, flowExecutionContext:false); } /// <summary>Ends the await on the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</summary> /// <returns>The result of the completed <see cref="System.Threading.Tasks.Task{TResult}"/>.</returns> /// <exception cref="System.NullReferenceException">The awaiter was not properly initialized.</exception> /// <exception cref="System.Threading.Tasks.TaskCanceledException">The task was canceled.</exception> /// <exception cref="System.Exception">The task completed in a Faulted state.</exception> public TResult GetResult() { TaskAwaiter.ValidateEnd(m_task); return m_task.ResultOnSuccess; } } } }
//============================================================================= // Vici Core - Productivity Library for .NET 3.5 // // Copyright (c) 2008-2012 Philippe Leybaert // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //============================================================================= using System; using System.Collections.Generic; using NUnit.Framework; using Vici.Core.Parser; namespace Vici.Core.Test { [TestFixture] public class CSharpParserFixture { private readonly ParserContext _context = new CSharpContext(); private readonly CScriptParser _parser = new CScriptParser(); private class DataClass { public DataClass() { } public DataClass(int int1) { Int1 = int1; } public DataClass(string string1, int int1) { String1 = string1; Int1 = int1; } public string String1; public int Int1; public int Method0() { return 2; } public int Method1(int x) { return x * 2; } public int Method2(int x, int y) { return x + y; } public static int Static1 = 500; public static int Static2 { get { return 501; } } public int this[int i] { get { return i * 2; } } public int this[int x, int y] { get { return x + y; } } } [TestFixtureSetUp] public void SetupFixture() { DataClass dataObject = new DataClass(); dataObject.String1 = "blabla1"; dataObject.Int1 = 123; _context.AddType("Math", typeof(Math)); _context.Set("Data", dataObject); _context.AddType("DataClass", typeof(DataClass)); _context.Set("Func", new Converter<int, int>(Func)); _context.AddFunction("Max", typeof(Math), "Max"); _context.AddFunction("fmt", typeof(String), "Format"); _context.Set("Value10", 10, typeof(int)); _context.Set("NullableValue5", 5, typeof(int?)); _context.Set("NullableValueNull", null, typeof(int?)); _context.Set("MyArray", new int[] { 1, 2, 4, 8, 16 }); _context.Set("MyArray2", new int[,] { { 1, 2 }, { 2, 4 }, { 4, 8 }, { 8, 16 }, { 16, 32 } }); _context.Set("f", new Func<int,int>(i => i*2)); _parser.DefaultContext = _context; } private static int Func(int i) { return i * 5; } [Test] public void ComplexExpressions() { Assert.AreEqual(435, _parser.Evaluate<int>("Math.Max(Data.Method2(Data.Int1+10,300),Data.Method1(Data.Int1))+(\"x\" + 5).Length")); Assert.AreEqual(17, _parser.Evaluate<int>("Data.Method2(Data.Method2(3,4),Data.Method1(5))")); Assert.AreEqual(100, _parser.Evaluate<int>("Max(Max(100,5),Func(10))")); Assert.AreEqual(1000, _parser.Evaluate<int>("Max(Max(100,5),Func(200))")); } [Test] public void DefaultValueExpression() { IParserContext context = new FlexContext(); context.Set("a",""); context.Set("b", "z"); Assert.AreEqual("x", _parser.Evaluate<string>("a ?: \"x\"",context)); Assert.AreEqual("z", _parser.Evaluate<string>("b ?: \"x\"", context)); } [Test] public void StringExpressions() { Assert.AreEqual("ab", _parser.Evaluate<string>("string.Concat(\"a\",\"b\")")); Assert.AreEqual("ab", _parser.Evaluate<string>("\"a\" + \"b\")")); } [Test] public void StringComparisons() { StringComparison saved = _context.StringComparison; _context.StringComparison = StringComparison.Ordinal; Assert.IsTrue(_parser.Evaluate<bool>("\"a\" == \"a\"")); Assert.IsFalse(_parser.Evaluate<bool>("\"a\" == \"b\"")); Assert.IsTrue(_parser.Evaluate<bool>("\"a\" != \"b\"")); Assert.IsFalse(_parser.Evaluate<bool>("\"a\" != \"a\"")); Assert.IsFalse(_parser.Evaluate<bool>("\"a\" == \"A\"")); Assert.IsFalse(_parser.Evaluate<bool>("\"a\" == \"B\"")); Assert.IsTrue(_parser.Evaluate<bool>("\"a\" != \"B\"")); Assert.IsTrue(_parser.Evaluate<bool>("\"a\" != \"B\"")); _context.StringComparison = StringComparison.OrdinalIgnoreCase; Assert.IsTrue(_parser.Evaluate<bool>("\"a\" == \"A\"")); Assert.IsFalse(_parser.Evaluate<bool>("\"a\" != \"A\"")); _context.StringComparison = saved; } [Test] public void MemberMethods() { Assert.AreEqual(2, _parser.Evaluate<int>("Data.Method0()")); Assert.AreEqual(2, _parser.Evaluate<int>("Math.Max(1,2)")); Assert.AreEqual(21, _parser.Evaluate<int>("Data.Method0() + Data.Method1(5) + Data.Method2(5,4)")); } [Test] public void CharLiterals() { Assert.AreEqual('x', _parser.Evaluate<char>("'x'")); Assert.AreEqual('\n', _parser.Evaluate<char>("'\\n'")); Assert.AreEqual("Test\n", _parser.Evaluate<string>("\"Test\" + '\\n'")); Assert.AreEqual('\'', _parser.Evaluate<char>("'\\''")); Assert.AreEqual('\x45', _parser.Evaluate<char>("'\\x45'")); Assert.AreEqual('\x4545', _parser.Evaluate<char>("'\\x4545'")); } [Test] public void TypeCast() { Assert.IsInstanceOf<int>(_parser.EvaluateToObject("(int)5L")); } [Test] public void StringLiterals() { Assert.AreEqual("xyz", _parser.Evaluate<string>("\"xyz\"")); Assert.AreEqual("\n", _parser.Evaluate<string>(@"""\n""")); Assert.AreEqual("\f", _parser.Evaluate<string>(@"""\f""")); Assert.AreEqual("\"", _parser.Evaluate<string>(@"""\""""")); Assert.AreEqual("\x45r\n", _parser.Evaluate<string>(@"""\x45r\n""")); Assert.AreEqual("\x45b\n", _parser.Evaluate<string>(@"""\x45b\n""")); Assert.AreEqual("\x45bf\n", _parser.Evaluate<string>(@"""\x45bf\n""")); Assert.AreEqual("\x45bff\n", _parser.Evaluate<string>(@"""\x45bff\n""")); } [Test] public void NumericLiterals() { Assert.IsInstanceOf<int>(_parser.EvaluateToObject("1")); Assert.AreEqual(1, _parser.Evaluate<int>("1")); Assert.IsInstanceOf<long>(_parser.EvaluateToObject("10000000000")); Assert.AreEqual(10000000000, _parser.Evaluate<long>("10000000000")); Assert.IsInstanceOf<decimal>(_parser.EvaluateToObject("1m")); Assert.AreEqual(1m, _parser.Evaluate<decimal>("1m")); Assert.IsInstanceOf<long>(_parser.EvaluateToObject("1L")); Assert.AreEqual(1L, _parser.Evaluate<long>("1L")); Assert.IsInstanceOf<ulong>(_parser.EvaluateToObject("1UL")); Assert.AreEqual(1UL, _parser.Evaluate<ulong>("1UL")); Assert.IsInstanceOf<double>(_parser.EvaluateToObject("1.0")); Assert.AreEqual(1L, _parser.Evaluate<double>("1.0")); Assert.IsInstanceOf<float>(_parser.EvaluateToObject("1.0f")); Assert.AreEqual(1L, _parser.Evaluate<float>("1.0f")); } [Test] public void ObjectCreation() { Assert.IsInstanceOf<DataClass>(_parser.Evaluate<object>("new DataClass(5)")); Assert.AreEqual(5, _parser.Evaluate<int>("(new DataClass(5)).Int1")); Assert.AreEqual(5, _parser.Evaluate<int>("new DataClass(5).Int1")); Assert.AreEqual(5, _parser.Evaluate<int>("Math.Max(new DataClass(3+2).Int1,3)")); } [Test] public void Delegates() { Assert.AreEqual(10, _parser.Evaluate<int>("Func(2)")); Assert.AreEqual(5, _parser.Evaluate<int>("Max(4,5)")); } [Test] public void Typeof() { Assert.AreEqual(typeof(int), _parser.Evaluate<Type>("typeof(int)")); } [Test] public void OperatorPrecedence() { Assert.AreEqual(2, _parser.Evaluate<int>("(5-4)*2")); Assert.AreEqual(13, _parser.Evaluate<int>("5+4*2")); Assert.AreEqual(22, _parser.Evaluate<int>("5*4+2")); Assert.AreEqual(18, _parser.Evaluate<int>("(5+4)*2")); } [Test] public void UnaryNot() { Assert.AreEqual(false, _parser.Evaluate<bool>("!(1==1)")); Assert.AreEqual(true, _parser.Evaluate<bool>("!false")); Assert.AreEqual(true, _parser.Evaluate<bool>("!!true")); } [Test] public void UnaryMinus() { Assert.AreEqual(-2, _parser.Evaluate<int>("-2")); Assert.AreEqual(3, _parser.Evaluate<int>("5+-2")); Assert.AreEqual(-1, _parser.Evaluate<int>("-(3-2)")); } [Test] public void BitwiseComplement() { Assert.AreEqual(~2, _parser.Evaluate<int>("~2")); Assert.AreEqual(5 + ~2, _parser.Evaluate<int>("5+~2")); Assert.AreEqual(~(3 - 2), _parser.Evaluate<int>("~(3 - 2)")); } [Test] public void StaticFields() { Assert.AreEqual(500, _parser.Evaluate<int>("DataClass.Static1")); Assert.AreEqual(501, _parser.Evaluate<int>("DataClass.Static2")); } [Test] public void NullableLifting() { Assert.AreEqual(15, _parser.Evaluate<int?>("Value10 + NullableValue5")); Assert.IsInstanceOf<int>(_parser.Evaluate<int?>("Value10 + NullableValue5")); Assert.AreEqual(null, _parser.Evaluate<int?>("Value10 + NullableValueNull")); } [Test] public void Indexing() { Assert.AreEqual(30, _parser.Evaluate<int>("Data[Func(5),5]")); } [Test] public void ArrayIndexing() { Assert.AreEqual(8, _parser.Evaluate<int>("MyArray[3]")); Assert.AreEqual(8, _parser.Evaluate<int>("MyArray2[2,1]")); Assert.AreEqual(16, _parser.Evaluate<int>("MyArray[Data.Method0()+2]")); Assert.AreEqual(8, _parser.Evaluate<int>("MyArray2[Data.Method0()+1,0]")); } [Test] public void Ternary() { Assert.AreEqual(1, _parser.Evaluate<int>("true ? 1:2")); Assert.AreEqual(2, _parser.Evaluate<int>("false ? 1:2")); _context.Set("a", 1); Assert.AreEqual(1, _parser.Evaluate<int>("a==1 ? 1 : 2")); Assert.AreEqual(2, _parser.Evaluate<int>("a!=1 ? 1 : 2")); Assert.AreEqual("1", _parser.Evaluate<string>("a==1 ? \"1\" : \"2\"")); Assert.AreEqual("2", _parser.Evaluate<string>("a!=1 ? \"1\" : \"2\"")); Assert.AreEqual(1, _parser.Evaluate<int>("a==1 ? 1 : a==2 ? 2 : a==3 ? 3 : 4")); Assert.AreEqual("x", _parser.Evaluate<string>("a==1 ? \"x\" : a==2 ? \"y\" : a==3 ? \"z\" : \"error\"")); _context.Set("a", 2); Assert.AreEqual("y", _parser.Evaluate<string>("a==1 ? \"x\" : a==2 ? \"y\" : a==3 ? \"z\" : \"error\"")); _context.Set("a", 3); Assert.AreEqual("z", _parser.Evaluate<string>("a==1 ? \"x\" : a==2 ? \"y\" : a==3 ? \"z\" : \"error\"")); _context.Set("a", 56443); Assert.AreEqual("error", _parser.Evaluate<string>("a==1 ? \"x\" : a==2 ? \"y\" : a==3 ? \"z\" : \"error\"")); } [Test] public void Comparisons() { Assert.IsTrue(_parser.Evaluate<bool>("1==1")); Assert.IsTrue(_parser.Evaluate<bool>("2>=1")); Assert.IsTrue(_parser.Evaluate<bool>("2>1")); Assert.IsTrue(_parser.Evaluate<bool>("1<2")); Assert.IsFalse(_parser.Evaluate<bool>("2<1")); _context.Set("NullString", null, typeof(string)); _context.Set("ShortValue", 4, typeof(short)); Assert.IsTrue(_parser.Evaluate<bool>("NullString == null")); Assert.IsTrue(_parser.Evaluate<bool>("NullableValue5 == 5")); Assert.IsTrue(_parser.Evaluate<bool>("ShortValue == 4")); } [Test] public void AsOperator() { Assert.AreEqual("x", _parser.Evaluate<string>("\"x\" as string")); Assert.AreEqual(null, _parser.Evaluate<string>("5 as string")); } [Test] public void IsOperator() { Assert.IsTrue(_parser.Evaluate<bool>("\"x\" is string")); Assert.IsFalse(_parser.Evaluate<bool>("5 is string")); Assert.IsFalse(_parser.Evaluate<bool>("null is string")); } [Test] public void NullValueOperator() { Assert.AreEqual(10, _parser.Evaluate<int>("NullableValueNull ?? 10")); Assert.AreEqual(5, _parser.Evaluate<int>("NullableValue5 ?? 10")); } [Test] public void Assignment() { _context.AssignmentPermissions = AssignmentPermissions.NewVariable; Assert.AreEqual(5, _parser.Evaluate<int>("aaa = 5")); Assert.IsTrue(_parser.Evaluate<bool>("aaa == 5")); _context.AssignmentPermissions = AssignmentPermissions.ExistingVariable; Assert.AreEqual(100, _parser.Evaluate<int>("aaa = 100")); Assert.IsTrue(_parser.Evaluate<bool>("aaa == 100")); _context.AssignmentPermissions = AssignmentPermissions.Variable; Assert.AreEqual(200, _parser.Evaluate<int>("aaa = bbb = 100*2")); Assert.IsTrue(_parser.Evaluate<bool>("aaa == 200")); Assert.IsTrue(_parser.Evaluate<bool>("bbb == 200")); } [Test] //[ExpectedException(typeof(IllegalAssignmentException))] public void PropertyAssignmentNotAllowed() { try { _context.AssignmentPermissions = AssignmentPermissions.None; Assert.AreEqual(123, _parser.Evaluate<int>("Data.Int1 = 123")); Assert.Fail(); } catch (IllegalAssignmentException) { } } [Test] public void PropertyAssignment() { _context.AssignmentPermissions = AssignmentPermissions.Property; Assert.AreEqual(123, _parser.Evaluate<int>("Data.Int1 = 123")); Assert.AreEqual(123,_parser.Evaluate<int>("Data.Int1")); } public class XElement { public string Attribute(XName xName) { return "attr[" + xName + "]"; } } public class XName { private string _name; public static implicit operator XName(string s) { XName xName = new XName(); xName._name = s; return xName; } public override string ToString() { return _name; } } [Test] public void CustomImplicitConversions() { XElement xEl = new XElement(); _context.Set("xEl", xEl); Assert.AreEqual("attr[Test]", _parser.Evaluate<string>("xEl.Attribute(\"Test\")")); } [Test] public void CustomOperators() { _context.Set("date1", DateTime.Now); _context.Set("date2",DateTime.Now.AddHours(1)); Assert.IsTrue(_parser.Evaluate<bool>("date1 < date2")); Assert.IsFalse(_parser.Evaluate<bool>("date1 > date2")); Assert.IsFalse(_parser.Evaluate<bool>("date1 == date2")); Assert.AreEqual(1,(int)_parser.Evaluate<TimeSpan>("date2 - date1").TotalHours); } [Test] public void ExpressionTree() { IParserContext context = new ParserContext(); ExpressionWithContext expr = new ExpressionWithContext(context); expr.Expression = Exp.Add(TokenPosition.Unknown, Exp.Value(TokenPosition.Unknown, 4), Exp.Value(TokenPosition.Unknown, 5)); Assert.AreEqual(9, expr.Evaluate().Value); Assert.AreEqual(typeof(int), expr.Evaluate().Type); expr.Expression = Exp.Add(TokenPosition.Unknown, Exp.Add(TokenPosition.Unknown, Exp.Value(TokenPosition.Unknown, 4), Exp.Value(TokenPosition.Unknown, (long)5)), Exp.Value(TokenPosition.Unknown, 6)); Assert.AreEqual(15L, expr.Evaluate().Value); Assert.AreEqual(typeof(long), expr.Evaluate().Type); expr.Expression = Exp.Op(TokenPosition.Unknown, "<<", Exp.Value(TokenPosition.Unknown, (long)4), Exp.Value(TokenPosition.Unknown, 2)); Assert.AreEqual(16L, expr.Evaluate().Value); } [Test] public void NumRange() { Converter<IEnumerable<int>, int> sum = delegate(IEnumerable<int> items) { int total = 0; foreach (int n in items) total += n; return total; }; //IParserContext context = new ParserContext(); _context.Set("sum",sum); Assert.IsInstanceOf < IEnumerable<int>>(_parser.EvaluateToObject("1...3")); Assert.AreEqual(6,_parser.Evaluate<int>("sum(1 ... 3)")); } [Test] public void DynObject() { DynamicObject dynObj = new DynamicObject(); dynObj.Apply(new DataClass(5)); CSharpContext context = new CSharpContext(dynObj); Assert.AreEqual(2, _parser.Evaluate<int>("Method0()",context)); Assert.AreEqual(21, _parser.Evaluate<int>("Method0() + Method1(5) + Method2(Int1,4)", context)); } private static ParserContext SetupFalsyContext(ParserContextBehavior behavior) { ParserContext context = new ParserContext(behavior); context.Set<object>("NullValue", null); context.Set<object>("RandomObject",new object()); context.Set("EmptyString", ""); context.Set("NonEmptyString", "x"); return context; } [Test] //[ExpectedException(typeof(NullReferenceException))] public void NotFalsyNull() { try { ParserContext context = SetupFalsyContext(ParserContextBehavior.Default); _parser.Evaluate<bool>("!!NullValue", context); Assert.Fail(); } catch(NullReferenceException) { } } [Test] //[ExpectedException(typeof(ArgumentException))] public void NotFalsyEmptyString() { try { ParserContext context = SetupFalsyContext(ParserContextBehavior.Default); _parser.Evaluate<bool>("!!EmptyString", context); Assert.Fail(); } catch(ArgumentException) { } } [Test] //[ExpectedException(typeof(ArgumentException))] public void NotFalsyString() { try { ParserContext context = SetupFalsyContext(ParserContextBehavior.Default); _parser.Evaluate<bool>("!!NonEmptyString", context); Assert.Fail(); } catch(ArgumentException) { } } [Test] public void FalsyEmptyString() { ParserContext context = SetupFalsyContext(ParserContextBehavior.EmptyStringIsFalse); Assert.IsFalse(_parser.Evaluate<bool>("!!EmptyString",context)); } [Test] public void FalsyString() { ParserContext context = SetupFalsyContext(ParserContextBehavior.NonEmptyStringIsTrue); Assert.IsTrue(_parser.Evaluate<bool>("!!NonEmptyString", context)); } [Test] public void FalsyNull() { ParserContext context = SetupFalsyContext(ParserContextBehavior.NullIsFalse); Assert.IsFalse(_parser.Evaluate<bool>("!!NullValue", context)); } [Test] public void FalsyNotNull() { ParserContext context = SetupFalsyContext(ParserContextBehavior.NotNullIsTrue); Assert.IsTrue(_parser.Evaluate<bool>("!!RandomObject", context)); } [Test] public void Sequence() { CSharpContext context = new CSharpContext(); string output = ""; context.Set("f", new Action<int>(delegate(int i) { output += i; })); _parser.Evaluate("f(1);f(2);",context); Assert.AreEqual("12",output); output = ""; _parser.Evaluate("foreach (x in [1...9]) f(x);", context); Assert.AreEqual("123456789", output); output = ""; _parser.Evaluate("foreach (x in [1...9]) { f(x); f(x-1); }", context); Assert.AreEqual("102132435465768798", output); } [Test] public void SequenceWithReturn() { CSharpContext context = new CSharpContext(); string output = ""; context.Set("f", new Action<int>(delegate(int i) { output += i; })); Assert.AreEqual(5,_parser.Evaluate<int>("f(1);return 5;f(2);", context)); Assert.AreEqual("1", output); } [Test] public void ForEach() { CSharpContext context = new CSharpContext(); string output = ""; context.Set("f", new Action<int>(delegate(int i) { output += i; })); _parser.Evaluate("foreach (x in [1...9]) f(x);", context); Assert.AreEqual("123456789", output); output = ""; _parser.Evaluate("foreach (x in [1...3]) { f(x); foreach(y in [1...x]) f(y); }", context); Assert.AreEqual("112123123", output); } [Test] public void If() { CSharpContext context = new CSharpContext(ParserContextBehavior.Easy); string output = ""; context.Set("f", new Action<int>(delegate(int i) { output += i; })); _parser.Evaluate("if(1==1) f(1);f(2)", context); Assert.AreEqual("12", output); output = ""; _parser.Evaluate("if(0) f(1);f(2)", context); Assert.AreEqual("2", output); output = ""; } [Test] public void IfWithReturn() { CSharpContext context = new CSharpContext(ParserContextBehavior.Easy); string output = ""; context.Set("f", new Action<int>(delegate(int i) { output += i; })); Assert.AreEqual(5,_parser.Evaluate<int>("if(1==1) { f(1); return 5; } f(2);", context)); Assert.AreEqual("1", output); } [Test] public void IfElse() { CSharpContext context = new CSharpContext(ParserContextBehavior.Easy); string output = ""; context.Set("f", new Action<int>(delegate(int i) { output += i; })); _parser.Evaluate("if(1==1) f(1); else f(3); f(2)", context); Assert.AreEqual("12", output); output = ""; _parser.Evaluate("if(1==0) f(1); else f(3); f(2)", context); Assert.AreEqual("32", output); output = ""; _parser.Evaluate("if(1==0) f(1); else if(1==1) f(3); f(2)", context); Assert.AreEqual("32", output); output = ""; } [Test] public void ComplexScript1() { CSharpContext context = new CSharpContext(ParserContextBehavior.Easy); string output = ""; context.AssignmentPermissions = AssignmentPermissions.All; context.Set("f", new Action<int>(delegate(int i) { output += i; })); int[] array = new int[50]; context.Set("array", array); for (int i = 0; i < array.Length; i++) array[i] = i + 1; Random rnd = new Random(); for (int i=0;i<array.Length-1;i++) { int idx = rnd.Next(i + 1, array.Length - 1); int tmp = array[idx]; array[idx] = array[i]; array[i] = tmp; } string script = @" numSwaps = 0; foreach (i in [0...array.Length-2]) { foreach (j in [i+1...array.Length-1]) { if (array[i] > array[j]) { tmp = array[i]; array[i] = array[j]; array[j] = tmp; numSwaps = numSwaps + 1; } } } return numSwaps; "; _parser.Evaluate(script, context); object o; Type t; context.Get("array", out o, out t); array = (int[]) o; Assert.AreEqual(1, array[0]); Assert.AreEqual(2, array[1]); Assert.AreEqual(3, array[2]); Assert.AreEqual(4, array[3]); Assert.AreEqual(5, array[4]); Assert.AreEqual(6, array[5]); Assert.AreEqual(7, array[6]); Assert.AreEqual(8, array[7]); Assert.AreEqual(9, array[8]); } [Test] public void FunctionDefinition() { CSharpContext context = new CSharpContext(); string output = ""; context.Set("f", new Action<int>(delegate(int i) { output += i; })); _parser.Evaluate("function x(a,b) { f(a); f(b); } x(1,2);", context); Assert.AreEqual("12",output); } [Test] public void FunctionDefinition2() { CSharpContext context = new CSharpContext(); string output = ""; context.Set("f", new Action<int>(delegate(int i) { output += i; })); string script = @" function max(a,b) { return a > b ? a : b; } f(max(1,2)); f(max(2,1)); "; _parser.Evaluate(script, context); Assert.AreEqual("22", output); } [Test] public void FunctionDefinition3() { CSharpContext context = new CSharpContext(); string output = ""; context.Set("f", new Action<string>(delegate(string i) { output += i; })); string libraryScript = @" function plural(n,a,b,c,d) { if (n == 1) return a; if (n == 2 || n == 0) return b; if (n == 3) return c; return d; } "; string script = @" f(plural(0,""a"",""b"",""c"",""d"")); f(plural(1,""a"",""b"",""c"",""d"")); f(plural(2,""a"",""b"",""c"",""d"")); f(plural(3,""a"",""b"",""c"",""d"")); f(plural(4,""a"",""b"",""c"",""d"")); "; var library = _parser.Parse(libraryScript); library.Evaluate(context); _parser.Evaluate(script, context); Assert.AreEqual("babcd", output); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Framework.WebServices.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; namespace System { /// <summary> /// Span is a uniform API for dealing with arrays and subarrays, strings /// and substrings, and unmanaged memory buffers. It adds minimal overhead /// to regular accesses and is a struct so that creation and subslicing do /// not require additional allocations. It is type- and memory-safe. /// </summary> [DebuggerTypeProxy(typeof(SpanDebuggerView<>))] [DebuggerDisplay("Length = {Length}")] public partial struct Span<T> : IEnumerable<T>, IEquatable<Span<T>> { /// <summary>A managed array/string; or null for native ptrs.</summary> internal readonly object Object; /// <summary>An byte-offset into the array/string; or a native ptr.</summary> internal readonly UIntPtr Offset; /// <summary>Fetches the number of elements this Span contains.</summary> public readonly int Length; /// <summary> /// Creates a new span over the entirety of the target array. /// </summary> /// <param name="array">The target array.</param> /// <exception cref="System.ArgumentException"> /// Thrown if the 'array' parameter is null. /// </exception> public Span(T[] array) { Contract.Requires(array != null); Object = array; Offset = new UIntPtr((uint)SpanHelpers<T>.OffsetToArrayData); Length = array.Length; } /// <summary> /// Creates a new span over the portion of the target array beginning /// at 'start' index. /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the span.</param> /// <exception cref="System.ArgumentException"> /// Thrown if the 'array' parameter is null. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified start index is not in range (&lt;0 or &gt;&eq;length). /// </exception> // TODO: Should we have this overload? It is really confusing when you also have Span(T* array, int length) // While with Slice it makes sense it might not in here. internal Span(T[] array, int start) { Contract.Requires(array != null); Contract.RequiresInInclusiveRange(start, (uint)array.Length); if (start < array.Length) { Object = array; Offset = new UIntPtr( (uint)(SpanHelpers<T>.OffsetToArrayData + (start * PtrUtils.SizeOf<T>()))); Length = array.Length - start; } else { Object = null; Offset = UIntPtr.Zero; Length = 0; } } /// <summary> /// Creates a new span over the portion of the target array beginning /// at 'start' index and ending at 'end' index (exclusive). /// </summary> /// <param name="array">The target array.</param> /// <param name="start">The index at which to begin the span.</param> /// <param name="length">The number of items in the span.</param> /// <exception cref="System.ArgumentException"> /// Thrown if the 'array' parameter is null. /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified start or end index is not in range (&lt;0 or &gt;&eq;length). /// </exception> public Span(T[] array, int start, int length) { Contract.Requires(array != null); Contract.RequiresInInclusiveRange(start, length, (uint)array.Length); if (start < array.Length) { Object = array; Offset = new UIntPtr( (uint)(SpanHelpers<T>.OffsetToArrayData + (start * PtrUtils.SizeOf<T>()))); Length = length; } else { Object = null; Offset = UIntPtr.Zero; Length = 0; } } /// <summary> /// Creates a new span over the target unmanaged buffer. Clearly this /// is quite dangerous, because we are creating arbitrarily typed T's /// out of a void*-typed block of memory. And the length is not checked. /// But if this creation is correct, then all subsequent uses are correct. /// </summary> /// <param name="ptr">An unmanaged pointer to memory.</param> /// <param name="length">The number of T elements the memory contains.</param> public unsafe Span(void* ptr, int length) { Contract.Requires(length >= 0); Contract.Requires(length == 0 || ptr != null); Object = null; Offset = new UIntPtr(ptr); Length = length; } /// <summary> /// An internal helper for creating spans. Not for public use. /// </summary> internal Span(object obj, UIntPtr offset, int length) { Object = obj; Offset = offset; Length = length; } public static Span<T> Empty { get { return default(Span<T>); } } public bool IsEmpty { get { return Length == 0; } } public unsafe void* UnsafePointer { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return Offset.ToPointer(); } } /// <summary> /// Gets array if the slice is over an array /// </summary> /// <param name="dummy">dummy is just to make the call unsafe; feel free to pass void</param> /// <param name="array"></param> /// <returns>true if it's a span over an array; otherwise false (if over a pointer)</returns> public unsafe bool TryGetArray(void* dummy, out ArraySegment<T> array) { var a = Object as T[]; if (a == null) { array = new ArraySegment<T>(); return false; } var offsetToData = SpanHelpers<T>.OffsetToArrayData; var index = (int)((Offset.ToUInt32() - offsetToData) / PtrUtils.SizeOf<T>()); array = new ArraySegment<T>(a, index, Length); return true; } /// <summary> /// Fetches the element at the specified index. /// </summary> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified index is not in range (&lt;0 or &gt;&eq;length). /// </exception> public T this[int index] { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { Contract.RequiresInRange(index, (uint)Length); return PtrUtils.Get<T>(Object, Offset, (UIntPtr)index); } [MethodImpl(MethodImplOptions.AggressiveInlining)] set { Contract.RequiresInRange(index, (uint)Length); PtrUtils.Set(Object, Offset, (UIntPtr)index, value); } } /// <summary> /// Copies the contents of this span into a new array. This heap /// allocates, so should generally be avoided, however is sometimes /// necessary to bridge the gap with APIs written in terms of arrays. /// </summary> public T[] CreateArray() { var dest = new T[Length]; TryCopyTo(dest.Slice()); return dest; } /// <summary> /// Copies the contents of this span into another. The destination /// must be at least as big as the source, and may be bigger. /// </summary> /// <param name="dest">The span to copy items into.</param> public bool TryCopyTo(Span<T> dest) { if (Length > dest.Length) { return false; } // TODO(joe): specialize to use a fast memcpy if T is pointerless. for (int i = 0; i < Length; i++) { dest[i] = this[i]; } return true; } /// <summary> /// Copies the contents of this span into an array. The destination /// must be at least as big as the source, and may be bigger. /// </summary> /// <param name="dest">The span to copy items into.</param> public bool TryCopyTo(T[] dest) { if (Length > dest.Length) { return false; } // TODO(joe): specialize to use a fast memcpy if T is pointerless. for (int i = 0; i < Length; i++) { dest[i] = this[i]; } return true; } public void Set(Span<T> values) { if (Length < values.Length) { throw new ArgumentOutOfRangeException("values"); } // TODO(joe): specialize to use a fast memcpy if T is pointerless. for (int i = 0; i < values.Length; i++) { this[i] = values[i]; } } public void Set(T[] values) { if (Length < values.Length) { throw new ArgumentOutOfRangeException("values"); } // TODO(joe): specialize to use a fast memcpy if T is pointerless. for (int i = 0; i < values.Length; i++) { this[i] = values[i]; } } /// <summary> /// Forms a slice out of the given span, beginning at 'start'. /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified start index is not in range (&lt;0 or &gt;&eq;length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start) { Contract.RequiresInInclusiveRange(start, (uint)Length); return new Span<T>( Object, Offset + (start * PtrUtils.SizeOf<T>()), Length - start); } /// <summary> /// Forms a slice out of the given span, beginning at 'start', and /// ending at 'end' (exclusive). /// </summary> /// <param name="start">The index at which to begin this slice.</param> /// <param name="end">The index at which to end this slice (exclusive).</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// Thrown when the specified start or end index is not in range (&lt;0 or &gt;&eq;length). /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public Span<T> Slice(int start, int length) { Contract.RequiresInInclusiveRange(start, length, (uint)Length); return new Span<T>( Object, Offset + (start * PtrUtils.SizeOf<T>()), length); } /// <summary> /// Checks to see if two spans point at the same memory. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ReferenceEquals(Span<T> other) { return Object == other.Object && Offset == other.Offset && Length == other.Length; } public override int GetHashCode() { unchecked { var hashCode = Offset.GetHashCode(); hashCode = hashCode * 31 + Length; if (Object != null) { hashCode = hashCode * 31 + Object.GetHashCode(); } return hashCode; } } /// <summary> /// Checks to see if two spans point at the same memory. Note that /// this does *not* check to see if the *contents* are equal. /// </summary> public bool Equals(Span<T> other) { return ReferenceEquals(other); } public override bool Equals(object obj) { if (obj is Span<T>) { return Equals((Span<T>)obj); } return false; } /// <summary> /// Returns item from given index without the boundaries check /// use only in places where moving outside the boundaries is impossible /// gain: performance: no boundaries check (single operation) /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] internal T GetItemWithoutBoundariesCheck(int index) { return PtrUtils.Get<T>(Object, Offset, (UIntPtr)index); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Configuration.Provider; using System.Runtime.Serialization; using System.Security.Permissions; using System.Threading; using System.Web; using System.Web.Compilation; using System.Web.Configuration; using System.Web.Hosting; using System.Web.Management; using System.Web.UI; using System.Web.Util; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace System.Web.Caching { /* We currently have the following buffer types: HttpResponseBufferElement - managed memory HttpResponseUnmanagedBufferElement - native memory HttpResourceResponseElement - pointer to resource HttpFileResponseElement - contains a file name, file can have 64-bit length HttpSubstBlockResponseElement - subst callback Custom output cache providers do not support all features. If we cannot use a custom output cache, provider, we will use the internal cache. We will use a custom output cache provider only if: a) no instance validation callbacks (static callbacks are okay) b) no dependencies other than files c) no sliding expiration d) no instance substitution callbacks (HttpSubstBlockResponseElement) (static callbacks okay) INSERT/GET: ---------- The custom cache provider receives an OutputCacheEntry, which contains the status, headers, response elements, cache policy settings, and kernel cache key. The cache provider can coallesce response elements. For example, a disk based cache may return a single response element which is the name of a file containing the entire response. ISSUES: If the custom cache provider is distributed, the cache keys must be unique for two applications with the same name but different domains. For example, a request to http://company1.com/myapp/page.aspx and a request to http://company2.com/myapp/page.aspx need to use output cache entry keys that include the domain name. Today, the key is just /myapp/page.aspx. It would need to include the Host header, but if that is "localhost", "::1", etc, we'd need to use %USERDOMAIN%\%COMPUTERNAME% instead. But it is possible for a single site to have multiple host name bindings, so this would result in multiple cache entries for potentially the same cached result. We could allow this to be adjusted by adding a setting to the cache policy. */ internal class DependencyCacheEntry { private string _providerName; private string _outputCacheEntryKey; private string _kernelCacheEntryKey; internal string ProviderName { get { return _providerName; } } internal string OutputCacheEntryKey { get { return _outputCacheEntryKey; } } internal string KernelCacheEntryKey { get { return _kernelCacheEntryKey; } } internal DependencyCacheEntry(string oceKey, string kernelCacheEntryKey, string providerName) { _outputCacheEntryKey = oceKey; _kernelCacheEntryKey = kernelCacheEntryKey; _providerName = providerName; } } public static class OutputCache { private const string OUTPUTCACHE_KEYPREFIX_DEPENDENCIES = CacheInternal.PrefixOutputCache + "D"; internal const string ASPNET_INTERNAL_PROVIDER_NAME = "AspNetInternalProvider"; private static bool s_inited; private static object s_initLock = new object(); private static CacheItemRemovedCallback s_entryRemovedCallback; private static CacheItemRemovedCallback s_dependencyRemovedCallback; private static CacheItemRemovedCallback s_dependencyRemovedCallbackForFragment; private static OutputCacheProvider s_defaultProvider; private static OutputCacheProviderCollection s_providers; // when there are no providers being used, we'll use this count to optimize performance when the value is zero. private static int s_cEntries; // // private helper methods // private static void AddCacheKeyToDependencies(ref CacheDependency dependencies, string cacheKey) { CacheDependency keyDep = new CacheDependency(0, null, new string[1] {cacheKey}); if (dependencies == null) { dependencies = keyDep; } else { // if it's not an aggregate, we have to create one because you can't add // it to anything but an aggregate AggregateCacheDependency agg = dependencies as AggregateCacheDependency; if (agg != null) { agg.Add(keyDep); } else { agg = new AggregateCacheDependency(); agg.Add(keyDep, dependencies); dependencies = agg; } } } private static void EnsureInitialized() { if (s_inited) return; lock (s_initLock) { if (!s_inited) { OutputCacheSection settings = RuntimeConfig.GetAppConfig().OutputCache; s_providers = settings.CreateProviderCollection(); s_defaultProvider = settings.GetDefaultProvider(s_providers); s_entryRemovedCallback = new CacheItemRemovedCallback(OutputCache.EntryRemovedCallback); s_dependencyRemovedCallback = new CacheItemRemovedCallback(OutputCache.DependencyRemovedCallback); s_dependencyRemovedCallbackForFragment = new CacheItemRemovedCallback(OutputCache.DependencyRemovedCallbackForFragment); s_inited = true; } } } private static void DecrementCount() { if (Providers == null) Interlocked.Decrement(ref s_cEntries); } private static void IncrementCount() { if (Providers == null) Interlocked.Increment(ref s_cEntries); } private static OutputCacheProvider GetFragmentProvider(String providerName) { // if providerName is null, use default provider. If default provider is null, we'll use internal cache. // if providerName is not null, get it from the provider collection. OutputCacheProvider provider = null; if (providerName == null) { provider = s_defaultProvider; } else { provider = s_providers[providerName]; if (provider == null) { Debug.Assert(false, "Unexpected, " + providerName + " should be a member of the collection."); throw new ProviderException(SR.GetString(SR.Provider_Not_Found, providerName)); } } #if DBG string msg = (provider != null) ? provider.GetType().Name : "null"; Debug.Trace("OutputCache", "GetFragmentProvider(" + providerName + ") --> " + msg); #endif return provider; } private static OutputCacheProvider GetProvider(HttpContext context) { Debug.Assert(context != null, "context != null"); if (context == null) { return null; } // Call GetOutputCacheProviderName // so it can determine which provider to use. HttpApplication app = context.ApplicationInstance; string name = app.GetOutputCacheProviderName(context); if (name == null) { throw new ProviderException(SR.GetString(SR.GetOutputCacheProviderName_Invalid, name)); } // AspNetInternalProvider means use the internal cache if (name == OutputCache.ASPNET_INTERNAL_PROVIDER_NAME) { return null; } OutputCacheProvider provider = (s_providers == null) ? null : s_providers[name]; if (provider == null) { throw new ProviderException(SR.GetString(SR.GetOutputCacheProviderName_Invalid, name)); } return provider; } private static OutputCacheEntry Convert(CachedRawResponse cachedRawResponse, string depKey, string[] fileDependencies) { List<HeaderElement> headerElements = null; ArrayList headers = cachedRawResponse._rawResponse.Headers; int count = (headers != null) ? headers.Count : 0; for (int i = 0; i < count; i++) { if (headerElements == null) { headerElements = new List<HeaderElement>(count); } HttpResponseHeader h = (HttpResponseHeader)(headers[i]); headerElements.Add(new HeaderElement(h.Name, h.Value)); } List<ResponseElement> responseElements = null; ArrayList buffers = cachedRawResponse._rawResponse.Buffers; count = (buffers != null) ? buffers.Count : 0; for (int i = 0; i < count; i++) { if (responseElements == null) { responseElements = new List<ResponseElement>(count); } IHttpResponseElement elem = buffers[i] as IHttpResponseElement; if (elem is HttpFileResponseElement) { HttpFileResponseElement fileElement = elem as HttpFileResponseElement; responseElements.Add(new FileResponseElement(fileElement.FileName, fileElement.Offset, elem.GetSize())); } else if (elem is HttpSubstBlockResponseElement) { HttpSubstBlockResponseElement substElement = elem as HttpSubstBlockResponseElement; responseElements.Add(new SubstitutionResponseElement(substElement.Callback)); } else { byte[] b = elem.GetBytes(); long length = (b != null) ? b.Length : 0; responseElements.Add(new MemoryResponseElement(b, length)); } } OutputCacheEntry oce = new OutputCacheEntry( cachedRawResponse._cachedVaryId, cachedRawResponse._settings, cachedRawResponse._kernelCacheUrl, depKey, fileDependencies, cachedRawResponse._rawResponse.StatusCode, cachedRawResponse._rawResponse.StatusDescription, headerElements, responseElements ); return oce; } private static CachedRawResponse Convert(OutputCacheEntry oce) { ArrayList headers = null; if (oce.HeaderElements != null && oce.HeaderElements.Count > 0) { headers = new ArrayList(oce.HeaderElements.Count); for (int i = 0; i < oce.HeaderElements.Count; i++) { HttpResponseHeader h = new HttpResponseHeader(oce.HeaderElements[i].Name, oce.HeaderElements[i].Value); headers.Add(h); } } ArrayList buffers = null; if (oce.ResponseElements != null && oce.ResponseElements.Count > 0) { buffers = new ArrayList(oce.ResponseElements.Count); for (int i = 0; i < oce.ResponseElements.Count; i++) { ResponseElement re = oce.ResponseElements[i]; IHttpResponseElement elem = null; if (re is FileResponseElement) { HttpContext context = HttpContext.Current; HttpWorkerRequest wr = (context != null) ? context.WorkerRequest : null; bool supportsLongTransmitFile = (wr != null && wr.SupportsLongTransmitFile); bool isImpersonating = ((context != null && context.IsClientImpersonationConfigured) || HttpRuntime.IsOnUNCShareInternal); FileResponseElement fre = (FileResponseElement)re; // DevDiv #21203: Need to verify permission to access the requested file since handled by native code. HttpRuntime.CheckFilePermission(fre.Path); elem = new HttpFileResponseElement(fre.Path, fre.Offset, fre.Length, isImpersonating, supportsLongTransmitFile); } else if (re is MemoryResponseElement) { MemoryResponseElement mre = (MemoryResponseElement)re; int size = System.Convert.ToInt32(mre.Length); elem = new HttpResponseBufferElement(mre.Buffer, size); } else if (re is SubstitutionResponseElement) { SubstitutionResponseElement sre = (SubstitutionResponseElement)re; elem = new HttpSubstBlockResponseElement(sre.Callback); } else { throw new NotSupportedException(); } buffers.Add(elem); } } else { buffers = new ArrayList(); } HttpRawResponse rawResponse = new HttpRawResponse(oce.StatusCode, oce.StatusDescription, headers, buffers, false /*hasSubstBlocks*/); CachedRawResponse cachedRawResponse = new CachedRawResponse(rawResponse, oce.Settings, oce.KernelCacheUrl, oce.CachedVaryId); return cachedRawResponse; } // // helpers for accessing CacheInternal // // add CachedVary private static CachedVary UtcAdd(String key, CachedVary cachedVary) { return (CachedVary) HttpRuntime.CacheInternal.UtcAdd(key, cachedVary, null /*dependencies*/, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null /*callback*/); } // add ControlCachedVary private static ControlCachedVary UtcAdd(String key, ControlCachedVary cachedVary) { return (ControlCachedVary) HttpRuntime.CacheInternal.UtcAdd(key, cachedVary, null /*dependencies*/, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null /*callback*/); } private static bool IsSubstBlockSerializable(HttpRawResponse rawResponse) { if (!rawResponse.HasSubstBlocks) return true; for (int i = 0; i < rawResponse.Buffers.Count; i++) { HttpSubstBlockResponseElement substBlock = rawResponse.Buffers[i] as HttpSubstBlockResponseElement; if (substBlock == null) continue; if (!substBlock.Callback.Method.IsStatic) return false; } return true; } // // callbacks // private static void HandleErrorWithoutContext(Exception e) { HttpApplicationFactory.RaiseError(e); try { WebBaseEvent.RaiseRuntimeError(e, typeof(OutputCache)); } catch { } } // only used by providers private static void DependencyRemovedCallback(string key, object value, CacheItemRemovedReason reason) { Debug.Trace("OutputCache", "DependencyRemovedCallback: reason=" + reason + ", key=" + key); DependencyCacheEntry dce = value as DependencyCacheEntry; if (dce.KernelCacheEntryKey != null) { // invalidate kernel cache entry if (HttpRuntime.UseIntegratedPipeline) { UnsafeIISMethods.MgdFlushKernelCache(dce.KernelCacheEntryKey); } else { UnsafeNativeMethods.InvalidateKernelCache(dce.KernelCacheEntryKey); } } if (reason == CacheItemRemovedReason.DependencyChanged) { if (dce.OutputCacheEntryKey != null) { try { OutputCache.RemoveFromProvider(dce.OutputCacheEntryKey, dce.ProviderName); } catch (Exception e) { HandleErrorWithoutContext(e); } } } } // only used by providers private static void DependencyRemovedCallbackForFragment(string key, object value, CacheItemRemovedReason reason) { Debug.Trace("OutputCache", "DependencyRemovedCallbackForFragment: reason=" + reason + ", key=" + key); if (reason == CacheItemRemovedReason.DependencyChanged) { DependencyCacheEntry dce = value as DependencyCacheEntry; if (dce.OutputCacheEntryKey != null) { try { OutputCache.RemoveFragment(dce.OutputCacheEntryKey, dce.ProviderName); } catch (Exception e) { HandleErrorWithoutContext(e); } } } } // only used by internal cache private static void EntryRemovedCallback(string key, object value, CacheItemRemovedReason reason) { Debug.Trace("OutputCache", "EntryRemovedCallback: reason=" + reason + ", key=" + key); DecrementCount(); PerfCounters.DecrementCounter(AppPerfCounter.OUTPUT_CACHE_ENTRIES); PerfCounters.IncrementCounter(AppPerfCounter.OUTPUT_CACHE_TURNOVER_RATE); CachedRawResponse cachedRawResponse = value as CachedRawResponse; if (cachedRawResponse != null) { String kernelCacheUrl = cachedRawResponse._kernelCacheUrl; // if it is kernel cached, the url will be non-null. // if the entry was re-inserted, don't remove kernel entry since it will be updated if (kernelCacheUrl != null && HttpRuntime.CacheInternal.Get(key) == null) { // invalidate kernel cache entry if (HttpRuntime.UseIntegratedPipeline) { UnsafeIISMethods.MgdFlushKernelCache(kernelCacheUrl); } else { UnsafeNativeMethods.InvalidateKernelCache(kernelCacheUrl); } } } } // // public properties // public static string DefaultProviderName { get { EnsureInitialized(); return (s_defaultProvider != null) ? s_defaultProvider.Name : OutputCache.ASPNET_INTERNAL_PROVIDER_NAME; } } public static OutputCacheProviderCollection Providers { get { EnsureInitialized(); return s_providers; } } // // internal properties and methods // // // If we're not using a provider, we can optimize this so the OutputCacheModule // only need run when there are entries--return true iff count is non-zero. // If we're using a provider, it's not easy to keep track of the number of entries, // so always return true (so OutputCacheModule always runs). // internal static bool InUse { get { return (Providers == null) ? (s_cEntries != 0) : true; } } internal static void ThrowIfProviderNotFound(String providerName) { // null means use default provider or internal cache if (providerName == null) { return; } OutputCacheProviderCollection providers = Providers; if (providers == null || providers[providerName] == null) { throw new ProviderException(SR.GetString(SR.Provider_Not_Found, providerName)); } } internal static bool HasDependencyChanged(bool isFragment, string depKey, string[] fileDeps, string kernelKey, string oceKey, string providerName) { if (depKey == null) { #if DBG Debug.Trace("OutputCache", "HasDependencyChanged(" + depKey + ", ..., " + oceKey + ", ...) --> false"); #endif return false; } // is the file dependency already in the in-memory cache? if (HttpRuntime.CacheInternal.Get(depKey) != null) { #if DBG Debug.Trace("OutputCache", "HasDependencyChanged(" + depKey + ", ..., " + oceKey + ", ...) --> false"); #endif return false; } // deserialize the file dependencies CacheDependency dep = new CacheDependency(0, fileDeps); int idStartIndex = OUTPUTCACHE_KEYPREFIX_DEPENDENCIES.Length; int idLength = depKey.Length - idStartIndex; CacheItemRemovedCallback callback = (isFragment) ? s_dependencyRemovedCallbackForFragment : s_dependencyRemovedCallback; // have the file dependencies changed? if (String.Compare(dep.GetUniqueID(), 0, depKey, idStartIndex, idLength, StringComparison.Ordinal) == 0) { // file dependencies have not changed--cache them with callback to remove OutputCacheEntry if they change HttpRuntime.CacheInternal.UtcInsert(depKey, new DependencyCacheEntry(oceKey, kernelKey, providerName), dep, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, callback); #if DBG Debug.Trace("OutputCache", "HasDependencyChanged(" + depKey + ", ..., " + oceKey + ", ...) --> false, DEPENDENCY RE-INSERTED"); #endif return false; } else { // file dependencies have changed dep.Dispose(); #if DBG Debug.Trace("OutputCache", "HasDependencyChanged(" + depKey + ", ..., " + oceKey + ", ...) --> true, " + dep.GetUniqueID()); #endif return true; } } [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.SerializationFormatter)] public static void Serialize(Stream stream, Object data) { BinaryFormatter formatter = new BinaryFormatter(); if (data is OutputCacheEntry || data is PartialCachingCacheEntry || data is CachedVary || data is ControlCachedVary || data is FileResponseElement || data is MemoryResponseElement || data is SubstitutionResponseElement) { formatter.Serialize(stream, data); } else { throw new ArgumentException(SR.GetString(SR.OutputCacheExtensibility_CantSerializeDeserializeType)); } } [SecurityPermission(SecurityAction.Assert, Flags = SecurityPermissionFlag.SerializationFormatter)] public static object Deserialize(Stream stream) { BinaryFormatter formatter = new BinaryFormatter(); Object data = formatter.Deserialize(stream); if (!(data is OutputCacheEntry || data is PartialCachingCacheEntry || data is CachedVary || data is ControlCachedVary || data is FileResponseElement || data is MemoryResponseElement || data is SubstitutionResponseElement)) { throw new ArgumentException(SR.GetString(SR.OutputCacheExtensibility_CantSerializeDeserializeType)); } return data; } // lookup cached vary // lookup entry // lookup entry for content-encoding internal static Object Get(String key) { // if it's not in the provider or the default provider is undefined, // check the internal cache (we don't know where it is). Object result = null; OutputCacheProvider provider = GetProvider(HttpContext.Current); if (provider != null) { result = provider.Get(key); OutputCacheEntry oce = result as OutputCacheEntry; if (oce != null) { if (HasDependencyChanged(false /*isFragment*/, oce.DependenciesKey, oce.Dependencies, oce.KernelCacheUrl, key, provider.Name)) { OutputCache.RemoveFromProvider(key, provider.Name); #if DBG Debug.Trace("OutputCache", "Get(" + key + ") --> null, " + provider.Name); #endif return null; } result = Convert(oce); } } if (result == null) { result = HttpRuntime.CacheInternal.Get(key); #if DBG string typeName = (result != null) ? result.GetType().Name : "null"; Debug.Trace("OutputCache", "Get(" + key + ") --> " + typeName + ", CacheInternal"); } else { Debug.Trace("OutputCache", "Get(" + key + ") --> " + result.GetType().Name + ", " + provider.Name); #endif } return result; } // lookup fragment internal static Object GetFragment(String key, String providerName) { // if providerName is null, use default provider. // if providerName is not null, get it from the provider collection. // if it's not in the provider or the default provider is undefined, // check the internal cache (we don't know where it is). Object result = null; OutputCacheProvider provider = GetFragmentProvider(providerName); if (provider != null) { result = provider.Get(key); PartialCachingCacheEntry fragment = result as PartialCachingCacheEntry; if (fragment != null) { if (HasDependencyChanged(true /*isFragment*/, fragment._dependenciesKey, fragment._dependencies, null /*kernelKey*/, key, provider.Name)) { OutputCache.RemoveFragment(key, provider.Name); #if DBG Debug.Trace("OutputCache", "GetFragment(" + key + "," + providerName + ") --> null, " + providerName); #endif return null; } } } if (result == null) { result = HttpRuntime.CacheInternal.Get(key); #if DBG string typeName = (result != null) ? result.GetType().Name : "null"; Debug.Trace("OutputCache", "GetFragment(" + key + "," + providerName + ") --> " + typeName + ", CacheInternal"); } else { Debug.Trace("OutputCache", "GetFragment(" + key + "," + providerName + ") --> " + result.GetType().Name + ", " + providerName); #endif } return result; } // remove cache vary // remove entry internal static void Remove(String key, HttpContext context) { // we don't know if it's in the internal cache or // one of the providers. If a context is given, // then we can narrow down to at most one provider. // If the context is null, then we don't know which // provider and we have to check all. HttpRuntime.CacheInternal.Remove(key); if (context == null) { // remove from all providers since we don't know which one it's in. OutputCacheProviderCollection providers = Providers; if (providers != null) { foreach (OutputCacheProvider provider in providers) { provider.Remove(key); } } } else { OutputCacheProvider provider = GetProvider(context); if (provider != null) { provider.Remove(key); } } #if DBG Debug.Trace("OutputCache", "Remove(" + key + ", context)"); #endif } // remove cache vary // remove entry internal static void RemoveFromProvider(String key, String providerName) { // we know where it is. If providerName is given, // then it is in that provider. If it's not given, // it's in the internal cache. if (providerName == null) { throw new ArgumentNullException("providerName"); } OutputCacheProviderCollection providers = Providers; OutputCacheProvider provider = (providers == null) ? null : providers[providerName]; if (provider == null) { throw new ProviderException(SR.GetString(SR.Provider_Not_Found, providerName)); } provider.Remove(key); #if DBG Debug.Trace("OutputCache", "Remove(" + key + ", " + providerName + ")"); #endif } // remove fragment internal static void RemoveFragment(String key, String providerName) { // if providerName is null, use default provider. // if providerName is not null, get it from the provider collection. // remove it from the provider and the internal cache (we don't know where it is). OutputCacheProvider provider = GetFragmentProvider(providerName); if (provider != null) { provider.Remove(key); } HttpRuntime.CacheInternal.Remove(key); #if DBG Debug.Trace("OutputCache", "RemoveFragment(" + key + "," + providerName + ")"); #endif } // insert fragment internal static void InsertFragment(String cachedVaryKey, ControlCachedVary cachedVary, String fragmentKey, PartialCachingCacheEntry fragment, CacheDependency dependencies, DateTime absExp, TimeSpan slidingExp, String providerName) { // if providerName is not null, find the provider in the collection. // if providerName is null, use default provider. // if the default provider is undefined or the fragment can't be inserted in the // provider, insert it in the internal cache. OutputCacheProvider provider = GetFragmentProvider(providerName); // // ControlCachedVary and PartialCachingCacheEntry can be serialized // bool useProvider = (provider != null); if (useProvider) { bool canUseProvider = (slidingExp == Cache.NoSlidingExpiration && (dependencies == null || dependencies.IsFileDependency())); if (useProvider && !canUseProvider) { throw new ProviderException(SR.GetString(SR.Provider_does_not_support_policy_for_fragments, providerName)); } } #if DBG bool cachedVaryPutInCache = (cachedVary != null); #endif if (cachedVary != null) { // Add the ControlCachedVary item so that a request will know // which varies are needed to issue another request. // Use the Add method so that we guarantee we only use // a single ControlCachedVary and don't overwrite existing ones. ControlCachedVary cachedVaryInCache; if (!useProvider) { cachedVaryInCache = OutputCache.UtcAdd(cachedVaryKey, cachedVary); } else { cachedVaryInCache = (ControlCachedVary) provider.Add(cachedVaryKey, cachedVary, Cache.NoAbsoluteExpiration); } if (cachedVaryInCache != null) { if (!cachedVary.Equals(cachedVaryInCache)) { // overwrite existing cached vary if (!useProvider) { HttpRuntime.CacheInternal.UtcInsert(cachedVaryKey, cachedVary); } else { provider.Set(cachedVaryKey, cachedVary, Cache.NoAbsoluteExpiration); } } else { cachedVary = cachedVaryInCache; #if DBG cachedVaryPutInCache = false; #endif } } if (!useProvider) { AddCacheKeyToDependencies(ref dependencies, cachedVaryKey); } // not all caches support cache key dependencies, but we can use a "change number" to associate // the ControlCachedVary and the PartialCachingCacheEntry fragment._cachedVaryId = cachedVary.CachedVaryId; } // Now insert into the cache (use cache provider if possible, otherwise use internal cache) if (!useProvider) { HttpRuntime.CacheInternal.UtcInsert(fragmentKey, fragment, dependencies, absExp, slidingExp, CacheItemPriority.Normal, null); } else { string depKey = null; if (dependencies != null) { depKey = OUTPUTCACHE_KEYPREFIX_DEPENDENCIES + dependencies.GetUniqueID(); fragment._dependenciesKey = depKey; fragment._dependencies = dependencies.GetFileDependencies(); } provider.Set(fragmentKey, fragment, absExp); if (dependencies != null) { // use Add and dispose dependencies if there's already one in the cache Object d = HttpRuntime.CacheInternal.UtcAdd(depKey, new DependencyCacheEntry(fragmentKey, null, provider.Name), dependencies, absExp, Cache.NoSlidingExpiration, CacheItemPriority.Normal, s_dependencyRemovedCallbackForFragment); if (d != null) { dependencies.Dispose(); } } } #if DBG string cachedVaryType = (cachedVaryPutInCache) ? "ControlCachedVary" : ""; string providerUsed = (useProvider) ? provider.Name : "CacheInternal"; Debug.Trace("OutputCache", "InsertFragment(" + cachedVaryKey + ", " + cachedVaryType + ", " + fragmentKey + ", PartialCachingCacheEntry, ...) -->" + providerUsed); #endif } // insert cached vary or output cache entry internal static void InsertResponse(String cachedVaryKey, CachedVary cachedVary, String rawResponseKey, CachedRawResponse rawResponse, CacheDependency dependencies, DateTime absExp, TimeSpan slidingExp) { // if the provider is undefined or the fragment can't be inserted in the // provider, insert it in the internal cache. OutputCacheProvider provider = GetProvider(HttpContext.Current); // // CachedVary can be serialized. // CachedRawResponse is not always serializable. // bool useProvider = (provider != null); if (useProvider) { bool canUseProvider = (IsSubstBlockSerializable(rawResponse._rawResponse) && rawResponse._settings.IsValidationCallbackSerializable() && slidingExp == Cache.NoSlidingExpiration && (dependencies == null || dependencies.IsFileDependency())); if (useProvider && !canUseProvider) { throw new ProviderException(SR.GetString(SR.Provider_does_not_support_policy_for_responses, provider.Name)); } } #if DBG bool cachedVaryPutInCache = (cachedVary != null); #endif if (cachedVary != null) { /* * Add the CachedVary item so that a request will know * which headers are needed to issue another request. * * Use the Add method so that we guarantee we only use * a single CachedVary and don't overwrite existing ones. */ CachedVary cachedVaryInCache; if (!useProvider) { cachedVaryInCache = OutputCache.UtcAdd(cachedVaryKey, cachedVary); } else { cachedVaryInCache = (CachedVary) provider.Add(cachedVaryKey, cachedVary, Cache.NoAbsoluteExpiration); } if (cachedVaryInCache != null) { if (!cachedVary.Equals(cachedVaryInCache)) { if (!useProvider) { HttpRuntime.CacheInternal.UtcInsert(cachedVaryKey, cachedVary); } else { provider.Set(cachedVaryKey, cachedVary, Cache.NoAbsoluteExpiration); } } else { cachedVary = cachedVaryInCache; #if DBG cachedVaryPutInCache = false; #endif } } if (!useProvider) { AddCacheKeyToDependencies(ref dependencies, cachedVaryKey); } // not all caches support cache key dependencies, but we can use a "change number" to associate // the ControlCachedVary and the PartialCachingCacheEntry rawResponse._cachedVaryId = cachedVary.CachedVaryId; } // Now insert into the cache (use cache provider if possible, otherwise use internal cache) if (!useProvider) { HttpRuntime.CacheInternal.UtcInsert(rawResponseKey, rawResponse, dependencies, absExp, slidingExp, CacheItemPriority.Normal, s_entryRemovedCallback); IncrementCount(); PerfCounters.IncrementCounter(AppPerfCounter.OUTPUT_CACHE_ENTRIES); PerfCounters.IncrementCounter(AppPerfCounter.OUTPUT_CACHE_TURNOVER_RATE); } else { string depKey = null; string[] fileDeps = null; if (dependencies != null) { depKey = OUTPUTCACHE_KEYPREFIX_DEPENDENCIES + dependencies.GetUniqueID(); fileDeps = dependencies.GetFileDependencies(); } OutputCacheEntry oce = Convert(rawResponse, depKey, fileDeps); provider.Set(rawResponseKey, oce, absExp); if (dependencies != null) { // use Add and dispose dependencies if there's already one in the cache Object d = HttpRuntime.CacheInternal.UtcAdd(depKey, new DependencyCacheEntry(rawResponseKey, oce.KernelCacheUrl, provider.Name), dependencies, absExp, Cache.NoSlidingExpiration, CacheItemPriority.Normal, s_dependencyRemovedCallback); if (d != null) { dependencies.Dispose(); } } } #if DBG string cachedVaryType = (cachedVaryPutInCache) ? "CachedVary" : ""; string providerUsed = (useProvider) ? provider.Name : "CacheInternal"; Debug.Trace("OutputCache", "InsertResposne(" + cachedVaryKey + ", " + cachedVaryType + ", " + rawResponseKey + ", CachedRawResponse, ...) -->" + providerUsed); #endif } } }
using System; using System.Drawing.Imaging; namespace Rimss.GraphicsProcessing.Palette.Extensions { /// <summary> /// The utility extender class. /// </summary> public static partial class Extend { /// <summary> /// Gets the bit count for a given pixel format. /// </summary> /// <param name="pixelFormat">The pixel format.</param> /// <returns>The bit count.</returns> public static Byte GetBitDepth(this PixelFormat pixelFormat) { switch (pixelFormat) { case PixelFormat.Format1bppIndexed: return 1; case PixelFormat.Format4bppIndexed: return 4; case PixelFormat.Format8bppIndexed: return 8; case PixelFormat.Format16bppArgb1555: case PixelFormat.Format16bppGrayScale: case PixelFormat.Format16bppRgb555: case PixelFormat.Format16bppRgb565: return 16; case PixelFormat.Format24bppRgb: return 24; case PixelFormat.Format32bppArgb: case PixelFormat.Format32bppPArgb: case PixelFormat.Format32bppRgb: return 32; case PixelFormat.Format48bppRgb: return 48; case PixelFormat.Format64bppArgb: case PixelFormat.Format64bppPArgb: return 64; default: String message = string.Format("A pixel format '{0}' not supported!", pixelFormat); throw new NotSupportedException(message); } } /// <summary> /// Gets the available color count for a given pixel format. /// </summary> /// <param name="pixelFormat">The pixel format.</param> /// <returns>The available color count.</returns> public static UInt16 GetColorCount(this PixelFormat pixelFormat) { // checks whether a pixel format is indexed, otherwise throw an exception if (!pixelFormat.IsIndexed()) { String message = string.Format("Cannot retrieve color count for a non-indexed format '{0}'.", pixelFormat); throw new NotSupportedException(message); } switch (pixelFormat) { case PixelFormat.Format1bppIndexed: return 2; case PixelFormat.Format4bppIndexed: return 16; case PixelFormat.Format8bppIndexed: return 256; default: String message = string.Format("A pixel format '{0}' not supported!", pixelFormat); throw new NotSupportedException(message); } } /// <summary> /// Gets the friendly name of the pixel format. /// </summary> /// <param name="pixelFormat">The pixel format.</param> /// <returns></returns> public static String GetFriendlyName(this PixelFormat pixelFormat) { switch (pixelFormat) { case PixelFormat.Format1bppIndexed: return "Indexed (2 colors)"; case PixelFormat.Format4bppIndexed: return "Indexed (16 colors)"; case PixelFormat.Format8bppIndexed: return "Indexed (256 colors)"; case PixelFormat.Format16bppGrayScale: return "Grayscale (65536 shades)"; case PixelFormat.Format16bppArgb1555: return "Highcolor + Alpha mask (32768 colors)"; case PixelFormat.Format16bppRgb555: case PixelFormat.Format16bppRgb565: return "Highcolor (65536 colors)"; case PixelFormat.Format24bppRgb: return "Truecolor (24-bit)"; case PixelFormat.Format32bppArgb: case PixelFormat.Format32bppPArgb: return "Truecolor + Alpha (32-bit)"; case PixelFormat.Format32bppRgb: return "Truecolor (32-bit)"; case PixelFormat.Format48bppRgb: return "Truecolor (48-bit)"; case PixelFormat.Format64bppArgb: case PixelFormat.Format64bppPArgb: return "Truecolor + Alpha (64-bit)"; default: String message = string.Format("A pixel format '{0}' not supported!", pixelFormat); throw new NotSupportedException(message); } } /// <summary> /// Determines whether the specified pixel format is indexed. /// </summary> /// <param name="pixelFormat">The pixel format.</param> /// <returns> /// <c>true</c> if the specified pixel format is indexed; otherwise, <c>false</c>. /// </returns> public static Boolean IsIndexed(this PixelFormat pixelFormat) { return (pixelFormat & PixelFormat.Indexed) == PixelFormat.Indexed; } /// <summary> /// Determines whether the specified pixel format is supported. /// </summary> /// <param name="pixelFormat">The pixel format.</param> /// <returns> /// <c>true</c> if the specified pixel format is supported; otherwise, <c>false</c>. /// </returns> public static Boolean IsSupported(this PixelFormat pixelFormat) { switch (pixelFormat) { case PixelFormat.Format1bppIndexed: case PixelFormat.Format4bppIndexed: case PixelFormat.Format8bppIndexed: case PixelFormat.Format16bppArgb1555: case PixelFormat.Format16bppRgb555: case PixelFormat.Format16bppRgb565: case PixelFormat.Format24bppRgb: case PixelFormat.Format32bppArgb: case PixelFormat.Format32bppPArgb: case PixelFormat.Format32bppRgb: case PixelFormat.Format48bppRgb: case PixelFormat.Format64bppArgb: case PixelFormat.Format64bppPArgb: return true; default: return false; } } /// <summary> /// Gets the format by color count. /// </summary> public static PixelFormat GetFormatByColorCount(Int32 colorCount) { if (colorCount <= 0 || colorCount > 256) { String message = string.Format("A color count '{0}' not supported!", colorCount); throw new NotSupportedException(message); } PixelFormat result = PixelFormat.Format1bppIndexed; if (colorCount > 16) { result = PixelFormat.Format8bppIndexed; } else if (colorCount > 2) { result = PixelFormat.Format4bppIndexed; } return result; } /// <summary> /// Determines whether the specified pixel format has an alpha channel. /// </summary> /// <param name="pixelFormat">The pixel format.</param> /// <returns> /// <c>true</c> if the specified pixel format has an alpha channel; otherwise, <c>false</c>. /// </returns> public static Boolean HasAlpha(this PixelFormat pixelFormat) { return (pixelFormat & PixelFormat.Alpha) == PixelFormat.Alpha || (pixelFormat & PixelFormat.PAlpha) == PixelFormat.PAlpha; } /// <summary> /// Determines whether [is deep color] [the specified pixel format]. /// </summary> /// <param name="pixelFormat">The pixel format.</param> /// <returns> /// <c>true</c> if [is deep color] [the specified pixel format]; otherwise, <c>false</c>. /// </returns> public static Boolean IsDeepColor(this PixelFormat pixelFormat) { switch (pixelFormat) { case PixelFormat.Format16bppGrayScale: case PixelFormat.Format48bppRgb: case PixelFormat.Format64bppArgb: case PixelFormat.Format64bppPArgb: return true; default: return false; } } } }
//----------------------------------------------------------------------- // <copyright file="DepthMeshCollider.cs" company="Google LLC"> // // 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. // // </copyright> //----------------------------------------------------------------------- using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.Serialization; using UnityEngine.XR.ARFoundation; using UnityEngine.XR.ARSubsystems; /// <summary> /// Manages the collision physics and events when the user throws a virtual game object (projectile) /// in the physical environment. /// </summary> public class DepthMeshCollider : MonoBehaviour { /// <summary> /// Depth processing script. /// </summary> [FormerlySerializedAs("depthProcessingCS")] public ComputeShader DepthProcessingCS; /// <summary> /// Whether to compute the normal vector. /// </summary> [FormerlySerializedAs("calculateNormals")] public bool CalculateNormals = false; /// <summary> /// An array of game object thrown by the user. /// </summary> [FormerlySerializedAs("projectiles")] public GameObject[] Projectiles; /// <summary> /// Life time in seconds of the thrown game object. /// </summary> [FormerlySerializedAs("projectileLifetimeS")] public int ProjectileLifetimeS = _projectileLifetimeS; /// <summary> /// Whether to enable the renderer. /// </summary> [FormerlySerializedAs("render")] public bool Render = false; /// <summary> /// Flag to enable sparse depth. /// </summary> public bool UseRawDepth; /// <summary> /// Makes sure physics objects don't fall through. /// </summary> public bool ExtendMeshEdges = true; /// <summary> /// Offset from where the projectile starts. /// </summary> public float ForwardOffset = 0.25f; /// <summary> /// Triggers when the ColliderMesh is ready. /// </summary> [FormerlySerializedAs("colliderMeshReadyEvent")] public UnityEvent ColliderMeshReadyEvent; /// <summary> /// How much thrust are we giving to the projectile. /// </summary> public float ProjectileThrust = 5; // Number of threads used by the compute shader. private const int _numThreadsX = 8; private const int _numThreadsY = 8; private const int _kDepthPixelSkippingX = 2; private const int _kDepthPixelSkippingY = 2; private const int _normalSamplingOffset = 1; private const int _projectileLifetimeS = 180; private const float _edgeExtensionOffset = 0.5f; private const float _edgeExtensionDepthOffset = -0.5f; // Holds the vertex and index data of the depth template mesh. private Mesh _mesh; private bool _initialized = false; private MeshCollider _meshCollider; private System.Random _random = new System.Random(); private int _vertexFromDepthHandle; private int _normalFromVertexHandle; private int _numElements; private ComputeBuffer _vertexBuffer; private ComputeBuffer _normalBuffer; private Vector3[] _vertices; private Vector3[] _normals; private int _getDataCountdown = -1; private int _depthPixelSkippingX = _kDepthPixelSkippingX; private int _depthPixelSkippingY = _kDepthPixelSkippingY; private int _meshWidth; private int _meshHeight; private GameObject _root = null; private List<GameObject> _gameObjects = new List<GameObject>(); private bool _cachedUseRawDepth = false; private AROcclusionManager _occlusionManager; private Texture2D _depthTexture; /// <summary> /// Throws a game object for the collision test. /// </summary> public void ShootProjectile() { UpdateMesh(); } /// <summary> /// Instantiates a game object from prefab and throws it. /// </summary> public void ShootPrefab() { if (_root == null) { _root = new GameObject("Projectiles"); } GameObject bullet = Instantiate( Projectiles[_random.Next(Projectiles.Length)], DepthSource.ARCamera.transform.position + (DepthSource.ARCamera.transform.forward * ForwardOffset), Quaternion.identity); Vector3 forceVector = DepthSource.ARCamera.transform.forward * ProjectileThrust; bullet.GetComponent<Rigidbody>().velocity = forceVector; bullet.transform.parent = _root.transform; _gameObjects.Add(bullet); } /// <summary> /// Clears all the instantiated projectiles. /// </summary> public void Clear() { foreach (GameObject go in _gameObjects) { Destroy(go); } _gameObjects.Clear(); if (_root != null) { Debug.Log("Destroy all projectiles " + _root.transform.childCount); foreach (Transform child in _root.transform) { Destroy(child.gameObject); } } } private static int[] GenerateTriangles(int width, int height) { int[] indices = new int[(height - 1) * (width - 1) * 6]; int idx = 0; for (int y = 0; y < (height - 1); y++) { for (int x = 0; x < (width - 1); x++) { //// Unity has a clockwise triangle winding order. //// Upper quad triangle //// Top left int idx0 = (y * width) + x; //// Top right int idx1 = idx0 + 1; //// Bottom left int idx2 = idx0 + width; //// Lower quad triangle //// Top right int idx3 = idx1; //// Bottom right int idx4 = idx2 + 1; //// Bottom left int idx5 = idx2; indices[idx++] = idx0; indices[idx++] = idx1; indices[idx++] = idx2; indices[idx++] = idx3; indices[idx++] = idx4; indices[idx++] = idx5; } } return indices; } private void OnDestroy() { ARSession.stateChanged -= OnSessionStateChanged; Clear(); if (_root != null) { Destroy(_root); } _root = null; _vertexBuffer.Dispose(); _normalBuffer.Dispose(); } private void Start() { _meshCollider = GetComponent<MeshCollider>(); GetComponent<MeshRenderer>().enabled = Render; _occlusionManager = FindObjectOfType<AROcclusionManager>(); Debug.Assert(_occlusionManager); ARSession.stateChanged += OnSessionStateChanged; } private void Update() { if (_initialized) { if (_getDataCountdown > 0) { _getDataCountdown--; } else if (_getDataCountdown == 0) { UpdateDepthTexture(); UpdateCollider(); } } else { if (DepthSource.Initialized) { if (_cachedUseRawDepth != UseRawDepth) { DepthSource.SwitchToRawDepth(UseRawDepth); _cachedUseRawDepth = UseRawDepth; } _meshWidth = DepthSource.DepthWidth / _depthPixelSkippingX; _meshHeight = DepthSource.DepthHeight / _depthPixelSkippingY; _numElements = _meshWidth * _meshHeight; UpdateDepthTexture(); InitializeComputeShader(); InitializeMesh(); _initialized = true; } } } private void InitializeMesh() { // Creates template vertices. _vertices = new Vector3[_numElements]; _normals = new Vector3[_numElements]; // Creates template vertices for the mesh object. for (int y = 0; y < _meshHeight; y++) { for (int x = 0; x < _meshWidth; x++) { int index = (y * _meshWidth) + x; Vector3 v = new Vector3(x * 0.01f, -y * 0.01f, 0); _vertices[index] = v; _normals[index] = Vector3.back; } } // Creates template triangle list. int[] triangles = GenerateTriangles(_meshWidth, _meshHeight); // Creates the mesh object and set all template data. _mesh = new Mesh(); _mesh.MarkDynamic(); _mesh.indexFormat = UnityEngine.Rendering.IndexFormat.UInt32; _mesh.vertices = _vertices; _mesh.normals = _normals; _mesh.triangles = triangles; _mesh.bounds = new Bounds(Vector3.zero, new Vector3(20, 20, 20)); _mesh.UploadMeshData(false); if (Render) { GetComponent<MeshFilter>().sharedMesh = _mesh; } } private void InitializeComputeShader() { _vertexFromDepthHandle = DepthProcessingCS.FindKernel("VertexFromDepth"); _normalFromVertexHandle = DepthProcessingCS.FindKernel("NormalFromVertex"); _vertexBuffer = new ComputeBuffer(_numElements, sizeof(float) * 3); _normalBuffer = new ComputeBuffer(_numElements, sizeof(float) * 3); // Sets general compute shader variables. DepthProcessingCS.SetInt("DepthWidth", DepthSource.ImageDimensions.x); DepthProcessingCS.SetInt("DepthHeight", DepthSource.ImageDimensions.y); DepthProcessingCS.SetFloat("PrincipalX", DepthSource.PrincipalPoint.x); DepthProcessingCS.SetFloat("PrincipalY", DepthSource.PrincipalPoint.y); DepthProcessingCS.SetFloat("FocalLengthX", DepthSource.FocalLength.x); DepthProcessingCS.SetFloat("FocalLengthY", DepthSource.FocalLength.y); DepthProcessingCS.SetInt("NormalSamplingOffset", _normalSamplingOffset); DepthProcessingCS.SetInt("DepthPixelSkippingX", _depthPixelSkippingX); DepthProcessingCS.SetInt("DepthPixelSkippingY", _depthPixelSkippingY); DepthProcessingCS.SetInt("MeshWidth", _meshWidth); DepthProcessingCS.SetInt("MeshHeight", _meshHeight); DepthProcessingCS.SetBool("ExtendEdges", ExtendMeshEdges); DepthProcessingCS.SetFloat("EdgeExtensionOffset", _edgeExtensionOffset); DepthProcessingCS.SetFloat("EdgeExtensionDepthOffset", _edgeExtensionDepthOffset); // Sets shader resources for the vertex function. DepthProcessingCS.SetBuffer(_vertexFromDepthHandle, "vertexBuffer", _vertexBuffer); // Sets shader resources for the normal function. DepthProcessingCS.SetBuffer(_normalFromVertexHandle, "vertexBuffer", _vertexBuffer); DepthProcessingCS.SetBuffer(_normalFromVertexHandle, "normalBuffer", _normalBuffer); } private void UpdateMesh() { if (!_initialized) { return; } UpdateComputeShaderVariables(); DepthProcessingCS.Dispatch(_vertexFromDepthHandle, _meshWidth / _numThreadsX, (_meshHeight / _numThreadsY) + 1, 1); _getDataCountdown = 2; if (Render) { _vertexBuffer.GetData(_vertices); _mesh.vertices = _vertices; _mesh.RecalculateNormals(); _mesh.UploadMeshData(false); } } private void UpdateCollider() { _getDataCountdown = -1; _vertexBuffer.GetData(_vertices); _mesh.vertices = _vertices; _meshCollider.sharedMesh = null; _meshCollider.sharedMesh = _mesh; OnColliderMeshReady(); } private void OnColliderMeshReady() { ColliderMeshReadyEvent?.Invoke(); } private void UpdateComputeShaderVariables() { DepthProcessingCS.SetTexture(_vertexFromDepthHandle, "depthTex", _depthTexture); DepthProcessingCS.SetMatrix("ModelTransform", DepthSource.LocalToWorldMatrix); } private void OnSessionStateChanged(ARSessionStateChangedEventArgs eventArgs) { if (eventArgs.state == ARSessionState.SessionInitializing) { // Clear all projectiles for a new session. Clear(); } } private void UpdateDepthTexture() { if (_occlusionManager.TryAcquireEnvironmentDepthCpuImage(out XRCpuImage image)) { UpdateRawImage(ref _depthTexture, image); } image.Dispose(); } private void UpdateRawImage(ref Texture2D texture, XRCpuImage cpuImage) { if (texture == null || texture.width != cpuImage.width || texture.height != cpuImage.height) { texture = new Texture2D(cpuImage.width, cpuImage.height, TextureFormat.RGB565, false); } var conversionParams = new XRCpuImage.ConversionParams(cpuImage, TextureFormat.R16); var rawTextureData = texture.GetRawTextureData<byte>(); cpuImage.Convert(conversionParams, rawTextureData); texture.Apply(); } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Linq; using Adxstudio.Xrm.Resources; using Microsoft.Xrm.Client; using Microsoft.Xrm.Portal.Core; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; namespace Adxstudio.Xrm.Commerce { public static class OrganizationServiceContextExtensions { public static IEnumerable<Entity> GetCartsForContact(this OrganizationServiceContext context, Entity contact, Entity website) { contact.AssertEntityName("contact"); website.AssertEntityName("adx_website"); var findShoppingCarts = from sc in context.CreateQuery("adx_shoppingcart") where sc.GetAttributeValue<EntityReference>("adx_contactid") == contact.ToEntityReference() && sc.GetAttributeValue<EntityReference>("adx_websiteid") == website.ToEntityReference() && sc.GetAttributeValue<OptionSetValue>("statuscode") != null && sc.GetAttributeValue<OptionSetValue>("statuscode").Value == 1 && sc.GetAttributeValue<bool?>("adx_system").GetValueOrDefault(false) == false select sc; return findShoppingCarts; } public static IEnumerable<Entity> GetCartsForVisitor(this OrganizationServiceContext context, string visitorId, Entity website) { website.AssertEntityName("adx_website"); var findShoppingCarts = from sc in context.CreateQuery("adx_shoppingcart") where sc.GetAttributeValue<string>("adx_visitorid") == visitorId && sc.GetAttributeValue<EntityReference>("adx_websiteid") == website.ToEntityReference() && sc.GetAttributeValue<OptionSetValue>("statuscode") != null && sc.GetAttributeValue<OptionSetValue>("statuscode").Value == 1 && sc.GetAttributeValue<bool?>("adx_system").GetValueOrDefault(false) == false select sc; return findShoppingCarts; } public static Entity GetCartItemByID(this OrganizationServiceContext context, Guid id) { var findShoppingCartItem = from sc in context.CreateQuery("adx_shoppingcartitem") where sc.GetAttributeValue<Guid>("adx_shoppingcartitemid") == id select sc; return findShoppingCartItem.FirstOrDefault(); } public static IEnumerable<Entity> GetOrdersForContact(this OrganizationServiceContext context, Entity contact) { var findOrders = from o in context.CreateQuery("salesorder") where o.GetAttributeValue<EntityReference>("customerid") == contact.ToEntityReference() select o; return findOrders; } public static IEnumerable<Entity> GetQuotesForContact(this OrganizationServiceContext context, Entity contact) { var findOrders = from o in context.CreateQuery("quote") where o.GetAttributeValue<EntityReference>("customerid") == contact.ToEntityReference() select o; return findOrders; } public static Money GetProductPriceByPriceListName(this OrganizationServiceContext context, Entity product, Entity website, string priceListName) { product.AssertEntityName("product"); website.AssertEntityName("adx_website"); var priceListItem = context.GetPriceListItemByPriceListName(product, priceListName); var returnPrice = priceListItem != null ? priceListItem.GetAttributeValue<Money>("amount") : null; if (returnPrice == null) { priceListItem = context.GetPriceListItemByPriceListName(product, context.GetDefaultPriceListName(website)); returnPrice = priceListItem != null ? priceListItem.GetAttributeValue<Money>("amount") : null; } return returnPrice; } public static Money GetProductPriceByPriceListName(this OrganizationServiceContext context, Guid productID, Entity website, string priceListName) { website.AssertEntityName("adx_website"); var product = context.CreateQuery("product").FirstOrDefault(p => p.GetAttributeValue<Guid>("productid") == productID); return context.GetProductPriceByPriceListName(product, website, priceListName); } public static string GetPriceListNameForParentAccount(this OrganizationServiceContext context, Entity contact) { var priceLevel = context.GetPriceListForParentAccount(contact); return priceLevel != null ? priceLevel.GetAttributeValue<string>("name") : null; } public static Entity GetPriceListForParentAccount(this OrganizationServiceContext context, Entity contact) { contact.AssertEntityName("contact"); var priceLevels = from pricelevel in context.CreateQuery("pricelevel") join account in context.CreateQuery("account") on pricelevel.GetAttributeValue<Guid>("pricelevelid") equals account.GetAttributeValue<EntityReference>("defaultpricelevelid").Id where account.GetAttributeValue<Guid>("accountid") == (contact.GetAttributeValue<EntityReference>("parentcustomerid") == null ? Guid.Empty : contact.GetAttributeValue<EntityReference>("parentcustomerid").Id) select pricelevel; return priceLevels.FirstOrDefault(); } public static string GetDefaultPriceListName(this OrganizationServiceContext context, Entity website) { website.AssertEntityName("adx_website"); var defaultPriceLevelSetting = context.CreateQuery("adx_sitesetting") .Where(ss => ss.GetAttributeValue<EntityReference>("adx_websiteid") == website.ToEntityReference()) .FirstOrDefault(purl => purl.GetAttributeValue<string>("adx_name") == "Ecommerce/DefaultPriceLevelName"); return defaultPriceLevelSetting == null || string.IsNullOrWhiteSpace(defaultPriceLevelSetting.GetAttributeValue<string>("adx_value")) ? "Web" : defaultPriceLevelSetting.GetAttributeValue<string>("adx_value"); } public static string GetDefaultPriceListName(this OrganizationServiceContext context, Guid websiteid) { var defaultPriceLevelSetting = context.CreateQuery("adx_sitesetting") .Where(ss => ss.GetAttributeValue<EntityReference>("adx_websiteid") == new EntityReference("adx_website", websiteid)) .FirstOrDefault(purl => purl.GetAttributeValue<string>("adx_name") == "Ecommerce/DefaultPriceLevelName"); return defaultPriceLevelSetting == null || string.IsNullOrWhiteSpace(defaultPriceLevelSetting.GetAttributeValue<string>("adx_value")) ? "Web" : defaultPriceLevelSetting.GetAttributeValue<string>("adx_value"); } public static Entity GetDefaultUomByProduct(this OrganizationServiceContext context, Entity product) { var uom = context.CreateQuery("uom").FirstOrDefault(um => um.GetAttributeValue<Guid>("uomid") == product.GetAttributeValue<EntityReference>("defaultuomid").Id); return uom; } public static Money GetProductPriceByPriceListName(this OrganizationServiceContext context, Entity product, string priceListName) { product.AssertEntityName("product"); return context.GetProductPriceByPriceListName(product.GetAttributeValue<Guid>("productid"), priceListName); } public static Money GetProductPriceByPriceListName(this OrganizationServiceContext context, Guid productID, string priceListName) { var priceListItem = context.GetPriceListItemByPriceListName(productID, priceListName); return priceListItem != null ? priceListItem.GetAttributeValue<Money>("amount") : null; } public static Entity GetPriceListItemByPriceListName(this OrganizationServiceContext context, Guid productID, string priceListName) { var product = context.CreateQuery("product").FirstOrDefault(p => p.GetAttributeValue<Guid>("productid") == productID); return context.GetPriceListItemByPriceListName(product, priceListName); } public static Entity GetPriceListItemByPriceListName(this OrganizationServiceContext context, Entity product, string priceListName) { product.AssertEntityName("product"); var defaultUOM = context.GetDefaultUomByProduct(product); return context.GetPriceListItemByPriceListNameAndUom(product.GetAttributeValue<Guid>("productid"), defaultUOM.GetAttributeValue<Guid>("uomid"), priceListName); } public static Entity GetPriceListItemByPriceListNameAndUom(this OrganizationServiceContext context, Guid productID, Guid uomid, string priceListName) { var product = context.CreateQuery("product").FirstOrDefault(p => p.GetAttributeValue<Guid>("productid") == productID); return context.GetPriceListItemByPriceListNameAndUom(product, uomid, priceListName); } public static Entity GetPriceListItemByPriceListNameAndUom(this OrganizationServiceContext context, Entity product, Guid uomid, string priceListName) { var priceListItems = from pl in context.CreateQuery("pricelevel") join ppl in context.CreateQuery("productpricelevel") on pl.GetAttributeValue<Guid>("pricelevelid") equals ppl.GetAttributeValue<EntityReference>("pricelevelid").Id where ppl.GetAttributeValue<EntityReference>("pricelevelid") != null && ppl.GetAttributeValue<EntityReference>("productid") != null && ppl.GetAttributeValue<EntityReference>("productid") == product.ToEntityReference() && ppl.GetAttributeValue<EntityReference>("uomid") == new EntityReference("uom", uomid) where pl.GetAttributeValue<string>("name") == priceListName && ((pl.GetAttributeValue<DateTime?>("begindate") == null || pl.GetAttributeValue<DateTime?>("begindate") <= DateTime.UtcNow) && (pl.GetAttributeValue<DateTime?>("enddate") == null || pl.GetAttributeValue<DateTime?>("enddate") >= DateTime.UtcNow)) select ppl; return priceListItems.FirstOrDefault(); } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System.Diagnostics.Contracts; using System; namespace System { public static class BitConverter { #if !SILVERLIGHT public static double Int64BitsToDouble(Int64 value) { return default(double); } public static Int64 DoubleToInt64Bits(double value) { return default(Int64); } #endif public static bool ToBoolean(Byte[] value, int startIndex) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= (value.Length - 1)); return default(bool); } public static string ToString(Byte[] value, int startIndex) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= value.Length); Contract.Ensures(Contract.Result<string>() != null); return default(string); } public static string ToString(Byte[] value) { Contract.Requires(value != null); Contract.Ensures(Contract.Result<string>() != null); return default(string); } public static string ToString(Byte[] value, int startIndex, int length) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(length >= 0); Contract.Requires(startIndex + length <= value.Length); Contract.Ensures(Contract.Result<string>() != null); return default(string); } public static double ToDouble(Byte[] value, int startIndex) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= value.Length - 8); return default(double); } public static Single ToSingle(Byte[] value, int startIndex) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= value.Length - 4); return default(Single); } public static UInt64 ToUInt64(Byte[] value, int startIndex) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= value.Length - 8); return default(UInt64); } public static UInt32 ToUInt32(Byte[] value, int startIndex) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= value.Length - 4); return default(UInt32); } public static UInt16 ToUInt16(Byte[] value, int startIndex) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= value.Length - 2); return default(UInt16); } public static Int64 ToInt64(Byte[] value, int startIndex) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= value.Length - 8); return default(Int64); } public static int ToInt32(Byte[] value, int startIndex) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= value.Length - 4); return default(int); } public static Int16 ToInt16(Byte[] value, int startIndex) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= value.Length - 2); return default(Int16); } public static Char ToChar(Byte[] value, int startIndex) { Contract.Requires(value != null); Contract.Requires(startIndex >= 0); Contract.Requires(startIndex <= value.Length - 2); return default(Char); } public static Byte[] GetBytes(double value) { Contract.Ensures(Contract.Result<Byte[]>() != null); Contract.Ensures(Contract.Result<Byte[]>().Length == 8); return default(Byte[]); } public static Byte[] GetBytes(Single value) { Contract.Ensures(Contract.Result<Byte[]>() != null); Contract.Ensures(Contract.Result<Byte[]>().Length == 4); return default(Byte[]); } public static Byte[] GetBytes(UInt64 value) { Contract.Ensures(Contract.Result<Byte[]>() != null); Contract.Ensures(Contract.Result<Byte[]>().Length == 8); return default(Byte[]); } public static Byte[] GetBytes(UInt32 value) { Contract.Ensures(Contract.Result<Byte[]>() != null); Contract.Ensures(Contract.Result<Byte[]>().Length == 4); return default(Byte[]); } public static Byte[] GetBytes(UInt16 value) { Contract.Ensures(Contract.Result<Byte[]>() != null); Contract.Ensures(Contract.Result<Byte[]>().Length == 2); return default(Byte[]); } public static Byte[] GetBytes(Int64 arg0) { Contract.Ensures(Contract.Result<Byte[]>() != null); Contract.Ensures(Contract.Result<Byte[]>().Length == 8); return default(Byte[]); } public static Byte[] GetBytes(int arg0) { Contract.Ensures(Contract.Result<Byte[]>() != null); Contract.Ensures(Contract.Result<Byte[]>().Length == 4); return default(Byte[]); } public static Byte[] GetBytes(Int16 arg0) { Contract.Ensures(Contract.Result<Byte[]>() != null); Contract.Ensures(Contract.Result<Byte[]>().Length == 2); return default(Byte[]); } public static Byte[] GetBytes(Char arg0) { Contract.Ensures(Contract.Result<Byte[]>() != null); Contract.Ensures(Contract.Result<Byte[]>().Length == 2); return default(Byte[]); } public static Byte[] GetBytes(bool value) { Contract.Ensures(Contract.Result<Byte[]>() != null); Contract.Ensures(Contract.Result<Byte[]>().Length == 1); return default(Byte[]); } } }
// 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.Data.Common; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Data.OleDb { sealed internal class DBPropSet : SafeHandle { private readonly Int32 propertySetCount; // stores the exception with last error.HRESULT from IDBProperties.GetProperties private Exception lastErrorFromProvider; private DBPropSet() : base(IntPtr.Zero, true) { propertySetCount = 0; } internal DBPropSet(int propertysetCount) : this() { this.propertySetCount = propertysetCount; IntPtr countOfBytes = (IntPtr)(propertysetCount * ODB.SizeOf_tagDBPROPSET); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { base.handle = SafeNativeMethods.CoTaskMemAlloc(countOfBytes); if (ADP.PtrZero != base.handle) { SafeNativeMethods.ZeroMemory(base.handle, (int)countOfBytes); } } if (ADP.PtrZero == base.handle) { throw new OutOfMemoryException(); } } internal DBPropSet(UnsafeNativeMethods.IDBProperties properties, PropertyIDSet propidset, out OleDbHResult hr) : this() { Debug.Assert(null != properties, "null IDBProperties"); int propidsetcount = 0; if (null != propidset) { propidsetcount = propidset.Count; } hr = properties.GetProperties(propidsetcount, propidset, out this.propertySetCount, out base.handle); if (hr < 0) { // remember the last HRESULT. Note we do not want to raise exception now to avoid breaking change from Orcas RTM/SP1 SetLastErrorInfo(hr); } } internal DBPropSet(UnsafeNativeMethods.IRowsetInfo properties, PropertyIDSet propidset, out OleDbHResult hr) : this() { Debug.Assert(null != properties, "null IRowsetInfo"); int propidsetcount = 0; if (null != propidset) { propidsetcount = propidset.Count; } hr = properties.GetProperties(propidsetcount, propidset, out this.propertySetCount, out base.handle); if (hr < 0) { // remember the last HRESULT. Note we do not want to raise exception now to avoid breaking change from Orcas RTM/SP1 SetLastErrorInfo(hr); } } internal DBPropSet(UnsafeNativeMethods.ICommandProperties properties, PropertyIDSet propidset, out OleDbHResult hr) : this() { Debug.Assert(null != properties, "null ICommandProperties"); int propidsetcount = 0; if (null != propidset) { propidsetcount = propidset.Count; } hr = properties.GetProperties(propidsetcount, propidset, out this.propertySetCount, out base.handle); if (hr < 0) { // remember the last HRESULT. Note we do not want to raise exception now to avoid breaking change from Orcas RTM/SP1 SetLastErrorInfo(hr); } } private void SetLastErrorInfo(OleDbHResult lastErrorHr) { // note: OleDbHResult is actually a simple wrapper over HRESULT with OLEDB-specific codes UnsafeNativeMethods.IErrorInfo errorInfo = null; string message = String.Empty; OleDbHResult errorInfoHr = UnsafeNativeMethods.GetErrorInfo(0, out errorInfo); // 0 - IErrorInfo exists, 1 - no IErrorInfo if ((errorInfoHr == OleDbHResult.S_OK) && (errorInfo != null)) { ODB.GetErrorDescription(errorInfo, lastErrorHr, out message); // note that either GetErrorInfo or GetErrorDescription might fail in which case we will have only the HRESULT value in exception message } lastErrorFromProvider = new COMException(message, (int)lastErrorHr); } public override bool IsInvalid { get { return (IntPtr.Zero == base.handle); } } override protected bool ReleaseHandle() { // NOTE: The SafeHandle class guarantees this will be called exactly once and is non-interrutible. IntPtr ptr = base.handle; base.handle = IntPtr.Zero; if (ADP.PtrZero != ptr) { int count = this.propertySetCount; for (int i = 0, offset = 0; i < count; ++i, offset += ODB.SizeOf_tagDBPROPSET) { IntPtr rgProperties = Marshal.ReadIntPtr(ptr, offset); if (ADP.PtrZero != rgProperties) { int cProperties = Marshal.ReadInt32(ptr, offset + ADP.PtrSize); IntPtr vptr = ADP.IntPtrOffset(rgProperties, ODB.OffsetOf_tagDBPROP_Value); for (int k = 0; k < cProperties; ++k, vptr = ADP.IntPtrOffset(vptr, ODB.SizeOf_tagDBPROP)) { SafeNativeMethods.VariantClear(vptr); } SafeNativeMethods.CoTaskMemFree(rgProperties); } } SafeNativeMethods.CoTaskMemFree(ptr); } return true; } internal int PropertySetCount { get { return this.propertySetCount; } } internal tagDBPROP[] GetPropertySet(int index, out Guid propertyset) { if ((index < 0) || (PropertySetCount <= index)) { if (lastErrorFromProvider != null) { // add extra error information for CSS/stress troubleshooting. // We need to keep same exception type to avoid breaking change with Orcas RTM/SP1. throw ADP.InternalError(ADP.InternalErrorCode.InvalidBuffer, lastErrorFromProvider); } else { throw ADP.InternalError(ADP.InternalErrorCode.InvalidBuffer); } } tagDBPROPSET propset = new tagDBPROPSET(); tagDBPROP[] properties = null; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr propertySetPtr = ADP.IntPtrOffset(DangerousGetHandle(), index * ODB.SizeOf_tagDBPROPSET); Marshal.PtrToStructure(propertySetPtr, propset); propertyset = propset.guidPropertySet; properties = new tagDBPROP[propset.cProperties]; for (int i = 0; i < properties.Length; ++i) { properties[i] = new tagDBPROP(); IntPtr ptr = ADP.IntPtrOffset(propset.rgProperties, i * ODB.SizeOf_tagDBPROP); Marshal.PtrToStructure(ptr, properties[i]); } } finally { if (mustRelease) { DangerousRelease(); } } return properties; } internal void SetPropertySet(int index, Guid propertySet, tagDBPROP[] properties) { if ((index < 0) || (PropertySetCount <= index)) { if (lastErrorFromProvider != null) { // add extra error information for CSS/stress troubleshooting. // We need to keep same exception type to avoid breaking change with Orcas RTM/SP1. throw ADP.InternalError(ADP.InternalErrorCode.InvalidBuffer, lastErrorFromProvider); } else { throw ADP.InternalError(ADP.InternalErrorCode.InvalidBuffer); } } Debug.Assert(Guid.Empty != propertySet, "invalid propertySet"); Debug.Assert((null != properties) && (0 < properties.Length), "invalid properties"); IntPtr countOfBytes = (IntPtr)(properties.Length * ODB.SizeOf_tagDBPROP); tagDBPROPSET propset = new tagDBPROPSET(properties.Length, propertySet); bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); IntPtr propsetPtr = ADP.IntPtrOffset(DangerousGetHandle(), index * ODB.SizeOf_tagDBPROPSET); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { // must allocate and clear the memory without interruption propset.rgProperties = SafeNativeMethods.CoTaskMemAlloc(countOfBytes); if (ADP.PtrZero != propset.rgProperties) { // clearing is important so that we don't treat existing // garbage as important information during releaseHandle SafeNativeMethods.ZeroMemory(propset.rgProperties, (int)countOfBytes); // writing the structure to native memory so that it knows to free the referenced pointers Marshal.StructureToPtr(propset, propsetPtr, false/*deleteold*/); } } if (ADP.PtrZero == propset.rgProperties) { throw new OutOfMemoryException(); } for (int i = 0; i < properties.Length; ++i) { Debug.Assert(null != properties[i], "null tagDBPROP " + i.ToString(CultureInfo.InvariantCulture)); IntPtr propertyPtr = ADP.IntPtrOffset(propset.rgProperties, i * ODB.SizeOf_tagDBPROP); Marshal.StructureToPtr(properties[i], propertyPtr, false/*deleteold*/); } } finally { if (mustRelease) { DangerousRelease(); } } } static internal DBPropSet CreateProperty(Guid propertySet, int propertyId, bool required, object value) { tagDBPROP dbprop = new tagDBPROP(propertyId, required, value); DBPropSet propertyset = new DBPropSet(1); propertyset.SetPropertySet(0, propertySet, new tagDBPROP[1] { dbprop }); return propertyset; } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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. *********************************************************************/ #region BSD License /* Copyright (c) 2004-2005 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com) 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. * The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion #region CVS Information /* * $Source$ * $Author: mccollum $ * $Date: 2006-09-08 17:12:07 -0700 (Fri, 08 Sep 2006) $ * $Revision: 6434 $ */ #endregion using System; using System.Collections; using System.IO; using System.Xml; using DNPreBuild.Core.Attributes; using DNPreBuild.Core.Interfaces; using DNPreBuild.Core.Util; namespace DNPreBuild.Core.Nodes { public enum ProjectType { Exe, WinExe, Library } public enum Runtime { Microsoft, Mono } [DataNode("Project")] public class ProjectNode : DataNode { #region Fields private string m_Name = "unknown"; private string m_Path = ""; private string m_FullPath = ""; private string m_AssemblyName = null; private string m_AppIcon = ""; private string m_Language = "C#"; private ProjectType m_Type = ProjectType.Exe; private Runtime m_Runtime = Runtime.Microsoft; private string m_StartupObject = ""; private string m_RootNamespace = null; private Guid m_Guid; private Hashtable m_Configurations = null; private ArrayList m_ReferencePaths = null; private ArrayList m_References = null; private FilesNode m_Files = null; #endregion #region Constructors public ProjectNode() { m_Configurations = new Hashtable(); m_ReferencePaths = new ArrayList(); m_References = new ArrayList(); } #endregion #region Properties public string Name { get { return m_Name; } } public string Path { get { return m_Path; } } public string FullPath { get { return m_FullPath; } } public string AssemblyName { get { return m_AssemblyName; } } public string AppIcon { get { return m_AppIcon; } } public string Language { get { return m_Language; } } public ProjectType Type { get { return m_Type; } } public Runtime Runtime { get { return m_Runtime; } } public string StartupObject { get { return m_StartupObject; } } public string RootNamespace { get { return m_RootNamespace; } } public ICollection Configurations { get { return m_Configurations.Values; } } public Hashtable ConfigurationsTable { get { return m_Configurations; } } public ArrayList ReferencePaths { get { return m_ReferencePaths; } } public ArrayList References { get { return m_References; } } public FilesNode Files { get { return m_Files; } } public override IDataNode Parent { get { return m_Parent; } set { m_Parent = value; if(m_Parent is SolutionNode && m_Configurations.Count < 1) { SolutionNode parent = (SolutionNode)m_Parent; foreach(ConfigurationNode conf in parent.Configurations) m_Configurations[conf.Name] = conf.Clone(); } } } public Guid Guid { get { return m_Guid; } } #endregion #region Private Methods private void HandleConfiguration(ConfigurationNode conf) { if(conf.Name.ToLower() == "all") //apply changes to all, this may not always be applied first, //so it *may* override changes to the same properties for configurations defines at the project level { foreach(ConfigurationNode confNode in this.m_Configurations.Values) { conf.CopyTo(confNode);//update the config templates defines at the project level with the overrides } } if(m_Configurations.ContainsKey(conf.Name)) { ConfigurationNode parentConf = (ConfigurationNode)m_Configurations[conf.Name]; conf.CopyTo(parentConf);//update the config templates defines at the project level with the overrides } else m_Configurations[conf.Name] = conf; } #endregion #region Public Methods public override void Parse(XmlNode node) { m_Name = Helper.AttributeValue(node, "name", m_Name); m_Path = Helper.AttributeValue(node, "path", m_Path); m_AppIcon = Helper.AttributeValue(node, "icon", m_AppIcon); m_AssemblyName = Helper.AttributeValue(node, "assemblyName", m_AssemblyName); m_Language = Helper.AttributeValue(node, "language", m_Language); m_Type = (ProjectType)Helper.EnumAttributeValue(node, "type", typeof(ProjectType), m_Type); m_Runtime = (Runtime)Helper.EnumAttributeValue(node, "runtime", typeof(Runtime), m_Runtime); m_StartupObject = Helper.AttributeValue(node, "startupObject", m_StartupObject); m_RootNamespace = Helper.AttributeValue(node, "rootNamespace", m_RootNamespace); m_Guid = Guid.NewGuid(); if(m_AssemblyName == null || m_AssemblyName.Length < 1) m_AssemblyName = m_Name; if(m_RootNamespace == null || m_RootNamespace.Length < 1) m_RootNamespace = m_Name; m_FullPath = m_Path; try { m_FullPath = Helper.ResolvePath(m_FullPath); } catch { throw new WarningException("Could not resolve Solution path: {0}", m_Path); } Kernel.Instance.CWDStack.Push(); try { Helper.SetCurrentDir(m_FullPath); foreach(XmlNode child in node.ChildNodes) { IDataNode dataNode = Kernel.Instance.ParseNode(child, this); if(dataNode is ConfigurationNode) HandleConfiguration((ConfigurationNode)dataNode); else if(dataNode is ReferencePathNode) m_ReferencePaths.Add(dataNode); else if(dataNode is ReferenceNode) m_References.Add(dataNode); else if(dataNode is FilesNode) m_Files = (FilesNode)dataNode; } } finally { Kernel.Instance.CWDStack.Pop(); } } #endregion } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ #if FEATURE_CORE_DLR using MSAst = System.Linq.Expressions; #else using MSAst = Microsoft.Scripting.Ast; #endif using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using Microsoft.Scripting.Actions; using Microsoft.Scripting.Utils; using Microsoft.Scripting.Interpreter; using Microsoft.Scripting.Runtime; using IronPython.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; namespace IronPython.Compiler.Ast { public class CallExpression : Expression, IInstructionProvider { private readonly Expression _target; private readonly Arg[] _args; public CallExpression(Expression target, Arg[] args) { _target = target; _args = args; } public Expression Target { get { return _target; } } public IList<Arg> Args { get { return _args; } } public bool NeedsLocalsDictionary() { NameExpression nameExpr = _target as NameExpression; if (nameExpr == null) return false; if (_args.Length == 0) { if (nameExpr.Name == "locals") return true; if (nameExpr.Name == "vars") return true; if (nameExpr.Name == "dir") return true; return false; } else if (_args.Length == 1 && (nameExpr.Name == "dir" || nameExpr.Name == "vars")) { if (_args[0].Name == "*" || _args[0].Name == "**") { // could be splatting empty list or dict resulting in 0-param call which needs context return true; } } else if (_args.Length == 2 && (nameExpr.Name == "dir" || nameExpr.Name == "vars")) { if (_args[0].Name == "*" && _args[1].Name == "**") { // could be splatting empty list and dict resulting in 0-param call which needs context return true; } } else { if (nameExpr.Name == "eval") return true; if (nameExpr.Name == "execfile") return true; } return false; } public override MSAst.Expression Reduce() { return UnicodeCall() ?? NormalCall(_target); } private MSAst.Expression NormalCall(MSAst.Expression target) { MSAst.Expression[] values = new MSAst.Expression[_args.Length + 2]; Argument[] kinds = new Argument[_args.Length]; values[0] = Parent.LocalContext; values[1] = target; for (int i = 0; i < _args.Length; i++) { kinds[i] = _args[i].GetArgumentInfo(); values[i + 2] = _args[i].Expression; } return Parent.Invoke( new CallSignature(kinds), values ); } private static MSAst.MethodCallExpression _GetUnicode = Expression.Call(AstMethods.GetUnicodeFunction); private MSAst.Expression UnicodeCall() { if (_target is NameExpression && ((NameExpression)_target).Name == "unicode") { // NameExpressions are always typed to object Debug.Assert(_target.Type == typeof(object)); var tmpVar = Expression.Variable(typeof(object)); return Expression.Block( new[] { tmpVar }, Expression.Assign(tmpVar, _target), Expression.Condition( Expression.Call( AstMethods.IsUnicode, tmpVar ), NormalCall(_GetUnicode), NormalCall(tmpVar) ) ); } return null; } #region IInstructionProvider Members void IInstructionProvider.AddInstructions(LightCompiler compiler) { if (_target is NameExpression && ((NameExpression)_target).Name == "unicode") { compiler.Compile(Reduce()); return; } for (int i = 0; i < _args.Length; i++) { if (!_args[i].GetArgumentInfo().IsSimple) { compiler.Compile(Reduce()); return; } } switch (_args.Length) { #region Generated Python Call Expression Instruction Switch // *** BEGIN GENERATED CODE *** // generated by function: gen_call_expression_instruction_switch from: generate_calls.py case 0: compiler.Compile(Parent.LocalContext); compiler.Compile(_target); compiler.Instructions.Emit(new Invoke0Instruction(Parent.PyContext)); return; case 1: compiler.Compile(Parent.LocalContext); compiler.Compile(_target); compiler.Compile(_args[0].Expression); compiler.Instructions.Emit(new Invoke1Instruction(Parent.PyContext)); return; case 2: compiler.Compile(Parent.LocalContext); compiler.Compile(_target); compiler.Compile(_args[0].Expression); compiler.Compile(_args[1].Expression); compiler.Instructions.Emit(new Invoke2Instruction(Parent.PyContext)); return; case 3: compiler.Compile(Parent.LocalContext); compiler.Compile(_target); compiler.Compile(_args[0].Expression); compiler.Compile(_args[1].Expression); compiler.Compile(_args[2].Expression); compiler.Instructions.Emit(new Invoke3Instruction(Parent.PyContext)); return; case 4: compiler.Compile(Parent.LocalContext); compiler.Compile(_target); compiler.Compile(_args[0].Expression); compiler.Compile(_args[1].Expression); compiler.Compile(_args[2].Expression); compiler.Compile(_args[3].Expression); compiler.Instructions.Emit(new Invoke4Instruction(Parent.PyContext)); return; case 5: compiler.Compile(Parent.LocalContext); compiler.Compile(_target); compiler.Compile(_args[0].Expression); compiler.Compile(_args[1].Expression); compiler.Compile(_args[2].Expression); compiler.Compile(_args[3].Expression); compiler.Compile(_args[4].Expression); compiler.Instructions.Emit(new Invoke5Instruction(Parent.PyContext)); return; case 6: compiler.Compile(Parent.LocalContext); compiler.Compile(_target); compiler.Compile(_args[0].Expression); compiler.Compile(_args[1].Expression); compiler.Compile(_args[2].Expression); compiler.Compile(_args[3].Expression); compiler.Compile(_args[4].Expression); compiler.Compile(_args[5].Expression); compiler.Instructions.Emit(new Invoke6Instruction(Parent.PyContext)); return; // *** END GENERATED CODE *** #endregion } compiler.Compile(Reduce()); } #endregion abstract class InvokeInstruction : Instruction { public override int ProducedStack { get { return 1; } } public override string InstructionName { get { return "Python Invoke" + (ConsumedStack - 1); } } } #region Generated Python Call Expression Instructions // *** BEGIN GENERATED CODE *** // generated by function: gen_call_expression_instructions from: generate_calls.py class Invoke0Instruction : InvokeInstruction { private readonly CallSite<Func<CallSite, CodeContext, object, object>> _site; public Invoke0Instruction(PythonContext context) { _site = context.CallSite0; } public override int ConsumedStack { get { return 2; } } public override int Run(InterpretedFrame frame) { var target = frame.Pop(); frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target)); return +1; } } class Invoke1Instruction : InvokeInstruction { private readonly CallSite<Func<CallSite, CodeContext, object, object, object>> _site; public Invoke1Instruction(PythonContext context) { _site = context.CallSite1; } public override int ConsumedStack { get { return 3; } } public override int Run(InterpretedFrame frame) { var arg0 = frame.Pop(); var target = frame.Pop(); frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0)); return +1; } } class Invoke2Instruction : InvokeInstruction { private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object>> _site; public Invoke2Instruction(PythonContext context) { _site = context.CallSite2; } public override int ConsumedStack { get { return 4; } } public override int Run(InterpretedFrame frame) { var arg1 = frame.Pop(); var arg0 = frame.Pop(); var target = frame.Pop(); frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1)); return +1; } } class Invoke3Instruction : InvokeInstruction { private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object>> _site; public Invoke3Instruction(PythonContext context) { _site = context.CallSite3; } public override int ConsumedStack { get { return 5; } } public override int Run(InterpretedFrame frame) { var arg2 = frame.Pop(); var arg1 = frame.Pop(); var arg0 = frame.Pop(); var target = frame.Pop(); frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2)); return +1; } } class Invoke4Instruction : InvokeInstruction { private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object, object>> _site; public Invoke4Instruction(PythonContext context) { _site = context.CallSite4; } public override int ConsumedStack { get { return 6; } } public override int Run(InterpretedFrame frame) { var arg3 = frame.Pop(); var arg2 = frame.Pop(); var arg1 = frame.Pop(); var arg0 = frame.Pop(); var target = frame.Pop(); frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2, arg3)); return +1; } } class Invoke5Instruction : InvokeInstruction { private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object, object, object>> _site; public Invoke5Instruction(PythonContext context) { _site = context.CallSite5; } public override int ConsumedStack { get { return 7; } } public override int Run(InterpretedFrame frame) { var arg4 = frame.Pop(); var arg3 = frame.Pop(); var arg2 = frame.Pop(); var arg1 = frame.Pop(); var arg0 = frame.Pop(); var target = frame.Pop(); frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2, arg3, arg4)); return +1; } } class Invoke6Instruction : InvokeInstruction { private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object, object, object, object>> _site; public Invoke6Instruction(PythonContext context) { _site = context.CallSite6; } public override int ConsumedStack { get { return 8; } } public override int Run(InterpretedFrame frame) { var arg5 = frame.Pop(); var arg4 = frame.Pop(); var arg3 = frame.Pop(); var arg2 = frame.Pop(); var arg1 = frame.Pop(); var arg0 = frame.Pop(); var target = frame.Pop(); frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2, arg3, arg4, arg5)); return +1; } } // *** END GENERATED CODE *** #endregion internal override string CheckAssign() { return "can't assign to function call"; } internal override string CheckDelete() { return "can't delete function call"; } public override void Walk(PythonWalker walker) { if (walker.Walk(this)) { if (_target != null) { _target.Walk(walker); } if (_args != null) { foreach (Arg arg in _args) { arg.Walk(walker); } } } walker.PostWalk(this); } } }
using System.Linq; using System.Text.RegularExpressions; using System; using System.Collections.Generic; using System.Text; using Albatross.Expression.Exceptions; using Albatross.Expression.Tokens; using System.Diagnostics; using System.IO; using System.Reflection; using System.Xml; using Albatross.Expression.Operations; namespace Albatross.Expression { /// <summary> /// An immutable implementation of the <see cref="Albatross.Expression.IParser"/> interface. /// </summary> public class Parser : IParser { public IToken VariableToken() { return variableToken.Clone(); } public IStringLiteralToken StringLiteralToken() { return (IStringLiteralToken)stringLiteralToken.Clone(); } public IEnumerable<PrefixOperationToken> PrefixOperationTokens { get { return prefixOperationTokens; } } public IEnumerable<InfixOperationToken> InfixOperationTokens { get { return infixOperationTokens; } } List<PrefixOperationToken> prefixOperationTokens = new List<PrefixOperationToken>(); List<InfixOperationToken> infixOperationTokens = new List<InfixOperationToken>(); IToken variableToken; IStringLiteralToken stringLiteralToken; public Parser(IEnumerable<IToken> operations, IVariableToken variableToken, IStringLiteralToken stringLiteralToken) { prefixOperationTokens.Clear(); infixOperationTokens.Clear(); this.variableToken = variableToken; this.stringLiteralToken = stringLiteralToken; foreach (var item in operations) { Add(item); } } IParser Add(IToken token) { if (token is PrefixOperationToken) { prefixOperationTokens.Add((PrefixOperationToken)token); } else if (token is InfixOperationToken) { infixOperationTokens.Add((InfixOperationToken)token); } else { throw new NotSupportedException(); } return this; } //parse an expression and produce queue of tokens //the expression is parse from left to right public Queue<IToken> Tokenize(string expression) { if (string.IsNullOrEmpty(expression)) { throw new ArgumentException(); } Queue<IToken> tokens = new Queue<IToken>(); int start = 0, next; IToken last; IEnumerable<IToken> list; bool found; while (start < expression.Length) { found = false; last = tokens.Count == 0 ? null : tokens.Last(); list = null; if (last == null || last == ControlToken.Comma || (last is PrefixOperationToken && ((PrefixOperationToken)last).Symbolic) || last is InfixOperationToken) { list = new IToken[] { new BooleanLiteralToken(), VariableToken(), StringLiteralToken(), new NumericLiteralToken(), ControlToken.LeftParenthesis }.Union(prefixOperationTokens); } else if (last == ControlToken.LeftParenthesis) { list = new IToken[] { VariableToken(), StringLiteralToken(), new NumericLiteralToken(), ControlToken.LeftParenthesis, ControlToken.RightParenthesis }.Union(prefixOperationTokens); } else if (last == ControlToken.RightParenthesis || last is IOperandToken) { list = new IToken[] { ControlToken.Comma, ControlToken.RightParenthesis }.Union(infixOperationTokens); } else if (last is PrefixOperationToken && !((PrefixOperationToken)last).Symbolic) { list = new IToken[] { ControlToken.LeftParenthesis }; } Debug.Assert(list != null, "Forgot to check an previous operation"); foreach (IToken token in list) { if (token.Match(expression, start, out next)) { found = true; start = next; if (token is PrefixOperationToken || token is InfixOperationToken) { tokens.Enqueue(token.Clone()); } else { tokens.Enqueue(token); } break; } } if (found) { continue; } if (start < expression.Length) { if (expression.Substring(start).Trim().Length == 0) { break; } } throw new TokenParsingException("Unexpected token: " + expression.Substring(start)); } return tokens; } public bool IsValidExpression(string exp) { if (string.IsNullOrWhiteSpace(exp)) { return false; } else { try { Tokenize(exp); return true; } catch { return false; } } } public Stack<IToken> BuildStack(Queue<IToken> queue) { IToken token; Stack<IToken> postfix = new Stack<IToken>(); Stack<IToken> stack = new Stack<IToken>(); while (queue.Count > 0) { token = queue.Dequeue(); if (token == ControlToken.Comma) { //pop stack to postfix until we see left parenthesis while (stack.Count > 0 && stack.Peek() != ControlToken.LeftParenthesis) { postfix.Push(stack.Pop()); } if (stack.Count == 0) { throw new StackException("misplace comma or missing left parenthesis"); } else { continue; } } // if it is an operand, put it on the postfix stack if (token is IOperandToken){ postfix.Push(token); } if (token == ControlToken.LeftParenthesis) { stack.Push(token); } else if (token == ControlToken.RightParenthesis) { while (stack.Count > 0 && stack.Peek() != ControlToken.LeftParenthesis) { postfix.Push(stack.Pop()); } if (stack.Count == 0) { throw new StackException("missing left parenthesis"); } else { stack.Pop(); } }else if(token is PrefixOperationToken){ stack.Push(token); postfix.Push(ControlToken.FuncParamStart); }else if(token is InfixOperationToken){ if (stack.Count == 0 || stack.Peek() == ControlToken.LeftParenthesis) { stack.Push(token); } else { InfixOperationToken infix = (InfixOperationToken)token; while (stack.Count > 0 && stack.Peek() != ControlToken.LeftParenthesis && (stack.Peek() is PrefixOperationToken || stack.Peek() is InfixOperationToken && infix.Precedence <= ((InfixOperationToken)stack.Peek()).Precedence)) { postfix.Push(stack.Pop()); } stack.Push(token); } } } while (stack.Count > 0) { token = stack.Pop(); if (token == ControlToken.LeftParenthesis) { throw new TokenParsingException("unbalance paranthesis"); } else { postfix.Push(token); } } return postfix; } public IToken CreateTree(Stack<IToken> postfix) { postfix = Reverse(postfix); Stack<IToken> stack = new Stack<IToken>(); IToken token; while (postfix.Count > 0) { token = postfix.Pop(); if (token is IOperandToken || token == ControlToken.FuncParamStart){ stack.Push(token); }else if(token is InfixOperationToken){ InfixOperationToken infixOp = (InfixOperationToken)token; infixOp.Operand2 = stack.Pop(); infixOp.Operand1 = stack.Pop(); stack.Push(infixOp); } else if (token is PrefixOperationToken) { PrefixOperationToken prefixOp = (PrefixOperationToken)token; for (IToken t = stack.Pop(); t != ControlToken.FuncParamStart; t = stack.Pop()) { prefixOp.Operands.Insert(0, t); } stack.Push(prefixOp); } } return stack.Pop(); } public object Eval(IToken token, Func<string, object> context) { return token.EvalValue(context); } public string EvalText(IToken token, string format) { return token.EvalText(format); } public static Stack<T> Reverse<T>(Stack<T> src) { Stack<T> dst = new Stack<T>(); while (src.Count > 0) { dst.Push(src.Pop()); } return dst; } } }
// 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.IO; using System.IO.Compression; using System.Net.Test.Common; using System.Text.RegularExpressions; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.Http.Functional.Tests { using Configuration = System.Net.Test.Common.Configuration; public abstract class HttpClientHandler_Decompression_Test : HttpClientHandlerTestBase { public HttpClientHandler_Decompression_Test(ITestOutputHelper output) : base(output) { } public static IEnumerable<object[]> RemoteServersAndCompressionUris() { foreach (Configuration.Http.RemoteServer remoteServer in Configuration.Http.RemoteServers) { yield return new object[] { remoteServer, remoteServer.GZipUri }; yield return new object[] { remoteServer, remoteServer.DeflateUri }; } } public static IEnumerable<object[]> DecompressedResponse_MethodSpecified_DecompressedContentReturned_MemberData() { foreach (bool specifyAllMethods in new[] { false, true }) { yield return new object[] { "deflate", new Func<Stream, Stream>(s => new DeflateStream(s, CompressionLevel.Optimal, leaveOpen: true)), specifyAllMethods ? DecompressionMethods.Deflate : DecompressionMethods.All }; yield return new object[] { "gzip", new Func<Stream, Stream>(s => new GZipStream(s, CompressionLevel.Optimal, leaveOpen: true)), specifyAllMethods ? DecompressionMethods.GZip : DecompressionMethods.All }; yield return new object[] { "br", new Func<Stream, Stream>(s => new BrotliStream(s, CompressionLevel.Optimal, leaveOpen: true)), specifyAllMethods ? DecompressionMethods.Brotli : DecompressionMethods.All }; } } [Theory] [MemberData(nameof(DecompressedResponse_MethodSpecified_DecompressedContentReturned_MemberData))] public async Task DecompressedResponse_MethodSpecified_DecompressedContentReturned( string encodingName, Func<Stream, Stream> compress, DecompressionMethods methods) { if (!UseSocketsHttpHandler && encodingName == "br") { // Brotli only supported on SocketsHttpHandler. return; } var expectedContent = new byte[12345]; new Random(42).NextBytes(expectedContent); await LoopbackServer.CreateClientAndServerAsync(async uri => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.AutomaticDecompression = methods; Assert.Equal<byte>(expectedContent, await client.GetByteArrayAsync(uri)); } }, async server => { await server.AcceptConnectionAsync(async connection => { await connection.ReadRequestHeaderAsync(); await connection.Writer.WriteAsync($"HTTP/1.1 200 OK\r\nContent-Encoding: {encodingName}\r\n\r\n"); using (Stream compressedStream = compress(connection.Stream)) { await compressedStream.WriteAsync(expectedContent); } }); }); } public static IEnumerable<object[]> DecompressedResponse_MethodNotSpecified_OriginalContentReturned_MemberData() { yield return new object[] { "deflate", new Func<Stream, Stream>(s => new DeflateStream(s, CompressionLevel.Optimal, leaveOpen: true)), DecompressionMethods.None }; yield return new object[] { "gzip", new Func<Stream, Stream>(s => new GZipStream(s, CompressionLevel.Optimal, leaveOpen: true)), DecompressionMethods.Brotli }; yield return new object[] { "br", new Func<Stream, Stream>(s => new BrotliStream(s, CompressionLevel.Optimal, leaveOpen: true)), DecompressionMethods.Deflate | DecompressionMethods.GZip }; } [Theory] [MemberData(nameof(DecompressedResponse_MethodNotSpecified_OriginalContentReturned_MemberData))] public async Task DecompressedResponse_MethodNotSpecified_OriginalContentReturned( string encodingName, Func<Stream, Stream> compress, DecompressionMethods methods) { if (IsCurlHandler && encodingName == "br") { // 'Content-Encoding' response header with Brotli causes error // with some Linux distros of libcurl. return; } var expectedContent = new byte[12345]; new Random(42).NextBytes(expectedContent); var compressedContentStream = new MemoryStream(); using (Stream s = compress(compressedContentStream)) { await s.WriteAsync(expectedContent); } byte[] compressedContent = compressedContentStream.ToArray(); await LoopbackServer.CreateClientAndServerAsync(async uri => { using (HttpClientHandler handler = CreateHttpClientHandler()) using (HttpClient client = CreateHttpClient(handler)) { handler.AutomaticDecompression = methods; Assert.Equal<byte>(compressedContent, await client.GetByteArrayAsync(uri)); } }, async server => { await server.AcceptConnectionAsync(async connection => { await connection.ReadRequestHeaderAsync(); await connection.Writer.WriteAsync($"HTTP/1.1 200 OK\r\nContent-Encoding: {encodingName}\r\n\r\n"); await connection.Stream.WriteAsync(compressedContent); }); }); } [OuterLoop("Uses external servers")] [Theory, MemberData(nameof(RemoteServersAndCompressionUris))] public async Task GetAsync_SetAutomaticDecompression_ContentDecompressed(Configuration.Http.RemoteServer remoteServer, Uri uri) { HttpClientHandler handler = CreateHttpClientHandler(); handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer, handler)) { using (HttpResponseMessage response = await client.GetAsync(uri)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); string responseContent = await response.Content.ReadAsStringAsync(); _output.WriteLine(responseContent); TestHelper.VerifyResponseBody( responseContent, response.Content.Headers.ContentMD5, false, null); } } } [OuterLoop("Uses external server")] [Theory, MemberData(nameof(RemoteServersAndCompressionUris))] public async Task GetAsync_SetAutomaticDecompression_HeadersRemoved(Configuration.Http.RemoteServer remoteServer, Uri uri) { HttpClientHandler handler = CreateHttpClientHandler(); handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; using (HttpClient client = CreateHttpClientForRemoteServer(remoteServer, handler)) using (HttpResponseMessage response = await client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead)) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.False(response.Content.Headers.Contains("Content-Encoding"), "Content-Encoding unexpectedly found"); Assert.False(response.Content.Headers.Contains("Content-Length"), "Content-Length unexpectedly found"); } } [Theory] #if NETCOREAPP [InlineData(DecompressionMethods.Brotli, "br", "")] [InlineData(DecompressionMethods.Brotli, "br", "br")] [InlineData(DecompressionMethods.Brotli, "br", "gzip")] [InlineData(DecompressionMethods.Brotli, "br", "gzip, deflate")] #endif [InlineData(DecompressionMethods.GZip, "gzip", "")] [InlineData(DecompressionMethods.Deflate, "deflate", "")] [InlineData(DecompressionMethods.GZip | DecompressionMethods.Deflate, "gzip, deflate", "")] [InlineData(DecompressionMethods.GZip, "gzip", "gzip")] [InlineData(DecompressionMethods.Deflate, "deflate", "deflate")] [InlineData(DecompressionMethods.GZip, "gzip", "deflate")] [InlineData(DecompressionMethods.GZip, "gzip", "br")] [InlineData(DecompressionMethods.Deflate, "deflate", "gzip")] [InlineData(DecompressionMethods.Deflate, "deflate", "br")] [InlineData(DecompressionMethods.GZip | DecompressionMethods.Deflate, "gzip, deflate", "gzip, deflate")] public async Task GetAsync_SetAutomaticDecompression_AcceptEncodingHeaderSentWithNoDuplicates( DecompressionMethods methods, string encodings, string manualAcceptEncodingHeaderValues) { if (IsCurlHandler) { // Skip these tests on CurlHandler, dotnet/corefx #29905. return; } if (!UseSocketsHttpHandler && (encodings.Contains("br") || manualAcceptEncodingHeaderValues.Contains("br"))) { // Brotli encoding only supported on SocketsHttpHandler. return; } await LoopbackServer.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.AutomaticDecompression = methods; using (HttpClient client = CreateHttpClient(handler)) { if (!string.IsNullOrEmpty(manualAcceptEncodingHeaderValues)) { client.DefaultRequestHeaders.Add("Accept-Encoding", manualAcceptEncodingHeaderValues); } Task<HttpResponseMessage> clientTask = client.GetAsync(url); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); await TaskTimeoutExtensions.WhenAllOrAnyFailed(new Task[] { clientTask, serverTask }); List<string> requestLines = await serverTask; string requestLinesString = string.Join("\r\n", requestLines); _output.WriteLine(requestLinesString); Assert.InRange(Regex.Matches(requestLinesString, "Accept-Encoding").Count, 1, 1); Assert.InRange(Regex.Matches(requestLinesString, encodings).Count, 1, 1); if (!string.IsNullOrEmpty(manualAcceptEncodingHeaderValues)) { Assert.InRange(Regex.Matches(requestLinesString, manualAcceptEncodingHeaderValues).Count, 1, 1); } using (HttpResponseMessage response = await clientTask) { Assert.Equal(HttpStatusCode.OK, response.StatusCode); } } }); } } }
// // Copyright (c) 2004-2020 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.UnitTests.LayoutRenderers { using System; using System.Reflection; using NLog.Config; using NLog.LayoutRenderers; using Xunit; using Xunit.Abstractions; public class AssemblyVersionTests : NLogTestBase { private readonly ITestOutputHelper _testOutputHelper; #if !NETSTANDARD private static Lazy<Assembly> TestAssembly = new Lazy<Assembly>(() => GenerateTestAssembly()); #endif public AssemblyVersionTests(ITestOutputHelper testOutputHelper) { _testOutputHelper = testOutputHelper; } [Fact] public void EntryAssemblyVersionTest() { var assembly = Assembly.GetEntryAssembly(); var assemblyVersion = assembly == null ? $"Could not find value for entry assembly and version type {nameof(AssemblyVersionType.Assembly)}" : assembly.GetName().Version.ToString(); AssertLayoutRendererOutput("${assembly-version}", assemblyVersion); } [Fact] public void AssemblyNameVersionTest() { AssertLayoutRendererOutput("${assembly-version:NLogAutoLoadExtension}", "2.0.0.0"); } [Fact] public void AssemblyNameVersionTypeTest() { AssertLayoutRendererOutput("${assembly-version:name=NLogAutoLoadExtension:type=assembly}", "2.0.0.0"); AssertLayoutRendererOutput("${assembly-version:name=NLogAutoLoadExtension:type=file}", "2.0.0.1"); AssertLayoutRendererOutput("${assembly-version:name=NLogAutoLoadExtension:type=informational}", "2.0.0.2"); } [Theory] [InlineData("Major", "2")] [InlineData("Major.Minor", "2.0")] [InlineData("Major.Minor.Build", "2.0.0")] [InlineData("Major.Minor.Build.Revision", "2.0.0.0")] [InlineData("Revision.Build.Minor.Major", "0.0.0.2")] [InlineData("Major.MINOR.Build.Revision", "2.0.0.0")] [InlineData("Major.Minor.BuILD.Revision", "2.0.0.0")] [InlineData("MAJOR.Minor.BUILD.Revision", "2.0.0.0")] public void AssemblyVersionFormatTest(string format, string expected) { AssertLayoutRendererOutput($"${{assembly-version:name=NLogAutoLoadExtension:format={format}}}", expected); } #if !NETSTANDARD private const string AssemblyVersionTest = "1.2.3.4"; private const string AssemblyFileVersionTest = "1.1.1.2"; private const string AssemblyInformationalVersionTest = "Version 1"; [Theory] [InlineData(AssemblyVersionType.Assembly, AssemblyVersionTest)] [InlineData(AssemblyVersionType.File, AssemblyFileVersionTest)] [InlineData(AssemblyVersionType.Informational, AssemblyInformationalVersionTest)] public void AssemblyVersionTypeTest(AssemblyVersionType type, string expected) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message:withException=true}|${assembly-version:type=" + type.ToString().ToLower() + @"}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"); var logger = LogManager.GetLogger("SomeLogger"); var compiledAssembly = TestAssembly.Value; var testLoggerType = compiledAssembly.GetType("LogTester.LoggerTest"); var logMethod = testLoggerType.GetMethod("TestLog"); var testLoggerInstance = Activator.CreateInstance(testLoggerType); logMethod.Invoke(testLoggerInstance, new object[] { logger, compiledAssembly }); var lastMessage = GetDebugLastMessage("debug"); var messageParts = lastMessage.Split('|'); var logMessage = messageParts[0]; var logVersion = messageParts[1]; if (logMessage.StartsWith("Skip:")) { _testOutputHelper.WriteLine(logMessage); } else { Assert.StartsWith("Pass:", logMessage); Assert.Equal(expected, logVersion); } } [Theory] [InlineData(AssemblyVersionType.Assembly, "Major", "1")] [InlineData(AssemblyVersionType.Assembly, "Major.Minor", "1.2")] [InlineData(AssemblyVersionType.Assembly, "Major.Minor.Build", "1.2.3")] [InlineData(AssemblyVersionType.Assembly, "Major.Minor.Build.Revision", "1.2.3.4")] [InlineData(AssemblyVersionType.Assembly, "Revision.Build.Minor.Major", "4.3.2.1")] [InlineData(AssemblyVersionType.Assembly, "Build.Major", "3.1")] [InlineData(AssemblyVersionType.File, "Major", "1")] [InlineData(AssemblyVersionType.File, "Major.Minor", "1.1")] [InlineData(AssemblyVersionType.File, "Major.Minor.Build", "1.1.1")] [InlineData(AssemblyVersionType.File, "Major.Minor.Build.Revision", "1.1.1.2")] [InlineData(AssemblyVersionType.File, "Revision.Build.Minor.Major", "2.1.1.1")] [InlineData(AssemblyVersionType.File, "Build.Major", "1.1")] [InlineData(AssemblyVersionType.Informational, "Major", "Version 1")] [InlineData(AssemblyVersionType.Informational, "Major.Minor", "Version 1.0")] [InlineData(AssemblyVersionType.Informational, "Major.Minor.Build", "Version 1.0.0")] [InlineData(AssemblyVersionType.Informational, "Major.Minor.Build.Revision", "Version 1")] [InlineData(AssemblyVersionType.Informational, "Revision.Build.Minor.Major", "0.0.0.Version 1")] [InlineData(AssemblyVersionType.Informational, "Build.Major", "0.Version 1")] public void AssemblyVersionFormatAndTypeTest(AssemblyVersionType type, string format, string expected) { LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message:withException=true}|${assembly-version:type=" + type.ToString().ToLower() + @":format=" + format + @"}' /></targets> <rules><logger name='*' minlevel='Debug' writeTo='debug' /></rules> </nlog>"); var logger = LogManager.GetLogger("SomeLogger"); var compiledAssembly = TestAssembly.Value; var testLoggerType = compiledAssembly.GetType("LogTester.LoggerTest"); var logMethod = testLoggerType.GetMethod("TestLog"); var testLoggerInstance = Activator.CreateInstance(testLoggerType); logMethod.Invoke(testLoggerInstance, new object[] { logger, compiledAssembly }); var lastMessage = GetDebugLastMessage("debug"); var messageParts = lastMessage.Split('|'); var logMessage = messageParts[0]; var logVersion = messageParts[1]; if (logMessage.StartsWith("Skip:")) { _testOutputHelper.WriteLine(logMessage); } else { Assert.StartsWith("Pass:", logMessage); Assert.Equal(expected, logVersion); } } private static Assembly GenerateTestAssembly() { const string code = @" using System; using System.Reflection; [assembly: AssemblyVersion(""" + AssemblyVersionTest + @""")] [assembly: AssemblyFileVersion(""" + AssemblyFileVersionTest + @""")] [assembly: AssemblyInformationalVersion(""" + AssemblyInformationalVersionTest + @""")] namespace LogTester { public class LoggerTest { public void TestLog(NLog.Logger logger, Assembly assembly) { if (System.Reflection.Assembly.GetEntryAssembly() == null) { // In some unit testing scenarios we cannot find the entry assembly // So we attempt to force this to be set, which can also still fail // This is not expected to be necessary in Visual Studio // See https://github.com/Microsoft/vstest/issues/649 try { SetEntryAssembly(assembly); } catch (InvalidOperationException ioex) { logger.Debug(ioex, ""Skip: No entry assembly""); return; } } logger.Debug(""Pass: Test fully executed""); } private static void SetEntryAssembly(Assembly assembly) { var manager = new AppDomainManager(); var domain = AppDomain.CurrentDomain; if (domain == null) throw new InvalidOperationException(""Current app domain is null""); var entryAssemblyField = manager.GetType().GetField(""m_entryAssembly"", BindingFlags.Instance | BindingFlags.NonPublic); if (entryAssemblyField == null) throw new InvalidOperationException(""Unable to find field m_entryAssembly""); entryAssemblyField.SetValue(manager, assembly); var domainManagerField = domain.GetType().GetField(""_domainManager"", BindingFlags.Instance | BindingFlags.NonPublic); if (domainManagerField == null) throw new InvalidOperationException(""Unable to find field _domainManager""); domainManagerField.SetValue(domain, manager); } } }"; var provider = new Microsoft.CSharp.CSharpCodeProvider(); var parameters = new System.CodeDom.Compiler.CompilerParameters { GenerateInMemory = true, GenerateExecutable = false, ReferencedAssemblies = {"NLog.dll"} }; System.CodeDom.Compiler.CompilerResults results = provider.CompileAssemblyFromSource(parameters, code); var compiledAssembly = results.CompiledAssembly; return compiledAssembly; } #endif } }
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; // ERROR: Not supported in C#: OptionDeclaration using VB = Microsoft.VisualBasic; namespace _4PosBackOffice.NET { internal partial class frmExportProductPerfomace : System.Windows.Forms.Form { List<RadioButton> optType = new List<RadioButton>(); private void loadLanguage() { //NOTE: Caption has a spelling mistake!!! modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2469; //Export Product Performance if (modRecordSet.rsLang.RecordCount){this.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;this.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2471; //Export Options|Checked if (modRecordSet.rsLang.RecordCount){_Frame1_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_Frame1_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2152; //Normal Item Listing|Checked if (modRecordSet.rsLang.RecordCount){_optType_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_optType_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2153; //Items Per Group|Checked if (modRecordSet.rsLang.RecordCount){_optType_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_optType_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2154; //Group Totals|Checked if (modRecordSet.rsLang.RecordCount){_optType_2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_optType_2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1173; //Group On|Checked if (modRecordSet.rsLang.RecordCount){_lbl_3.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_3.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2477; //Export Sort Options|Checked if (modRecordSet.rsLang.RecordCount){_Frame1_1.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_Frame1_1.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2158; //Sort Field|Checked if (modRecordSet.rsLang.RecordCount){_lbl_0.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_0.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2159; //Sort Order|Checked if (modRecordSet.rsLang.RecordCount){_lbl_2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_lbl_2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2480; //Export Filter|Checked if (modRecordSet.rsLang.RecordCount){_Frame1_2.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;_Frame1_2.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1006; //Filter|Checked if (modRecordSet.rsLang.RecordCount){cmdGroup.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdGroup.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 1004; //Exit|Checked if (modRecordSet.rsLang.RecordCount){cmdExit.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdExit.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsLang.filter = "LanguageLayoutLnk_LanguageID=" + 2483; //Export Now|Checked if (modRecordSet.rsLang.RecordCount){cmdLoad.Text = modRecordSet.rsLang.Fields("LanguageLayoutLnk_Description").Value;cmdLoad.RightToLeft = modRecordSet.rsLang.Fields("LanguageLayoutLnk_RightTL").Value;} modRecordSet.rsHelp.filter = "Help_Section=0 AND Help_Form='" + this.Name + "'"; //UPGRADE_ISSUE: Form property frmExportProductPerfomace.ToolTip1 was not upgraded. Click for more: 'ms-help://MS.VSCC.v90/dv_commoner/local/redirect.htm?keyword="CC4C7EC0-C903-48FC-ACCC-81861D12DA4A"' if (modRecordSet.rsHelp.RecordCount) this.ToolTip1 = modRecordSet.rsHelp.Fields("Help_ContextID").Value; } private void cmdExit_Click(System.Object eventSender, System.EventArgs eventArgs) { this.Close(); } private void cmdGroup_Click(System.Object eventSender, System.EventArgs eventArgs) { ADODB.Recordset rs = default(ADODB.Recordset); int lID = 0; modReport.cnnDBreport.Execute("DELETE aftDataItem.* From aftDataItem WHERE (((aftDataItem.ftDataItem_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("DELETE aftData.* From aftData WHERE (((aftData.ftData_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("INSERT INTO aftData ( ftData_PersonID, ftData_FieldName, ftData_SQL, ftData_Heading ) SELECT LinkData.LinkData_PersonID, LinkData.LinkData_FieldName, LinkData.LinkData_SQL, LinkData.LinkData_Heading From LinkData WHERE (((LinkData.LinkData_LinkID)=2) AND ((LinkData.LinkData_SectionID)=1) AND ((LinkData.LinkData_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("INSERT INTO aftDataItem ( ftDataItem_PersonID, ftDataItem_FieldName, ftDataItem_ID ) SELECT LinkDataItem.LinkDataItem_PersonID, LinkDataItem.LinkDataItem_FieldName, LinkDataItem.LinkDataItem_ID From LinkDataItem WHERE (((LinkDataItem.LinkDataItem_LinkID)=2) AND ((LinkDataItem.LinkDataItem_SectionID)=1) AND ((LinkDataItem.LinkDataItem_PersonID)=" + modRecordSet.gPersonID + "));"); My.MyProject.Forms.frmFilter.Close(); My.MyProject.Forms.frmFilter.buildCriteria(ref "Sale"); My.MyProject.Forms.frmFilter.loadFilter(ref "Sale"); My.MyProject.Forms.frmFilter.buildCriteria(ref "Sale"); modReport.cnnDBreport.Execute("UPDATE Link SET Link.Link_Name = '" + Strings.Replace(My.MyProject.Forms.frmFilter.gHeading, "'", "''") + "', Link.Link_SQL = '" + Strings.Replace(My.MyProject.Forms.frmFilter.gCriteria, "'", "''") + "' WHERE (((Link.LinkID)=2) AND ((Link.Link_SectionID)=1) AND ((Link.Link_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("DELETE LinkDataItem.* From LinkDataItem WHERE (((LinkDataItem.LinkDataItem_LinkID)=2) AND ((LinkDataItem.LinkDataItem_SectionID)=1) AND ((LinkDataItem.LinkDataItem_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("DELETE LinkData.* From LinkData WHERE (((LinkData.LinkData_LinkID)=2) AND ((LinkData.LinkData_SectionID)=1) AND ((LinkData.LinkData_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("INSERT INTO LinkData ( LinkData_LinkID, LinkData_SectionID, LinkData_PersonID, LinkData_FieldName, LinkData_SQL, LinkData_Heading ) SELECT 2, 1, aftData.ftData_PersonID, aftData.ftData_FieldName, aftData.ftData_SQL, aftData.ftData_Heading From aftData WHERE (((aftData.ftData_PersonID)=" + modRecordSet.gPersonID + "));"); modReport.cnnDBreport.Execute("INSERT INTO LinkDataItem ( LinkDataItem_LinkID, LinkDataItem_SectionID, LinkDataItem_PersonID, LinkDataItem_FieldName, LinkDataItem_ID ) SELECT 2, 1, aftDataItem.ftDataItem_PersonID, aftDataItem.ftDataItem_FieldName, aftDataItem.ftDataItem_ID From aftDataItem WHERE (((aftDataItem.ftDataItem_PersonID)=" + modRecordSet.gPersonID + "));"); lblGroup.Text = My.MyProject.Forms.frmFilter.gHeading; } private void setup() { ADODB.Recordset rs = default(ADODB.Recordset); rs = modReport.getRSreport(ref "SELECT Link.Link_PersonID From Link WHERE (((Link.Link_PersonID)=" + modRecordSet.gPersonID + "));"); if (rs.BOF | rs.EOF) { modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 1, 1, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 2, 1, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 1, 2, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 2, 2, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 1, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 2, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 3, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 4, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 5, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 6, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 7, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 8, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 9, 3, " + modRecordSet.gPersonID + ", '', '';"); modReport.cnnDBreport.Execute("INSERT INTO link ( LinkID, Link_SectionID, Link_PersonID, Link_Name, Link_SQL ) SELECT 10, 3, " + modRecordSet.gPersonID + ", '', '';"); } rs = modReport.getRSreport(ref "SELECT Link.Link_Name From Link WHERE (((Link.LinkID)=2) AND ((Link.Link_SectionID)=1) AND ((Link.Link_PersonID)=" + modRecordSet.gPersonID + "));"); lblGroup.Text = rs.Fields("Link_Name").Value; } private void cmdLoad_Click(System.Object eventSender, System.EventArgs eventArgs) { string dbText = null; string sql = null; string stFileName = null; string lOrder = null; ADODB.Recordset rs = default(ADODB.Recordset); ADODB.Recordset rsData = default(ADODB.Recordset); //Exporting file... string lne = null; short n = 0; Scripting.FileSystemObject fso = new Scripting.FileSystemObject(); switch (this.cmbSortField.SelectedIndex) { case 0: lOrder = "StockItem_Name"; break; case 1: lOrder = "[exclusiveSum]-[depositSum]-[listCostSum]"; break; case 2: lOrder = "[exclusiveSum]-[depositSum]"; break; case 3: lOrder = "[exclusiveSum]-[depositSum]-[listCostSum]"; break; case 4: lOrder = "IIf([exclusiveSum]=0,0,([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum])"; break; case 5: lOrder = "StockList.quantitySum"; break; } if (this.cmbSort.SelectedIndex) lOrder = lOrder + " DESC"; lOrder = " ORDER BY " + lOrder; System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor; rs = modReport.getRSreport(ref "SELECT * FROM Link Where LinkID=2 AND Link_SectionID=1"); if (_optType_0.Checked) { sql = "SELECT aStockItem.StockItemID, aStockItem.StockItem_Name, StockList.inclusiveSum AS inclusive, StockList.exclusiveSum AS exclusive, [exclusiveSum]-[depositSum] AS price, [exclusiveSum]-[depositSum] AS content, [exclusiveSum]-[depositSum]-[listCostSum] AS listProfit, [exclusiveSum]-[depositSum]-[actualCostSum] AS actualProfit, StockList.quantitySum AS quantity, StockList.listCostSum AS listCost, StockList.actualCostSum AS actualCost, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0) AS gpActual, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0) AS gpList, aStockGroup.StockGroup_Name AS department FROM StockList INNER JOIN (aStockItem INNER JOIN aStockGroup ON aStockItem.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem.StockItemID "; } else { sql = "SELECT aStockItem.StockItemID, aStockItem.StockItem_Name, StockList.inclusiveSum AS inclusive, StockList.exclusiveSum AS exclusive, [exclusiveSum]-[depositSum] AS price, [exclusiveSum]-[depositSum] AS content, [exclusiveSum]-[depositSum]-[listCostSum] AS listProfit, [exclusiveSum]-[depositSum]-[actualCostSum] AS actualProfit, StockList.quantitySum AS quantity, StockList.listCostSum AS listCost, StockList.actualCostSum AS actualCost, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[actualCostSum])/[exclusiveSum]*100,0) AS gpActual, IIf([exclusiveSum],([exclusiveSum]-[depositSum]-[listCostSum])/[exclusiveSum]*100,0) AS gpList, aStockGroup.StockGroup_Name AS department FROM StockList INNER JOIN (aStockItem INNER JOIN aStockGroup ON aStockItem.StockItem_StockGroupID = aStockGroup.StockGroupID) ON StockList.SaleItem_StockItemID = aStockItem.StockItemID "; switch (this.cmbGroup.SelectedIndex) { case 0: sql = Strings.Replace(sql, "StockGroup", "PricingGroup"); break; //Report.txtTitle.SetText "Product Performance - by Pricing Group" case 1: break; //Report.txtTitle.SetText "Product Performance - by Stock Group" case 2: sql = Strings.Replace(sql, "StockGroup", "Supplier"); sql = Strings.Replace(sql, "aSupplier", "Supplier"); break; //Report.txtTitle.SetText "Product Performance - by Supplier" } } if (string.IsNullOrEmpty(rs.Fields("Link_SQL").Value)) { } else { sql = sql + rs.Fields("Link_SQL").Value; } sql = sql + lOrder; string ptbl = null; string t_day = null; string t_Mon = null; if (Strings.Len(Strings.Trim(Conversion.Str(DateAndTime.Day(DateAndTime.Today)))) == 1) t_day = "0" + Strings.Trim(Convert.ToString(DateAndTime.Day(DateAndTime.Today))); else t_day = Convert.ToString(DateAndTime.Day(DateAndTime.Today)); if (Strings.Len(Strings.Trim(Conversion.Str(DateAndTime.Month(DateAndTime.Today)))) == 1) t_Mon = "0" + Strings.Trim(Convert.ToString(DateAndTime.Month(DateAndTime.Today))); else t_Mon = Conversion.Str(DateAndTime.Month(DateAndTime.Today)); ptbl = modRecordSet.serverPath + "4POSProd" + Strings.Trim(Convert.ToString(DateAndTime.Year(DateAndTime.Today))) + Strings.Trim(t_Mon) + Strings.Trim(t_day); if (fso.FileExists(ptbl + ".csv")) fso.DeleteFile((ptbl + ".csv")); FileSystem.FileOpen(1, ptbl + ".csv", OpenMode.Output); //Open serverPath & "ProductPerformace.csv" For Output As #1 rs = modReport.getRSreport(ref sql); //Write Out CSV if (rs.BOF | rs.EOF) { Interaction.MsgBox("There are no recods to export, Try Changing Day End date range", MsgBoxStyle.ApplicationModal + MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "Export Product Performance"); System.Windows.Forms.Cursor.Current = Cursors.Default; return; } else { //First line as column headings for (n = 0; n <= rs.Fields.Count - 1; n++) { lne = lne + Strings.Chr(34) + rs.Fields(n).Name + Strings.Chr(34) + ","; } FileSystem.PrintLine(1, lne); while (!rs.EOF) { lne = ""; for (n = 0; n <= rs.Fields.Count - 1; n++) { if (rs.Fields(n).Type == dbText) { lne = lne + Strings.Chr(34) + rs.Fields(n).Value + Strings.Chr(34) + ","; } else { lne = lne + rs.Fields(n).Value + ","; } } lne = Strings.Left(lne, Strings.Len(lne) - 1); //get rid of last comma FileSystem.PrintLine(1, lne); rs.moveNext(); } FileSystem.FileClose(1); Interaction.MsgBox("Product performance CSV File, was successfully exported to : " + ptbl + ".csv"); } System.Windows.Forms.Cursor.Current = Cursors.Default; } private void frmExportProductPerfomace_KeyPress(System.Object eventSender, System.Windows.Forms.KeyPressEventArgs eventArgs) { short KeyAscii = Strings.Asc(eventArgs.KeyChar); if (KeyAscii == 27) { KeyAscii = 0; this.Close(); } eventArgs.KeyChar = Strings.Chr(KeyAscii); if (KeyAscii == 0) { eventArgs.Handled = true; } } private void frmExportProductPerfomace_Load(System.Object eventSender, System.EventArgs eventArgs) { optType.AddRange(new RadioButton[] { _optType_0, _optType_1, _optType_2 }); loadLanguage(); setup(); this.cmbGroup.SelectedIndex = 0; this.cmbSort.SelectedIndex = 0; this.cmbSortField.SelectedIndex = 0; } //Handles optType.CheckedChanged private void optType_CheckedChanged(System.Object eventSender, System.EventArgs eventArgs) { if (eventSender.Checked) { RadioButton opt = new RadioButton(); opt = (RadioButton)eventSender; int Index = GetIndex.GetIndexer(ref opt, ref optType); if (Index) { cmbGroup.Enabled = true; } else { cmbGroup.Enabled = false; } this.chkPageBreak.Enabled = (Index == 1); } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Channels; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Hosting; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.Runtime.Messaging; using Orleans.Serialization; namespace Orleans.Messaging { // <summary> // This class is used on the client only. // It provides the client counterpart to the Gateway and GatewayAcceptor classes on the silo side. // // There is one ClientMessageCenter instance per OutsideRuntimeClient. There can be multiple ClientMessageCenter instances // in a single process, but because RuntimeClient keeps a static pointer to a single OutsideRuntimeClient instance, this is not // generally done in practice. // // Each ClientMessageCenter keeps a collection of GatewayConnection instances. Each of these represents a bidirectional connection // to a single gateway endpoint. Requests are assigned to a specific connection based on the target grain ID, so that requests to // the same grain will go to the same gateway, in sending order. To do this efficiently and scalably, we bucket grains together // based on their hash code mod a reasonably large number (currently 8192). // // When the first message is sent to a bucket, we assign a gateway to that bucket, selecting in round-robin fashion from the known // gateways. If this is the first message to be sent to the gateway, we will create a new connection for it and assign the bucket to // the new connection. Either way, all messages to grains in that bucket will be sent to the assigned connection as long as the // connection is live. // // Connections stay live as long as possible. If a socket error or other communications error occurs, then the client will try to // reconnect twice before giving up on the gateway. If the connection cannot be re-established, then the gateway is deemed (temporarily) // dead, and any buckets assigned to the connection are unassigned (so that the next message sent will cause a new gateway to be selected). // There is no assumption that this death is permanent; the system will try to reuse the gateway every 5 minutes. // // The list of known gateways is managed by the GatewayManager class. See comments there for details. // </summary> internal class ClientMessageCenter : IMessageCenter, IDisposable { private readonly object grainBucketUpdateLock = new object(); internal readonly SerializationManager SerializationManager; internal static readonly TimeSpan MINIMUM_INTERCONNECT_DELAY = TimeSpan.FromMilliseconds(100); // wait one tenth of a second between connect attempts internal const int CONNECT_RETRY_COUNT = 2; // Retry twice before giving up on a gateway server internal ClientGrainId ClientId { get; private set; } public IRuntimeClient RuntimeClient { get; } internal bool Running { get; private set; } private readonly GatewayManager gatewayManager; private Action<Message> messageHandler; private int numMessages; // The grainBuckets array is used to select the connection to use when sending an ordered message to a grain. // Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket. // Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used // if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is // false, then a new gateway is selected using the gateway manager, and a new connection established if necessary. private readonly WeakReference<Connection>[] grainBuckets; private readonly ILogger logger; public SiloAddress MyAddress { get; private set; } private readonly QueueTrackingStatistic queueTracking; private int numberOfConnectedGateways = 0; private readonly MessageFactory messageFactory; private readonly IClusterConnectionStatusListener connectionStatusListener; private readonly ConnectionManager connectionManager; private StatisticsLevel statisticsLevel; public ClientMessageCenter( IOptions<ClientMessagingOptions> clientMessagingOptions, IPAddress localAddress, int gen, ClientGrainId clientId, SerializationManager serializationManager, IRuntimeClient runtimeClient, MessageFactory messageFactory, IClusterConnectionStatusListener connectionStatusListener, ILoggerFactory loggerFactory, IOptions<StatisticsOptions> statisticsOptions, ConnectionManager connectionManager, GatewayManager gatewayManager) { this.connectionManager = connectionManager; this.SerializationManager = serializationManager; MyAddress = SiloAddress.New(new IPEndPoint(localAddress, 0), gen); ClientId = clientId; this.RuntimeClient = runtimeClient; this.messageFactory = messageFactory; this.connectionStatusListener = connectionStatusListener; Running = false; this.gatewayManager = gatewayManager; numMessages = 0; this.grainBuckets = new WeakReference<Connection>[clientMessagingOptions.Value.ClientSenderBuckets]; logger = loggerFactory.CreateLogger<ClientMessageCenter>(); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Proxy grain client constructed"); IntValueStatistic.FindOrCreate( StatisticNames.CLIENT_CONNECTED_GATEWAY_COUNT, () => { return connectionManager.ConnectionCount; }); statisticsLevel = statisticsOptions.Value.CollectionLevel; if (statisticsLevel.CollectQueueStats()) { queueTracking = new QueueTrackingStatistic("ClientReceiver", statisticsOptions); } } public void Start() { Running = true; if (this.statisticsLevel.CollectQueueStats()) { queueTracking.OnStartExecution(); } if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Proxy grain client started"); } public void Stop() { Running = false; if (this.statisticsLevel.CollectQueueStats()) { queueTracking.OnStopExecution(); } gatewayManager.Stop(); } public void OnReceivedMessage(Message message) { var handler = this.messageHandler; if (handler is null) { ThrowNullMessageHandler(); } else { handler(message); } static void ThrowNullMessageHandler() => throw new InvalidOperationException("MessageCenter does not have a message handler set"); } public void SendMessage(Message msg) { if (!Running) { this.logger.Error(ErrorCode.ProxyClient_MsgCtrNotRunning, $"Ignoring {msg} because the Client message center is not running"); return; } var connectionTask = this.GetGatewayConnection(msg); if (connectionTask.IsCompletedSuccessfully) { var connection = connectionTask.Result; if (connection is null) return; connection.Send(msg); if (this.logger.IsEnabled(LogLevel.Trace)) { this.logger.Trace( ErrorCode.ProxyClient_QueueRequest, "Sending message {0} via gateway {1}", msg, connection.RemoteEndPoint); } } else { _ = SendAsync(connectionTask, msg); async Task SendAsync(ValueTask<Connection> task, Message message) { try { var connection = await task; // If the connection returned is null then the message was already rejected due to a failure. if (connection is null) return; connection.Send(message); if (this.logger.IsEnabled(LogLevel.Trace)) { this.logger.Trace( ErrorCode.ProxyClient_QueueRequest, "Sending message {0} via gateway {1}", message, connection.RemoteEndPoint); } } catch (Exception exception) { if (message.RetryCount < MessagingOptions.DEFAULT_MAX_MESSAGE_SEND_RETRIES) { ++message.RetryCount; _ = Task.Factory.StartNew( state => this.SendMessage((Message)state), message, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { this.RejectMessage(message, $"Unable to send message due to exception {exception}", exception); } } } } } private ValueTask<Connection> GetGatewayConnection(Message msg) { // If there's a specific gateway specified, use it if (msg.TargetSilo != null && gatewayManager.GetLiveGateways().Contains(msg.TargetSilo)) { var siloAddress = SiloAddress.New(msg.TargetSilo.Endpoint, 0); var connectionTask = this.connectionManager.GetConnection(siloAddress); if (connectionTask.IsCompletedSuccessfully) return connectionTask; return ConnectAsync(msg.TargetSilo, connectionTask, msg, directGatewayMessage: true); } // For untargeted messages to system targets, and for unordered messages, pick a next connection in round robin fashion. if (msg.TargetGrain.IsSystemTarget() || msg.IsUnordered) { // Get the cached list of live gateways. // Pick a next gateway name in a round robin fashion. // See if we have a live connection to it. // If Yes, use it. // If not, create a new GatewayConnection and start it. // If start fails, we will mark this connection as dead and remove it from the GetCachedLiveGatewayNames. int msgNumber = Interlocked.Increment(ref numMessages); var gatewayAddresses = gatewayManager.GetLiveGateways(); int numGateways = gatewayAddresses.Count; if (numGateways == 0) { RejectMessage(msg, "No gateways available"); logger.Warn(ErrorCode.ProxyClient_CannotSend, "Unable to send message {0}; gateway manager state is {1}", msg, gatewayManager); return new ValueTask<Connection>(default(Connection)); } var gatewayAddress = gatewayAddresses[msgNumber % numGateways]; var connectionTask = this.connectionManager.GetConnection(gatewayAddress); if (connectionTask.IsCompletedSuccessfully) return connectionTask; return ConnectAsync(gatewayAddress, connectionTask, msg, directGatewayMessage: false); } // Otherwise, use the buckets to ensure ordering. var index = GetHashCodeModulo(msg.TargetGrain.GetHashCode(), (uint)grainBuckets.Length); // Repeated from above, at the declaration of the grainBuckets array: // Requests are bucketed by GrainID, so that all requests to a grain get routed through the same bucket. // Each bucket holds a (possibly null) weak reference to a GatewayConnection object. That connection instance is used // if the WeakReference is non-null, is alive, and points to a live gateway connection. If any of these conditions is // false, then a new gateway is selected using the gateway manager, and a new connection established if necessary. WeakReference<Connection> weakRef = grainBuckets[index]; if (weakRef != null && weakRef.TryGetTarget(out var existingConnection) && existingConnection.IsValid) { return new ValueTask<Connection>(existingConnection); } var addr = gatewayManager.GetLiveGateway(); if (addr == null) { RejectMessage(msg, "No gateways available"); logger.Warn(ErrorCode.ProxyClient_CannotSend_NoGateway, "Unable to send message {0}; gateway manager state is {1}", msg, gatewayManager); return new ValueTask<Connection>(default(Connection)); } if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.ProxyClient_NewBucketIndex, "Starting new bucket index {0} for ordered messages to grain {1}", index, msg.TargetGrain); if (logger.IsEnabled(LogLevel.Debug)) logger.Debug( ErrorCode.ProxyClient_CreatedGatewayToGrain, "Creating gateway to {0} for message to grain {1}, bucket {2}, grain id hash code {3}X", addr, msg.TargetGrain, index, msg.TargetGrain.GetHashCode().ToString("x")); var gatewayConnection = this.connectionManager.GetConnection(addr); if (gatewayConnection.IsCompletedSuccessfully) { this.UpdateBucket(index, gatewayConnection.Result); return gatewayConnection; } return AddToBucketAsync(index, gatewayConnection, addr); async ValueTask<Connection> AddToBucketAsync( uint bucketIndex, ValueTask<Connection> connectionTask, SiloAddress gatewayAddress) { try { var connection = await connectionTask.ConfigureAwait(false); this.UpdateBucket(bucketIndex, connection); return connection; } catch { this.gatewayManager.MarkAsDead(gatewayAddress); this.UpdateBucket(bucketIndex, null); throw; } } async ValueTask<Connection> ConnectAsync( SiloAddress gateway, ValueTask<Connection> connectionTask, Message message, bool directGatewayMessage) { Connection result = default; try { return result = await connectionTask; } catch (Exception exception) when (directGatewayMessage) { RejectMessage(message, string.Format("Target silo {0} is unavailable", message.TargetSilo), exception); return null; } finally { if (result is null) this.gatewayManager.MarkAsDead(gateway); } } static uint GetHashCodeModulo(int key, uint umod) { int mod = (int)umod; key = ((key % mod) + mod) % mod; // key should be positive now. So assert with checked. return checked((uint)key); } } private void UpdateBucket(uint index, Connection connection) { lock (this.grainBucketUpdateLock) { var value = this.grainBuckets[index] ?? new WeakReference<Connection>(connection); value.SetTarget(connection); this.grainBuckets[index] = value; } } public void RegisterLocalMessageHandler(Action<Message> handler) { this.messageHandler = handler; } public void RejectMessage(Message msg, string reason, Exception exc = null) { if (!Running) return; if (msg.Direction != Message.Directions.Request) { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.ProxyClient_DroppingMsg, "Dropping message: {0}. Reason = {1}", msg, reason); } else { if (logger.IsEnabled(LogLevel.Debug)) logger.Debug(ErrorCode.ProxyClient_RejectingMsg, "Rejecting message: {0}. Reason = {1}", msg, reason); MessagingStatisticsGroup.OnRejectedMessage(msg); var error = this.messageFactory.CreateRejectionResponse(msg, Message.RejectionTypes.Unrecoverable, reason, exc); OnReceivedMessage(error); } } public int SendQueueLength { get { return 0; } } private SiloAddress GetLiveGatewaySiloAddress() { var gateway = gatewayManager.GetLiveGateway(); if (gateway == null) { throw new OrleansException("Not connected to a gateway"); } return gateway; } internal void OnGatewayConnectionOpen() { int newCount = Interlocked.Increment(ref numberOfConnectedGateways); this.connectionStatusListener.NotifyGatewayCountChanged(newCount, newCount - 1); } internal void OnGatewayConnectionClosed() { var gatewayCount = Interlocked.Decrement(ref numberOfConnectedGateways); if (gatewayCount == 0) { this.connectionStatusListener.NotifyClusterConnectionLost(); } this.connectionStatusListener.NotifyGatewayCountChanged(gatewayCount, gatewayCount + 1); } public void Dispose() { gatewayManager.Dispose(); } } }
using System; using System.Linq; using System.Collections.Generic; using Qwack.Transport.BasicTypes; namespace Qwack.Dates { /// <summary> /// Business date extension methods /// </summary> public static class DateExtensions { private static readonly double _ticksFraction360 = 1.0 / (TimeSpan.TicksPerDay * 360.0); private static readonly double _ticksFraction365 = 1.0 / (TimeSpan.TicksPerDay * 365.0); public static readonly string[] Months = { "JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC" }; public static readonly string[] FutureMonths = { "F", "G", "H", "J", "K", "M", "N", "Q", "U", "V", "X", "Z" }; /// <summary> /// Gets the next IMM date for a given input date. Returns 3rd Wednesday in March, June, September or December. /// If an IMM date is given as the input, the following IMM date will be returned. /// </summary> /// <param name="input">The reference date</param> /// <returns></returns> public static DateTime GetNextImmDate(this DateTime input) { var m = input.Month; var y = input.Year; //handle case of date before 3rd weds in IMM month if (m % 3 == 0 && input < ThirdWednesday(input)) { return ThirdWednesday(input); } m = m - m % 3 + 3; //roll to next IMM month if (m <= 12) return ThirdWednesday(new DateTime(y, m, 1)); m -= 12; y++; return ThirdWednesday(new DateTime(y, m, 1)); } /// <summary> /// Gets the previous IMM date for a given input date. Returns 3rd Wednesday in March, June, September or December. /// If an IMM date is given as the input, the previous IMM date will be returned. /// </summary> /// <param name="input">The reference date</param> /// <returns></returns> public static DateTime GetPrevImmDate(this DateTime input) { var m = input.Month; var y = input.Year; //handle case of date after 3rd weds in IMM month if (m % 3 == 0 && input > ThirdWednesday(input)) return ThirdWednesday(input); m -= (m % 3 == 0 ? 3 : m % 3); //roll to next IMM month if (m >= 1) return ThirdWednesday(new DateTime(y, m, 1)); m += 12; y--; return ThirdWednesday(new DateTime(y, m, 1)); } /// <summary> /// Gets the next occurence of a specific weekday from the input date /// If the input date is the target day of the week, the following occurence is returned /// </summary> /// <param name="input">The reference date</param> /// <returns></returns> public static DateTime GetNextWeekday(this DateTime input, DayOfWeek weekDay) { var d = input.DayOfWeek; if(d<weekDay) { var deltaD = weekDay - d; return input.AddDays(deltaD); } else { var deltaD = 7 - (int)d + (int)weekDay; return input.AddDays(deltaD); } } /// <summary> /// Returns a list of business dates according to a specified calendar which are contained within two given dates. /// Start and end dates are treated as inclusive /// </summary> /// <param name="startDateInc"></param> /// <param name="endDateInc"></param> /// <param name="calendars"></param> /// <returns></returns> public static List<DateTime> BusinessDaysInPeriod(this DateTime startDateInc, DateTime endDateInc, Calendar calendars) { if (endDateInc < startDateInc) { throw new ArgumentException(nameof(endDateInc), "End date is before the start date"); } var o = new List<DateTime>((int)(endDateInc - startDateInc).TotalDays); var date = startDateInc.IfHolidayRollForward(calendars); while (date <= endDateInc) { o.Add(date); date = date.AddPeriod(RollType.F, calendars, 1.Bd()); } return o; } /// <summary> /// Returns a list of calendar dates which are contained within two given dates. /// Start and end dates are treated as inclusive /// </summary> /// <param name="startDateInc"></param> /// <param name="endDateInc"></param> /// <returns></returns> public static List<DateTime> CalendarDaysInPeriod(this DateTime startDateInc, DateTime endDateInc) { if (endDateInc < startDateInc) { throw new ArgumentException(nameof(endDateInc), "End date is before the start date"); } var o = new List<DateTime>((int)(endDateInc - startDateInc).TotalDays); var date = startDateInc; while (date <= endDateInc) { o.Add(date); date = date.AddDays(1); } return o; } /// <summary> /// Returns a list of friday dates according to a specified calendar which are contained within two given dates. /// If a friday is a holiday, the preceeding good business day is returned /// Start and end dates are treated as inclusive /// </summary> /// <param name="startDateInc"></param> /// <param name="endDateInc"></param> /// <param name="calendars"></param> /// <returns></returns> public static List<DateTime> FridaysInPeriod(this DateTime startDateInc, DateTime endDateInc, Calendar calendars) { if (endDateInc < startDateInc) { throw new ArgumentException(nameof(endDateInc), "End date is before the start date"); } var o = new List<DateTime>((int)(endDateInc - startDateInc).TotalDays); var date = startDateInc; while (date <= endDateInc) { if (date.DayOfWeek == DayOfWeek.Friday) { o.Add(date.IfHolidayRoll(RollType.P, calendars)); } date = date.AddPeriod(RollType.None, null, 1.Day()); } return o; } /// <summary> /// Calculates a year fraction from a day count method and two dates /// Start date is inclusive, end date exclusive /// </summary> /// <param name="startDate">Start Date (inclusive)</param> /// <param name="endDate">End Date (exclusive)</param> /// <param name="basis">DayCountBasis enum</param> /// <param name="ignoreTimeComponent">Ignore the time component of the DateTime inputs - defaults to true</param> /// <param name="calendar">Optional calendar object, required only for methods involving business days</param> /// <returns></returns> public static double CalculateYearFraction(this DateTime startDate, DateTime endDate, DayCountBasis basis, bool ignoreTimeComponent = true, Calendar calendar = null) { if (ignoreTimeComponent) { startDate = startDate.Date; endDate = endDate.Date; } switch (basis) { case DayCountBasis.Act_360: return (endDate.Ticks - startDate.Ticks) * _ticksFraction360; case DayCountBasis.Act_365F: return (endDate.Ticks - startDate.Ticks) * _ticksFraction365; case DayCountBasis.Act_Act_ISDA: case DayCountBasis.Act_Act: if (endDate.Year == startDate.Year) { //simple case var eoY = new DateTime(endDate.Year, 12, 31); return (endDate - startDate).TotalDays / eoY.DayOfYear; } else { double nIntermediateYears = endDate.Year - startDate.Year - 1; var eoYe = new DateTime(endDate.Year, 12, 31); var e = endDate.DayOfYear / (double)eoYe.DayOfYear; var eoYs = new DateTime(startDate.Year, 12, 31); var s = (eoYs - startDate).TotalDays / eoYs.DayOfYear; return s + nIntermediateYears + e; } case DayCountBasis._30_360: double ydiff = endDate.Year - startDate.Year; double mdiff = endDate.Month - startDate.Month; double ddiff = endDate.Day - startDate.Day; return (ydiff * 360 + mdiff * 30 + ddiff) / 360; case DayCountBasis.ThirtyE360: double d1E = Math.Min(startDate.Day, 30); double d2E = Math.Min(endDate.Day, 30); double ydiffE = endDate.Year - startDate.Year; double mdiffE = endDate.Month - startDate.Month; var ddiffE = d2E - d1E; return (ydiffE * 360 + mdiffE * 30 + ddiffE) / 360; case DayCountBasis.Bus252: return startDate.BusinessDaysInPeriod(endDate.AddDays(-1), calendar).Count / 252.0; case DayCountBasis.Unity: return 1.0; } return -1; } /// <summary> /// Calculates a year fraction from a day count method and two dates /// Start date is inclusive, end date exclusive /// </summary> /// <param name="startDate">Start Date (inclusive)</param> /// <param name="endDate">End Date (exclusive)</param> /// <param name="basis">DayCountBasis enum</param> /// <returns></returns> public static double CalculateYearFraction(this DayCountBasis basis, DateTime startDate, DateTime endDate) => startDate.CalculateYearFraction(endDate, basis); /// <summary> /// Adds a year fraction to a date to return an end date /// </summary> /// <param name="startDate">Start Date</param> /// <param name="yearFraction">Year fraction in format consistent with basis parameter</param> /// <param name="basis">DayCountBasis enum</param> /// <returns></returns> public static DateTime AddYearFraction(this DateTime startDate, double yearFraction, DayCountBasis basis, bool ignoreTimeComponent=true) { var o = new DateTime(); switch (basis) { case DayCountBasis.Act_360: o = new DateTime((long)(startDate.Ticks + yearFraction / _ticksFraction360)); break; case DayCountBasis.Act_365F: o = new DateTime((long)(startDate.Ticks + yearFraction / _ticksFraction365)); break; } if (ignoreTimeComponent) o = o.Date; return o; } /// <summary> /// Returns first business day (according to specified calendar) of month in which the input date falls /// </summary> /// <param name="input">Input date</param> /// <param name="calendar">Calendar</param> /// <returns></returns> public static DateTime FirstBusinessDayOfMonth(this DateTime input, Calendar calendar) { var returnDate = input.FirstDayOfMonth(); if (calendar != null) { returnDate = returnDate.IfHolidayRollForward(calendar); } return returnDate; } /// <summary> /// Returns first calendar day of the months in which the input date falls /// </summary> /// <param name="input">Input date</param> /// <returns></returns> public static DateTime FirstDayOfMonth(this DateTime input) => new(input.Year, input.Month, 1); /// <summary> /// Returns last business day, according to the specified calendar, of the month in which the input date falls /// </summary> /// <param name="input">Input date</param> /// <param name="calendar">Calendar</param> /// <returns></returns> public static DateTime LastBusinessDayOfMonth(this DateTime input, Calendar calendar) { var d = input.Date.AddMonths(1).FirstDayOfMonth(); return SubtractPeriod(d, RollType.P, calendar, 1.Bd()); } /// <summary> /// Returns the third wednesday of the month in which the input date falls /// </summary> /// <param name="date">Input date</param> /// <returns></returns> public static DateTime ThirdWednesday(this DateTime date) => date.NthSpecificWeekDay(DayOfWeek.Wednesday, 3); /// <summary> /// Returns the Nth instance of a specific week day in the month in which the input date falls /// E.g. NthSpecificWeekDay(date,DayOfWeek.Wednesday, 3) would return the third wednesday of the month in which the input date falls /// </summary> /// <param name="date">Input date</param> /// <param name="dayofWeek">DayOfWeek enum</param> /// <param name="number">N</param> /// <returns></returns> public static DateTime NthSpecificWeekDay(this DateTime date, DayOfWeek dayofWeek, int number) { //Get the first day of the month var firstDate = new DateTime(date.Year, date.Month, 1); //Get the current day 0=sunday var currentDay = (int)firstDate.DayOfWeek; var targetDow = (int)dayofWeek; int daysToAdd; if (currentDay == targetDow) return firstDate.AddDays((number - 1) * 7); if (currentDay < targetDow) { daysToAdd = targetDow - currentDay; } else { daysToAdd = 7 + targetDow - currentDay; } return firstDate.AddDays(daysToAdd).AddDays((number - 1) * 7); } /// <summary> /// Returns the Nth instance of a specific week day (from the end of the month) in the month in which the input date falls /// E.g. NthSpecificWeekDay(date,DayOfWeek.Wednesday, 2) would return the 2nd last wednesday of the month in which the input date falls /// </summary> /// <param name="date">Input date</param> /// <param name="dayofWeek">DayOfWeek enum</param> /// <param name="number">N</param> /// <returns></returns> public static DateTime NthLastSpecificWeekDay(this DateTime date, DayOfWeek dayofWeek, int number) { //Get the first day of the month var lastDate = LastDayOfMonth(date); //Get the current day 0=sunday var currentDay = (int)lastDate.DayOfWeek; var targetDow = (int)dayofWeek; int daysToAdd; if (currentDay == targetDow) return lastDate.AddDays(-(number - 1) * 7); if (currentDay > targetDow) { daysToAdd = currentDay - targetDow; } else { daysToAdd = 7 + currentDay - targetDow; } return lastDate.AddDays(-daysToAdd).AddDays(-(number - 1) * 7); } /// <summary> /// Returns the last calendar day of the month in which the input date falls /// </summary> /// <param name="input">Input date</param> /// <returns></returns> public static DateTime LastDayOfMonth(this DateTime input) { if (input.Month != 12) { return new DateTime(input.Year, input.Month + 1, 1).AddDays(-1); } else { return new DateTime(input.Year + 1, 1, 1).AddDays(-1); } } /// <summary> /// Returns the input date, adjusted by rolling forward if the input date falls on a holiday according to the specified calendar /// </summary> /// <param name="input">Input date</param> /// <param name="calendar">Calendar</param> /// <returns></returns> public static DateTime IfHolidayRollForward(this DateTime input, Calendar calendar) { if (calendar == null) return input; input = input.Date; while (calendar.IsHoliday(input)) { input = input.AddDays(1); } return input; } /// <summary> /// Returns the input date, adjusted by rolling backwards if the input date falls on a holiday according to the specified calendar /// </summary> /// <param name="input">Input date</param> /// <param name="calendar">Calendar</param> /// <returns></returns> public static DateTime IfHolidayRollBack(this DateTime input, Calendar calendar) { if (calendar == null) return input; while (calendar.IsHoliday(input)) { input = input.AddDays(-1); } return input; } /// <summary> /// Returns the input date, adjusted by rolling if the input date falls on a holiday according to the specified calendar. /// The type of roll is specfied in the input. /// </summary> /// <param name="date">Input date</param> /// <param name="rollType">RollType enum</param> /// <param name="calendar">Calendar</param> /// <returns></returns> public static DateTime IfHolidayRoll(this DateTime date, RollType rollType, Calendar calendar) { if (calendar == null) return date; date = date.Date; DateTime d, d1, d2; double distFwd, distBack; switch (rollType) { case RollType.F: return date.IfHolidayRollForward(calendar); case RollType.MF: default: d = date.IfHolidayRollForward(calendar); if (d.Month == date.Month) { return d; } else { return date.IfHolidayRollBack(calendar); } case RollType.P: return date.IfHolidayRollBack(calendar); case RollType.MP: d = date.IfHolidayRollBack(calendar); if (d.Month == date.Month) { return d; } else { return date.IfHolidayRollForward(calendar); } case RollType.NearestFollow: d1 = date.IfHolidayRollForward(calendar); d2 = date.IfHolidayRollBack(calendar); distFwd = (d1 - date).TotalDays; distBack = (date - d2).TotalDays; if (distBack < distFwd) { return d2; } else { return d1; } case RollType.NearestPrev: d1 = date.IfHolidayRollForward(calendar); d2 = date.IfHolidayRollBack(calendar); distFwd = (d1 - date).TotalDays; distBack = (date - d2).TotalDays; if (distFwd < distBack) { return d1; } else { return d2; } case RollType.LME: d1 = date.IfHolidayRollForward(calendar); if (d1.Month != date.Month) { return date.IfHolidayRollBack(calendar); } d2 = date.IfHolidayRollBack(calendar); if (d2.Month != date.Month) { return d1; } distFwd = (d1 - date).TotalDays; distBack = (date - d2).TotalDays; if (distBack < distFwd) { return d2; } else { return d1; } case RollType.None: return date; } } /// <summary> /// Returns a date equal to the input date plus the specified period, adjusted for holidays /// </summary> /// <param name="date">Input date</param> /// <param name="rollType">RollType enum</param> /// <param name="calendar">Calendar</param> /// <param name="datePeriod">Period to add in the form of a Frequency object</param> /// <returns></returns> public static DateTime AddPeriod(this DateTime date, RollType rollType, Calendar calendar, Frequency datePeriod) { if (calendar == null && datePeriod.PeriodType==DatePeriodType.B) return date; date = date.Date; if (datePeriod.PeriodCount == 0) { return IfHolidayRoll(date, rollType, calendar); } if (datePeriod.PeriodType == DatePeriodType.B) { if (datePeriod.PeriodCount < 0) //actually a subtract { return date.SubtractPeriod(rollType, calendar, new Frequency(-datePeriod.PeriodCount, datePeriod.PeriodType)); } //Business day jumping so we need to do something different var d = date; for (var i = 0; i < datePeriod.PeriodCount; i++) { d = d.AddDays(1); d = IfHolidayRoll(d, rollType, calendar); } return d; } var dt = datePeriod.PeriodType switch { DatePeriodType.D => date.AddDays(datePeriod.PeriodCount), DatePeriodType.M => date.AddMonths(datePeriod.PeriodCount), DatePeriodType.W => date.AddDays(datePeriod.PeriodCount * 7), _ => date.AddYears(datePeriod.PeriodCount), }; if ((rollType == RollType.MF_LIBOR) && (date == date.LastBusinessDayOfMonth(calendar))) { dt = date.LastBusinessDayOfMonth(calendar); } if (rollType == RollType.ShortFLongMF) { if (datePeriod.PeriodType == DatePeriodType.B || datePeriod.PeriodType == DatePeriodType.D || datePeriod.PeriodType == DatePeriodType.W) return IfHolidayRoll(dt, RollType.F, calendar); else return IfHolidayRoll(dt, RollType.MF, calendar); } return IfHolidayRoll(dt, rollType, calendar); } public static DateTime[] AddPeriod(this DateTime[] dates, RollType rollType, Calendar calendar, Frequency datePeriod) => dates.Select(d => d.AddPeriod(rollType, calendar, datePeriod)).ToArray(); /// <summary> /// Returns a date equal to the input date minus the specified period, adjusted for holidays /// </summary> /// <param name="date">Input date</param> /// <param name="rollType">RollType enum</param> /// <param name="calendar">Calendar</param> /// <param name="datePeriod">Period to add in the form of a Frequency object</param> /// <returns></returns> public static DateTime SubtractPeriod(this DateTime date, RollType rollType, Calendar calendar, Frequency datePeriod) { date = date.Date; if (datePeriod.PeriodCount == 0) { return IfHolidayRoll(date, rollType, calendar); } if (datePeriod.PeriodType == DatePeriodType.B) { //Business day jumping so we need to do something different var d = date; for (var i = 0; i < datePeriod.PeriodCount; i++) { d = d.AddDays(-1); d = IfHolidayRoll(d, rollType, calendar); } return d; } return AddPeriod(date, rollType, calendar, new Frequency(0 - datePeriod.PeriodCount, datePeriod.PeriodType)); } /// <summary> /// Returns the lesser of two DateTime objects /// </summary> /// <param name="dateA"></param> /// <param name="dateB"></param> /// <returns></returns> public static DateTime Min(this DateTime dateA, DateTime dateB) => dateA < dateB ? dateA : dateB; /// <summary> /// Returns the greater of two DateTime objects /// </summary> /// <param name="dateA"></param> /// <param name="dateB"></param> /// <returns></returns> public static DateTime Max(this DateTime dateA, DateTime dateB) => dateA > dateB ? dateA : dateB; /// <summary> /// Returns the average of two DateTime objects /// </summary> /// <param name="dateA"></param> /// <param name="dateB"></param> /// <returns></returns> public static DateTime Average(this DateTime dateA, DateTime dateB) => new((dateB.Ticks + dateA.Ticks) / 2); /// <summary> /// Returns the start and end dates for a specified period string /// e.g. CAL19, Q120, CAL-20, JAN-22, BALMO /// </summary> /// <param name="dateA"></param> /// <param name="dateB"></param> /// <returns></returns> public static (DateTime Start, DateTime End) ParsePeriod(this string period) { switch (period.ToUpper()) { case string p when int.TryParse(p, out var year): return (Start: new DateTime(year, 1, 1), End: new DateTime(year, 12, 31)); case string p when p.StartsWith("BALM"): return (Start: DateTime.Today, End: (DateTime.Today).LastDayOfMonth()); case string p when p.StartsWith("CAL"): if (!int.TryParse(p.Substring(3).Trim('-',' '), out var y)) throw new Exception($"Could not parse year from {period}"); return (Start: new DateTime(y + 2000, 1, 1), End: new DateTime(y + 2000, 12, 31)); case string p when p.StartsWith("+M") && p.Split('M').Length == 2 && int.TryParse(p.Split('M')[1], out var mm): var dm = DateTime.Today.AddMonths(mm); return (Start: new DateTime(dm.Year, dm.Month, 1), End: new DateTime(dm.Year, dm.Month, 1).LastDayOfMonth()); case string p when p.Length == 2 && int.TryParse(p.Substring(1,1), out var yr) && FutureMonths.Contains(p.Substring(0,1)): //X8 var m1 = Array.IndexOf(FutureMonths, p.Substring(0, 1)) +1; return (Start: new DateTime(2010 + yr, m1, 1), End: (new DateTime(2010 + yr, m1, 1)).LastDayOfMonth()); ; case string p when p.Length == 3 && int.TryParse(p.Substring(1, 2), out var yr) && FutureMonths.Contains(p.Substring(0, 1)): //X18 var m2 = Array.IndexOf(FutureMonths, p.Substring(0, 1)) + 1; return (Start: new DateTime(2000 + yr, m2, 1), End: (new DateTime(2000 + yr, m2, 1)).LastDayOfMonth()); ; case string p when p.StartsWith("Q"): if (!int.TryParse(p.Substring(1, 1), out var q)) throw new Exception($"Could not parse quarter from {period}"); if (!int.TryParse(p.Substring(2).Trim('-',' '), out var yq)) throw new Exception($"Could not parse year from {period}"); return (Start: new DateTime(2000 + yq, 3 * (q - 1) + 1, 1), End: (new DateTime(2000 + yq, 3 * q, 1)).LastDayOfMonth()); case string p when p.Length > 2 && p.StartsWith("H"): if (!int.TryParse(p.Substring(1, 1), out var h)) throw new Exception($"Could not parse half-year from {period}"); if (!int.TryParse(p.Substring(2).Trim('-',' '), out var yh)) throw new Exception($"Could not parse year from {period}"); return (Start: new DateTime(2000 + yh, (h-1)*6+1, 1), End: (new DateTime(2000 + yh, h * 6, 1)).LastDayOfMonth()); case string p when p.Length > 2 && Months.Any(x => x == p.Substring(0, 3)): if (!int.TryParse(p.Substring(3).Trim('-', ' '), out var ym)) throw new Exception($"Could not parse year from {period}"); var m = Months.ToList().IndexOf(p.Substring(0, 3))+1; return (Start: new DateTime(ym + 2000, m, 1), End: (new DateTime(ym + 2000, m, 1)).LastDayOfMonth()); default: throw new Exception($"Could not parse period {period}"); } } public static (DateTime Start, DateTime End, bool valid) TryParsePeriod(this string period) { switch (period.ToUpper()) { case string p when int.TryParse(p, out var year): return (Start: new DateTime(year, 1, 1), End: new DateTime(year, 12, 31), valid: true); case string p when p.StartsWith("BALM"): return (Start: DateTime.Today, End: (DateTime.Today).LastDayOfMonth(), valid:true); case string p when p.StartsWith("CAL"): if (!int.TryParse(p.Substring(3).Trim('-', ' '), out var y)) return (Start: default(DateTime), End: default(DateTime), valid: false); return (Start: new DateTime(y + 2000, 1, 1), End: new DateTime(y + 2000, 12, 31), valid:true); case string p when p.StartsWith("M") && p.Split('M').Length == 2 && int.TryParse(p.Split('M')[1], out var mm): var dm = DateTime.Today.AddMonths(mm); return (Start: new DateTime(dm.Year, dm.Month, 1), End: new DateTime(dm.Year, dm.Month, 1).LastDayOfMonth(), valid: true); case string p when p.Length == 2 && int.TryParse(p.Substring(1, 1), out var yr) && FutureMonths.Contains(p.Substring(0, 1)): //X8 var m1 = Array.IndexOf(FutureMonths, p.Substring(0, 1)) + 1; return (Start: new DateTime(2010 + yr, m1, 1), End: (new DateTime(2010 + yr, m1, 1)).LastDayOfMonth(), valid:true); ; case string p when p.Length == 3 && int.TryParse(p.Substring(1, 2), out var yr) && FutureMonths.Contains(p.Substring(0, 1)): //X18 var m2 = Array.IndexOf(FutureMonths, p.Substring(0, 1)) + 1; return (Start: new DateTime(2000 + yr, m2, 1), End: (new DateTime(2000 + yr, m2, 1)).LastDayOfMonth(), valid:true); ; case string p when p.StartsWith("Q") && p.Length > 2: if (!int.TryParse(p.Substring(1, 1), out var q)) return (Start: default(DateTime), End: default(DateTime), valid: false); if (!int.TryParse(p.Substring(2).Trim('-', ' '), out var yq)) return (Start: default(DateTime), End: default(DateTime), valid: false); return (Start: new DateTime(2000 + yq, 3 * (q - 1) + 1, 1), End: (new DateTime(2000 + yq, 3 * q, 1)).LastDayOfMonth(), valid:true); case string p when p.Length > 2 && p.StartsWith("H"): if (!int.TryParse(p.Substring(1, 1), out var h)) return (Start: default(DateTime), End: default(DateTime), valid: false); if (!int.TryParse(p.Substring(2).Trim('-', ' '), out var yh)) return (Start: default(DateTime), End: default(DateTime), valid: false); return (Start: new DateTime(2000 + yh, (h - 1) * 6 + 1, 1), End: (new DateTime(2000 + yh, h * 6, 1)).LastDayOfMonth(), valid: true); case string p when p.Length>2 && Months.Any(x => x == p.Substring(0, 3)): if (!int.TryParse(p.Substring(3).Trim('-', ' '), out var ym)) return (Start: default(DateTime), End: default(DateTime), valid: false); var m = Months.ToList().IndexOf(p.Substring(0, 3)) + 1; return (Start: new DateTime(ym + 2000, m, 1), End: (new DateTime(ym + 2000, m, 1)).LastDayOfMonth(), valid:true); default: return (Start: default(DateTime), End: default(DateTime), valid: false); } } public static int SingleDigitYear(int fullYear) { var floor = (int)Math.Floor(fullYear / 10.0) * 10; return fullYear - floor; } public static int DoubleDigitYear(int fullYear) { var floor = (int)Math.Floor(fullYear / 100.0) * 100; return fullYear - floor; } /// <summary> /// Returns spot date for a given val date /// e.g. for USD/ZAR, calendar would be for ZAR and otherCal would be for USD /// </summary> /// <param name="valDate"></param> /// <param name="spotLag"></param> /// <param name="calendar"></param> /// <param name="otherCal"></param> /// <returns></returns> public static DateTime SpotDate(this DateTime valDate, Frequency spotLag, Calendar calendar, Calendar otherCal) { var d = valDate.AddPeriod(RollType.F, calendar, spotLag); d = d.IfHolidayRollForward(otherCal); return d; } //http://www.henk-reints.nl/easter/index.htm?frame=easteralg2.htm public static DateTime EasterGauss(int year) { var P = year / 100; var Q = (3 * P + 3) / 4; var R = (8 * P + 13) / 25; var M = (15 + Q - R) % 30; var N = (4 + Q) % 7; var a = year % 19; var b = year % 4; var c = year % 7; var d = (19 * a + M) % 30; var e = (2 * b + 4 * c + 6 * d + N) % 7; var f = 22 + d + e; if (f == 57 || (f == 56 && e == 6 && a > 10)) f -= 7; var ge = (new DateTime(year, 3, 1)).AddDays(f-1); return ge; } /// <summary> /// Returns the dates of westerns easter for a given year /// </summary> /// <param name="dateInYear"></param> /// <returns> /// GoodFriday, EasterMonday /// </returns> public static (DateTime GoodFriday, DateTime EasterMonday) Easter(this DateTime dateInYear) { var easterSunday = EasterGauss(dateInYear.Year); return (easterSunday.AddDays(-2), easterSunday.AddDays(1)); } public static DateTime[] HolidaysForRange(this Calendar calendar, DateTime start, DateTime end) { var o = new List<DateTime>(); var d = start; while(d<=end) { if (calendar.IsHoliday(d)) o.Add(d); if (d.DayOfWeek == DayOfWeek.Friday) d = d.AddDays(3); else d = d.AddDays(1); } return o.ToArray(); } public static DateTime[] GenerateDateSchedule(this DatePeriodType period, DateTime start, DateTime end) { var o = new List<DateTime>(); var d = start; while (d < end) { o.Add(d); d = d.AddPeriod(RollType.F, null, new Frequency(1, period)); } o.Add(end); return o.ToArray(); } public static int DiffinMonths(this DateTime start, DateTime end) => (end.Year * 12 + end.Month) - (start.Year * 12 + start.Month); } }
namespace DennyTalk { partial class DialogUserControl { /// <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 Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DialogUserControl)); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle3 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle4 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle5 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle6 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle7 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle8 = new System.Windows.Forms.DataGridViewCellStyle(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.panel1 = new DennyTalk.CustomPanel(); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.ColumnAvatar = new System.Windows.Forms.DataGridViewImageColumn(); this.Column1 = new DennyTalk.DataGridViewDialogMessageColumn(); this.ColumnTime = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewDialogMessageColumn1 = new DennyTalk.DataGridViewDialogMessageColumn(); this.dataGridViewDialogMessageColumn2 = new DennyTalk.DataGridViewDialogMessageColumn(); this.dataGridViewDialogMessageColumn3 = new DennyTalk.DataGridViewDialogMessageColumn(); this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.contextMenuStrip1.SuspendLayout(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // contextMenuStrip1 // this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.copyToolStripMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(145, 26); // // copyToolStripMenuItem // this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; this.copyToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.C))); this.copyToolStripMenuItem.Size = new System.Drawing.Size(144, 22); this.copyToolStripMenuItem.Text = "Copy"; this.copyToolStripMenuItem.Click += new System.EventHandler(this.copyToolStripMenuItem_Click); // // panel1 // this.panel1.AutoScroll = true; this.panel1.BackColor = System.Drawing.SystemColors.Window; this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.panel1.Controls.Add(this.dataGridView1); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(2, 2); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(607, 360); this.panel1.TabIndex = 1; // // dataGridView1 // this.dataGridView1.AllowUserToAddRows = false; this.dataGridView1.AllowUserToDeleteRows = false; this.dataGridView1.AllowUserToResizeColumns = false; this.dataGridView1.AllowUserToResizeRows = false; this.dataGridView1.BackgroundColor = System.Drawing.SystemColors.Window; this.dataGridView1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.dataGridView1.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.dataGridView1.ClipboardCopyMode = System.Windows.Forms.DataGridViewClipboardCopyMode.Disable; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.ColumnHeadersVisible = false; this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.ColumnAvatar, this.Column1, this.ColumnTime}); this.dataGridView1.ContextMenuStrip = this.contextMenuStrip1; this.dataGridView1.EditMode = System.Windows.Forms.DataGridViewEditMode.EditProgrammatically; this.dataGridView1.GridColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); this.dataGridView1.Location = new System.Drawing.Point(0, 0); this.dataGridView1.MultiSelect = false; this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.RowHeadersVisible = false; this.dataGridView1.RowTemplate.DefaultCellStyle.BackColor = System.Drawing.Color.White; this.dataGridView1.RowTemplate.DefaultCellStyle.ForeColor = System.Drawing.Color.Black; this.dataGridView1.RowTemplate.DefaultCellStyle.SelectionBackColor = System.Drawing.SystemColors.Highlight; this.dataGridView1.RowTemplate.DefaultCellStyle.SelectionForeColor = System.Drawing.Color.Black; this.dataGridView1.RowTemplate.DefaultCellStyle.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridView1.RowTemplate.Height = 54; this.dataGridView1.ScrollBars = System.Windows.Forms.ScrollBars.None; this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridView1.Size = new System.Drawing.Size(456, 71); this.dataGridView1.TabIndex = 0; this.dataGridView1.CellBeginEdit += new System.Windows.Forms.DataGridViewCellCancelEventHandler(this.dataGridView1_CellBeginEdit); this.dataGridView1.CellEndEdit += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellEndEdit); this.dataGridView1.CellMouseDoubleClick += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridView1_CellMouseDoubleClick); this.dataGridView1.CellMouseDown += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.dataGridView1_CellMouseDown); this.dataGridView1.SizeChanged += new System.EventHandler(this.dataGridView1_SizeChanged); // // ColumnAvatar // this.ColumnAvatar.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; this.ColumnAvatar.DataPropertyName = "SenderAvatar"; dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopCenter; dataGridViewCellStyle1.NullValue = ((object)(resources.GetObject("dataGridViewCellStyle1.NullValue"))); this.ColumnAvatar.DefaultCellStyle = dataGridViewCellStyle1; this.ColumnAvatar.HeaderText = "Avatar"; this.ColumnAvatar.Name = "ColumnAvatar"; this.ColumnAvatar.Width = 52; // // Column1 // this.Column1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; this.Column1.DataPropertyName = "Text"; dataGridViewCellStyle2.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft; dataGridViewCellStyle2.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); dataGridViewCellStyle2.Padding = new System.Windows.Forms.Padding(0, 20, 0, 0); dataGridViewCellStyle2.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.Column1.DefaultCellStyle = dataGridViewCellStyle2; this.Column1.HeaderText = "Column1"; this.Column1.Name = "Column1"; this.Column1.Resizable = System.Windows.Forms.DataGridViewTriState.False; this.Column1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; this.Column1.Width = 350; // // ColumnTime // this.ColumnTime.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; this.ColumnTime.DataPropertyName = "Time"; dataGridViewCellStyle3.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopRight; dataGridViewCellStyle3.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); dataGridViewCellStyle3.ForeColor = System.Drawing.Color.Silver; dataGridViewCellStyle3.Padding = new System.Windows.Forms.Padding(0, 15, 0, 0); dataGridViewCellStyle3.SelectionBackColor = System.Drawing.Color.Silver; dataGridViewCellStyle3.SelectionForeColor = System.Drawing.Color.Silver; this.ColumnTime.DefaultCellStyle = dataGridViewCellStyle3; this.ColumnTime.FillWeight = 120F; this.ColumnTime.HeaderText = "Time"; this.ColumnTime.Name = "ColumnTime"; this.ColumnTime.ReadOnly = true; this.ColumnTime.Width = 120; // // dataGridViewDialogMessageColumn1 // this.dataGridViewDialogMessageColumn1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewDialogMessageColumn1.DataPropertyName = "Text"; dataGridViewCellStyle4.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft; dataGridViewCellStyle4.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); dataGridViewCellStyle4.Padding = new System.Windows.Forms.Padding(0, 20, 0, 0); dataGridViewCellStyle4.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridViewDialogMessageColumn1.DefaultCellStyle = dataGridViewCellStyle4; this.dataGridViewDialogMessageColumn1.HeaderText = "Column1"; this.dataGridViewDialogMessageColumn1.Name = "dataGridViewDialogMessageColumn1"; this.dataGridViewDialogMessageColumn1.Resizable = System.Windows.Forms.DataGridViewTriState.False; this.dataGridViewDialogMessageColumn1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; // // dataGridViewDialogMessageColumn2 // this.dataGridViewDialogMessageColumn2.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewDialogMessageColumn2.DataPropertyName = "Text"; dataGridViewCellStyle5.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft; dataGridViewCellStyle5.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); dataGridViewCellStyle5.Padding = new System.Windows.Forms.Padding(0, 20, 0, 0); dataGridViewCellStyle5.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridViewDialogMessageColumn2.DefaultCellStyle = dataGridViewCellStyle5; this.dataGridViewDialogMessageColumn2.HeaderText = "Column1"; this.dataGridViewDialogMessageColumn2.Name = "dataGridViewDialogMessageColumn2"; this.dataGridViewDialogMessageColumn2.Resizable = System.Windows.Forms.DataGridViewTriState.False; this.dataGridViewDialogMessageColumn2.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; // // dataGridViewDialogMessageColumn3 // this.dataGridViewDialogMessageColumn3.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.dataGridViewDialogMessageColumn3.DataPropertyName = "Text"; dataGridViewCellStyle6.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft; dataGridViewCellStyle6.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); dataGridViewCellStyle6.Padding = new System.Windows.Forms.Padding(0, 20, 0, 0); dataGridViewCellStyle6.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridViewDialogMessageColumn3.DefaultCellStyle = dataGridViewCellStyle6; this.dataGridViewDialogMessageColumn3.HeaderText = "Column1"; this.dataGridViewDialogMessageColumn3.Name = "dataGridViewDialogMessageColumn3"; this.dataGridViewDialogMessageColumn3.Resizable = System.Windows.Forms.DataGridViewTriState.False; this.dataGridViewDialogMessageColumn3.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.Programmatic; // // dataGridViewTextBoxColumn1 // this.dataGridViewTextBoxColumn1.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; this.dataGridViewTextBoxColumn1.DataPropertyName = "Text"; dataGridViewCellStyle7.Alignment = System.Windows.Forms.DataGridViewContentAlignment.TopLeft; dataGridViewCellStyle7.Padding = new System.Windows.Forms.Padding(2, 20, 0, 0); dataGridViewCellStyle7.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridViewTextBoxColumn1.DefaultCellStyle = dataGridViewCellStyle7; this.dataGridViewTextBoxColumn1.FillWeight = 120F; this.dataGridViewTextBoxColumn1.HeaderText = "Time"; this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1"; this.dataGridViewTextBoxColumn1.ReadOnly = true; this.dataGridViewTextBoxColumn1.Resizable = System.Windows.Forms.DataGridViewTriState.False; this.dataGridViewTextBoxColumn1.SortMode = System.Windows.Forms.DataGridViewColumnSortMode.NotSortable; this.dataGridViewTextBoxColumn1.Width = 70; // // dataGridViewTextBoxColumn2 // this.dataGridViewTextBoxColumn2.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.None; this.dataGridViewTextBoxColumn2.DataPropertyName = "Time"; dataGridViewCellStyle8.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204))); dataGridViewCellStyle8.ForeColor = System.Drawing.Color.Gray; this.dataGridViewTextBoxColumn2.DefaultCellStyle = dataGridViewCellStyle8; this.dataGridViewTextBoxColumn2.FillWeight = 120F; this.dataGridViewTextBoxColumn2.HeaderText = "Time"; this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2"; this.dataGridViewTextBoxColumn2.ReadOnly = true; this.dataGridViewTextBoxColumn2.Width = 120; // // DialogUserControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.panel1); this.Name = "DialogUserControl"; this.Padding = new System.Windows.Forms.Padding(2); this.Size = new System.Drawing.Size(611, 364); this.SizeChanged += new System.EventHandler(this.DialogUserControl_SizeChanged); this.contextMenuStrip1.ResumeLayout(false); this.panel1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.DataGridView dataGridView1; private DataGridViewDialogMessageColumn dataGridViewDialogMessageColumn1; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem copyToolStripMenuItem; private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2; private CustomPanel panel1; private DataGridViewDialogMessageColumn dataGridViewDialogMessageColumn2; private DataGridViewDialogMessageColumn dataGridViewDialogMessageColumn3; private System.Windows.Forms.DataGridViewImageColumn ColumnAvatar; private DataGridViewDialogMessageColumn Column1; private System.Windows.Forms.DataGridViewTextBoxColumn ColumnTime; } }
using System; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading; using bv.common.Core; using eidss.model.AVR.DataBase; using eidss.model.AVR.SourceData; using eidss.model.Resources; using Trace = bv.common.Trace; namespace eidss.avr.db.DBService.Access { public class AccessDataAdapter { private readonly string m_DBFileName; private readonly string m_ConnectionString; //Important!! //As I found OleDbCommand and OleDbDataReader don't release resources after it's using. //Each OleDbCommand must be disposed exlicitly //Each OleDbDataReader must be closed and disposed exlicitly public AccessDataAdapter(string dbFileName) { WindowsLogHelper.WriteToEventLogWindows("Creating DataAdapter for MS Access", EventLogEntryType.Information); //Trace.WriteLine(Trace.Kind.Info, "AccessDataAdapter(): Creating DataAdapter for MS Access."); //Utils.CheckNotNullOrEmpty(dbFileName, "dbFileName"); m_DBFileName = dbFileName; m_ConnectionString = ComposeConnectionString(dbFileName); WindowsLogHelper.WriteToEventLogWindows(String.Format("Connection String = {0}", m_ConnectionString), EventLogEntryType.Information); if (!File.Exists(dbFileName)) { throw new ArgumentException(string.Format("File '{0}' not found.", dbFileName)); } try { using (var connection = new OleDbConnection(m_ConnectionString)) { WindowsLogHelper.WriteToEventLogWindows("Testing MS Access connection with connectionstring", EventLogEntryType.Information); Trace.WriteLine(Trace.Kind.Undefine, "AccessDataAdapter(): Testing MS Access connection with connectionstring.", m_ConnectionString); connection.Open(); connection.Close(); } } catch (Exception ex) { string errStr = String.Format(EidssMessages.Get("msgCannotConnectToAccess"), m_DBFileName); WindowsLogHelper.WriteToEventLogWindows(errStr, EventLogEntryType.Error); Trace.WriteLine(ex); throw new AvrDbException(errStr, ex); } } public static void QueryLineListToAccess(string fileName, AvrDataTable originalTable, bool shouldModifyOriginalTable = true) { var adapter = new AccessDataAdapter(fileName); adapter.ExportTableToAccess(originalTable, shouldModifyOriginalTable); } internal string ComposeConnectionString(string dbFileName) { return string.Format("Data Source={0}; Provider=Microsoft.ACE.OLEDB.12.0;", dbFileName); } internal string DbFileName { get { return m_DBFileName; } } internal bool IsTableExistInAccess(string tableName) { Utils.CheckNotNullOrEmpty(tableName, "tableName"); Trace.WriteLine(Trace.Kind.Undefine, "AccessDataAdapter.IsTableExistInAccess(): Checking is table '{0}' exists.", tableName); using (var connection = new OleDbConnection(m_ConnectionString)) { connection.Open(); bool isTableExist = IsTableExist(connection, null, tableName); connection.Close(); return isTableExist; } } internal void ExportTableToAccess(AvrDataTable originalTable, bool shouldModifyOriginalTable) { WindowsLogHelper.WriteToEventLogWindows("Start ExportTableToAccess", EventLogEntryType.Information); Utils.CheckNotNull(originalTable, "originalTable"); string mess = String.Format("AccessDataAdapter().ExportTableToAccess: Exporting table '{0}' to MS Access Database '{1}'.", originalTable.TableName, m_DBFileName); WindowsLogHelper.WriteToEventLogWindows(mess, EventLogEntryType.Information); Trace.WriteLine(Trace.Kind.Info, "AccessDataAdapter().ExportTableToAccess: Exporting table '{0}' to MS Access Database '{1}'.", originalTable.TableName, m_DBFileName); AvrDataTable dataTable = ConvertTable(originalTable, shouldModifyOriginalTable); using (var connection = new OleDbConnection(m_ConnectionString)) { connection.Open(); OleDbTransaction transaction = connection.BeginTransaction(); try { DropTableIfExists(connection, transaction, dataTable.TableName); CreateTable(connection, transaction, dataTable); InsertData(connection, transaction, dataTable); transaction.Commit(); } catch (Exception ex) { Trace.WriteLine(ex); transaction.Rollback(); throw new AvrDbException(EidssMessages.Get("msgCannotExportToAccess"), ex); } finally { connection.Close(); //Important!! //Release connection pool here. In other case IIS may lock mdb file for downloading //I didn't find how to do this better Thread.Sleep(500); OleDbConnection.ReleaseObjectPool(); GC.WaitForPendingFinalizers(); GC.Collect(); } } } internal static AvrDataTable ConvertTable(AvrDataTable originalTable, bool shouldModifyOriginalTable) { Utils.CheckNotNull(originalTable, "originalTable"); if (originalTable.Columns.Count == 0) { throw new AvrDbException("Eporting table has no columns"); } AvrDataTable dataTable = shouldModifyOriginalTable ? originalTable : originalTable.Copy(); if (string.IsNullOrEmpty(dataTable.TableName)) { dataTable.TableName = "NO_NAME"; } dataTable.TableName = AccessTypeConverter.ConvertName(dataTable.TableName); var captions = new Dictionary<string, int>(); foreach (AvrDataColumn column in dataTable.Columns) { string caption = AccessTypeConverter.ConvertName(column.Caption); column.Caption = caption; if (captions.ContainsKey(caption)) { captions[caption] ++; } else { captions.Add(caption, 1); } } foreach (AvrDataColumn column in dataTable.Columns) { string newName = column.Caption; if (captions[newName] > 1) { int matches = dataTable.Columns .TakeWhile(innerColumn => !ReferenceEquals(innerColumn, column)) .Count(innerColumn => innerColumn.Caption == newName); newName += (matches+1).ToString(); } column.ColumnName = newName; } return dataTable; } internal static bool IsTableExist(OleDbConnection connection, OleDbTransaction transaction, string tableName) { Utils.CheckNotNull(connection, "connection"); Utils.CheckNotNullOrEmpty(tableName, "tableName"); DataTable schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] {null, null, null, "TABLE"}); var dataView = new DataView(schemaTable) { RowFilter = string.Format("TABLE_NAME = '{0}'", tableName) }; return dataView.Count > 0; } internal static void DropTableIfExists (OleDbConnection connection, OleDbTransaction transaction, string tableName) { Utils.CheckNotNull(connection, "connection"); Utils.CheckNotNullOrEmpty(tableName, "tableName"); bool isTableExists = IsTableExist(connection, transaction, tableName); if (isTableExists) { Trace.WriteLine(Trace.Kind.Info, "AccessDataAdapter.DropTableIfExists: Dropping table '{0}'.", tableName); using (OleDbCommand command = connection.CreateCommand()) { command.Transaction = transaction; command.CommandText = string.Format("DROP TABLE {0}", tableName); command.ExecuteNonQuery(); } } } internal static void CreateTable(OleDbConnection connection, OleDbTransaction transaction, AvrDataTable table) { Utils.CheckNotNull(connection, "connection"); Utils.CheckNotNull(table, "table"); Trace.WriteLine(Trace.Kind.Info, "AccessDataAdapter.CreateTable: Creating table '{0}'.", table.TableName); using (OleDbCommand command = connection.CreateCommand()) { command.Transaction = transaction; command.CommandText = CreateTableCommandText(table); command.ExecuteNonQuery(); } } internal static void InsertData(OleDbConnection connection, OleDbTransaction transaction, AvrDataTable table) { Utils.CheckNotNull(connection, "connection"); Utils.CheckNotNull(table, "table"); Trace.WriteLine(Trace.Kind.Info, "AccessDataAdapter.InsertData: Inserting data into table '{0}'.", table.TableName); bool isTableExists = IsTableExist(connection, transaction, table.TableName); if (!isTableExists) { throw new ApplicationException(string.Format("Table {0} doesn't exist", table.TableName)); } using (var adapter = new OleDbDataAdapter()) { adapter.SelectCommand = new OleDbCommand(SelectCommandText(table), connection) {Transaction = transaction}; adapter.InsertCommand = new OleDbCommand(InsertCommandText(table), connection) {Transaction = transaction}; foreach (AvrDataColumn column in table.Columns) { OleDbType dbType = AccessTypeConverter.ConverTypeToDb(column); OleDbParameter dbParameter = adapter.InsertCommand.Parameters.Add("@" + column.ColumnName, dbType); dbParameter.SourceColumn = column.ColumnName; } var dataTable = table.ToDataTable(); var rowList = new List<DataRow>(); foreach (DataRow row in dataTable.Rows) { if (row.RowState == DataRowState.Unchanged) { row.SetAdded(); } rowList.Add(row); } adapter.Update(rowList.ToArray()); adapter.SelectCommand.Dispose(); adapter.InsertCommand.Dispose(); } } #region command text internal static string CreateTableCommandText(AvrDataTable table) { Utils.CheckNotNull(table, "table"); Utils.CheckNotNullOrEmpty(table.TableName, "table.TableName"); var sbCreate = new StringBuilder(@"CREATE TABLE ["); sbCreate.Append(table.TableName); sbCreate.AppendLine("]("); bool isFirstColumn = true; foreach (AvrDataColumn column in table.Columns) { if (!isFirstColumn) { sbCreate.AppendLine(","); } isFirstColumn = false; string dataTypeName = AccessTypeConverter.ConvertTypeToDbName(column); string columnName = column.ColumnName; // if (columnName.Length > 64) // { // columnName = columnName.Substring(0, 60) + Guid.NewGuid().ToString().Substring(0, 4); // } sbCreate.AppendFormat("[{0}] {1}", columnName, dataTypeName); } sbCreate.AppendLine(); sbCreate.Append(")"); return sbCreate.ToString(); } internal static string SelectCommandText(AvrDataTable table) { Utils.CheckNotNull(table, "table"); Utils.CheckNotNullOrEmpty(table.TableName, "table.TableName"); var sbCreate = new StringBuilder(@"SELECT "); sbCreate.AppendLine(); bool isFirstColumn = true; foreach (AvrDataColumn column in table.Columns) { if (!isFirstColumn) { sbCreate.AppendLine(","); } isFirstColumn = false; sbCreate.AppendFormat("[{0}]", column.ColumnName); } sbCreate.AppendLine(); sbCreate.AppendFormat("FROM [{0}]", table.TableName); return sbCreate.ToString(); } internal static string InsertCommandText(AvrDataTable table) { Utils.CheckNotNull(table, "table"); Utils.CheckNotNullOrEmpty(table.TableName, "table.TableName"); var sbCreate = new StringBuilder(string.Format(@"INSERT INTO [{0}] ", table.TableName)); sbCreate.AppendLine("("); bool isFirstColumn = true; foreach (AvrDataColumn column in table.Columns) { if (!isFirstColumn) { sbCreate.AppendLine(", "); } isFirstColumn = false; sbCreate.AppendFormat("[{0}]", column.ColumnName); } sbCreate.AppendLine(")"); sbCreate.AppendLine("Values("); for (int i = 0; i < table.Columns.Count; i++) { if (i > 0) { sbCreate.Append(", "); } sbCreate.Append("?"); } sbCreate.Append(")"); return sbCreate.ToString(); } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; using k8s.Tests.Mock; using Xunit; using Xunit.Abstractions; namespace k8s.Tests { public class StreamDemuxerTests { private readonly ITestOutputHelper testOutput; public StreamDemuxerTests(ITestOutputHelper testOutput) { this.testOutput = testOutput; } [Fact] public async Task SendDataRemoteCommand() { using (var ws = new MockWebSocket()) using (var demuxer = new StreamDemuxer(ws)) { var sentBuffer = new List<byte>(); ws.MessageSent += (sender, args) => { sentBuffer.AddRange(args.Data.Buffer); }; demuxer.Start(); byte channelIndex = 12; var stream = demuxer.GetStream(channelIndex, channelIndex); var b = GenerateRandomBuffer(100, 0xEF); stream.Write(b, 0, b.Length); // Send 100 bytes, expect 1 (channel index) + 100 (payload) = 101 bytes Assert.True( await WaitForAsync(() => sentBuffer.Count == 101).ConfigureAwait(false), $"Demuxer error: expect to send 101 bytes, but actually send {sentBuffer.Count} bytes."); Assert.True(sentBuffer[0] == channelIndex, "The first sent byte is not channel index!"); Assert.True(sentBuffer[1] == 0xEF, "Incorrect payload!"); } } [Fact] public async Task SendMultipleDataRemoteCommand() { using (var ws = new MockWebSocket()) using (var demuxer = new StreamDemuxer(ws)) { var sentBuffer = new List<byte>(); ws.MessageSent += (sender, args) => { sentBuffer.AddRange(args.Data.Buffer); }; demuxer.Start(); byte channelIndex = 12; var stream = demuxer.GetStream(channelIndex, channelIndex); var b = GenerateRandomBuffer(100, 0xEF); stream.Write(b, 0, b.Length); b = GenerateRandomBuffer(200, 0xAB); stream.Write(b, 0, b.Length); // Send 300 bytes in 2 messages, expect 1 (channel index) * 2 + 300 (payload) = 302 bytes Assert.True( await WaitForAsync(() => sentBuffer.Count == 302).ConfigureAwait(false), $"Demuxer error: expect to send 302 bytes, but actually send {sentBuffer.Count} bytes."); Assert.True(sentBuffer[0] == channelIndex, "The first sent byte is not channel index!"); Assert.True(sentBuffer[1] == 0xEF, "The first part of payload incorrect!"); Assert.True(sentBuffer[101] == channelIndex, "The second message first byte is not channel index!"); Assert.True(sentBuffer[102] == 0xAB, "The second part of payload incorrect!"); } } [Fact] public async Task ReceiveDataRemoteCommand() { using (var ws = new MockWebSocket()) using (var demuxer = new StreamDemuxer(ws)) { demuxer.Start(); var receivedBuffer = new List<byte>(); byte channelIndex = 12; var stream = demuxer.GetStream(channelIndex, channelIndex); // Receive 600 bytes in 3 messages. Exclude 1 channel index byte per message, expect 597 bytes payload. var expectedCount = 597; var t = Task.Run(async () => { await ws.InvokeReceiveAsync( new ArraySegment<byte>(GenerateRandomBuffer(100, channelIndex, 0xAA, false)), WebSocketMessageType.Binary, true).ConfigureAwait(false); await ws.InvokeReceiveAsync( new ArraySegment<byte>(GenerateRandomBuffer(200, channelIndex, 0xAB, false)), WebSocketMessageType.Binary, true).ConfigureAwait(false); await ws.InvokeReceiveAsync( new ArraySegment<byte>(GenerateRandomBuffer(300, channelIndex, 0xAC, false)), WebSocketMessageType.Binary, true).ConfigureAwait(false); await WaitForAsync(() => receivedBuffer.Count == expectedCount).ConfigureAwait(false); await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "normal", CancellationToken.None).ConfigureAwait(false); }); var buffer = new byte[50]; while (true) { var cRead = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); if (cRead == 0) { break; } for (var i = 0; i < cRead; i++) { receivedBuffer.Add(buffer[i]); } } await t.ConfigureAwait(false); Assert.True( receivedBuffer.Count == expectedCount, $"Demuxer error: expect to receive {expectedCount} bytes, but actually got {receivedBuffer.Count} bytes."); Assert.True(receivedBuffer[0] == 0xAA, "The first payload incorrect!"); Assert.True(receivedBuffer[98] == 0xAA, "The first payload incorrect!"); Assert.True(receivedBuffer[99] == 0xAB, "The second payload incorrect!"); Assert.True(receivedBuffer[297] == 0xAB, "The second payload incorrect!"); Assert.True(receivedBuffer[298] == 0xAC, "The third payload incorrect!"); Assert.True(receivedBuffer[596] == 0xAC, "The third payload incorrect!"); } } [Fact] public async Task ReceiveDataPortForward() { using (var ws = new MockWebSocket()) using (var demuxer = new StreamDemuxer(ws, StreamType.PortForward)) { demuxer.Start(); var receivedBuffer = new List<byte>(); byte channelIndex = 12; var stream = demuxer.GetStream(channelIndex, channelIndex); // Receive 600 bytes in 3 messages. Exclude 1 channel index byte per message, and 2 port bytes in the first message. // expect 600 - 3 - 2 = 595 bytes payload. var expectedCount = 595; var t = Task.Run(async () => { await ws.InvokeReceiveAsync( new ArraySegment<byte>(GenerateRandomBuffer(100, channelIndex, 0xB1, true)), WebSocketMessageType.Binary, true).ConfigureAwait(false); await ws.InvokeReceiveAsync( new ArraySegment<byte>(GenerateRandomBuffer(200, channelIndex, 0xB2, false)), WebSocketMessageType.Binary, true).ConfigureAwait(false); await ws.InvokeReceiveAsync( new ArraySegment<byte>(GenerateRandomBuffer(300, channelIndex, 0xB3, false)), WebSocketMessageType.Binary, true).ConfigureAwait(false); await WaitForAsync(() => receivedBuffer.Count == expectedCount).ConfigureAwait(false); await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "normal", CancellationToken.None).ConfigureAwait(false); }); var buffer = new byte[50]; while (true) { var cRead = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); if (cRead == 0) { break; } for (var i = 0; i < cRead; i++) { receivedBuffer.Add(buffer[i]); } } await t.ConfigureAwait(false); Assert.True( receivedBuffer.Count == expectedCount, $"Demuxer error: expect to receive {expectedCount} bytes, but actually got {receivedBuffer.Count} bytes."); Assert.True(receivedBuffer[0] == 0xB1, "The first payload incorrect!"); Assert.True(receivedBuffer[96] == 0xB1, "The first payload incorrect!"); Assert.True(receivedBuffer[97] == 0xB2, "The second payload incorrect!"); Assert.True(receivedBuffer[295] == 0xB2, "The second payload incorrect!"); Assert.True(receivedBuffer[296] == 0xB3, "The third payload incorrect!"); Assert.True(receivedBuffer[594] == 0xB3, "The third payload incorrect!"); } } [Fact] public async Task ReceiveDataPortForwardOneByteMessage() { using (var ws = new MockWebSocket()) using (var demuxer = new StreamDemuxer(ws, StreamType.PortForward)) { demuxer.Start(); var receivedBuffer = new List<byte>(); byte channelIndex = 12; var stream = demuxer.GetStream(channelIndex, channelIndex); // Receive 402 bytes in 3 buffers of 2 messages. Exclude 1 channel index byte per message, and 2 port bytes in the first message. // expect 402 - 1 x 2 - 2 = 398 bytes payload. var expectedCount = 398; var t = Task.Run(async () => { await ws.InvokeReceiveAsync( new ArraySegment<byte>(GenerateRandomBuffer(2, channelIndex, 0xC1, true)), WebSocketMessageType.Binary, false).ConfigureAwait(false); await ws.InvokeReceiveAsync( new ArraySegment<byte>(GenerateRandomBuffer(100, channelIndex, 0xC2, false)), WebSocketMessageType.Binary, true).ConfigureAwait(false); await ws.InvokeReceiveAsync( new ArraySegment<byte>(GenerateRandomBuffer(300, channelIndex, 0xC3, false)), WebSocketMessageType.Binary, true).ConfigureAwait(false); await WaitForAsync(() => receivedBuffer.Count == expectedCount).ConfigureAwait(false); await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "normal", CancellationToken.None).ConfigureAwait(false); }); var buffer = new byte[50]; while (true) { var cRead = await stream.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); if (cRead == 0) { break; } for (var i = 0; i < cRead; i++) { receivedBuffer.Add(buffer[i]); } } await t.ConfigureAwait(false); Assert.True( receivedBuffer.Count == expectedCount, $"Demuxer error: expect to receive {expectedCount} bytes, but actually got {receivedBuffer.Count} bytes."); Assert.True(receivedBuffer[0] == 0xC2, "The first payload incorrect!"); Assert.True(receivedBuffer[98] == 0xC2, "The first payload incorrect!"); Assert.True(receivedBuffer[99] == 0xC3, "The second payload incorrect!"); Assert.True(receivedBuffer[397] == 0xC3, "The second payload incorrect!"); } } [Fact] public async Task ReceiveDataRemoteCommandMultipleStream() { using (var ws = new MockWebSocket()) using (var demuxer = new StreamDemuxer(ws)) { demuxer.Start(); var receivedBuffer1 = new List<byte>(); byte channelIndex1 = 1; var stream1 = demuxer.GetStream(channelIndex1, channelIndex1); var receivedBuffer2 = new List<byte>(); byte channelIndex2 = 2; var stream2 = demuxer.GetStream(channelIndex2, channelIndex2); // stream 1: receive 100 + 300 = 400 bytes, exclude 1 channel index per message, expect 400 - 1 x 2 = 398 bytes. var expectedCount1 = 398; // stream 2: receive 200 bytes, exclude 1 channel index per message, expect 200 - 1 = 199 bytes. var expectedCount2 = 199; var t1 = Task.Run(async () => { // Simulate WebSocket received remote data to multiple streams await ws.InvokeReceiveAsync( new ArraySegment<byte>(GenerateRandomBuffer(100, channelIndex1, 0xD1, false)), WebSocketMessageType.Binary, true).ConfigureAwait(false); await ws.InvokeReceiveAsync( new ArraySegment<byte>(GenerateRandomBuffer(200, channelIndex2, 0xD2, false)), WebSocketMessageType.Binary, true).ConfigureAwait(false); await ws.InvokeReceiveAsync( new ArraySegment<byte>(GenerateRandomBuffer(300, channelIndex1, 0xD3, false)), WebSocketMessageType.Binary, true).ConfigureAwait(false); await WaitForAsync(() => receivedBuffer1.Count == expectedCount1).ConfigureAwait(false); await WaitForAsync(() => receivedBuffer2.Count == expectedCount2).ConfigureAwait(false); await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "normal", CancellationToken.None).ConfigureAwait(false); }); var t2 = Task.Run(async () => { var buffer = new byte[50]; while (true) { var cRead = await stream1.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); if (cRead == 0) { break; } for (var i = 0; i < cRead; i++) { receivedBuffer1.Add(buffer[i]); } } }); var t3 = Task.Run(async () => { var buffer = new byte[50]; while (true) { var cRead = await stream2.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); if (cRead == 0) { break; } for (var i = 0; i < cRead; i++) { receivedBuffer2.Add(buffer[i]); } } }); await Task.WhenAll(t1, t2, t3).ConfigureAwait(false); Assert.True( receivedBuffer1.Count == expectedCount1, $"Demuxer error: expect to receive {expectedCount1} bytes, but actually got {receivedBuffer1.Count} bytes."); Assert.True( receivedBuffer2.Count == expectedCount2, $"Demuxer error: expect to receive {expectedCount2} bytes, but actually got {receivedBuffer2.Count} bytes."); Assert.True(receivedBuffer1[0] == 0xD1, "The first payload incorrect!"); Assert.True(receivedBuffer1[98] == 0xD1, "The first payload incorrect!"); Assert.True(receivedBuffer1[99] == 0xD3, "The second payload incorrect!"); Assert.True(receivedBuffer1[397] == 0xD3, "The second payload incorrect!"); Assert.True(receivedBuffer2[0] == 0xD2, "The first payload incorrect!"); Assert.True(receivedBuffer2[198] == 0xD2, "The first payload incorrect!"); } } [Fact] public async Task ReceiveDataPortForwardMultipleStream() { using (var ws = new MockWebSocket()) using (var demuxer = new StreamDemuxer(ws, StreamType.PortForward)) { demuxer.Start(); var receivedBuffer1 = new List<byte>(); byte channelIndex1 = 1; var stream1 = demuxer.GetStream(channelIndex1, channelIndex1); var receivedBuffer2 = new List<byte>(); byte channelIndex2 = 2; var stream2 = demuxer.GetStream(channelIndex2, channelIndex2); // stream 1: receive 100 + 300 = 400 bytes, exclude 1 channel index per message, exclude port bytes in the first message, // expect 400 - 1 x 2 - 2 = 396 bytes. var expectedCount1 = 396; // stream 2: receive 200 bytes, exclude 1 channel index per message, exclude port bytes in the first message, // expect 200 - 1 - 2 = 197 bytes. var expectedCount2 = 197; var t1 = Task.Run(async () => { // Simulate WebSocket received remote data to multiple streams await ws.InvokeReceiveAsync( new ArraySegment<byte>(GenerateRandomBuffer(100, channelIndex1, 0xE1, true)), WebSocketMessageType.Binary, true).ConfigureAwait(false); await ws.InvokeReceiveAsync( new ArraySegment<byte>(GenerateRandomBuffer(200, channelIndex2, 0xE2, true)), WebSocketMessageType.Binary, true).ConfigureAwait(false); await ws.InvokeReceiveAsync( new ArraySegment<byte>(GenerateRandomBuffer(300, channelIndex1, 0xE3, false)), WebSocketMessageType.Binary, true).ConfigureAwait(false); await WaitForAsync(() => receivedBuffer1.Count == expectedCount1).ConfigureAwait(false); await WaitForAsync(() => receivedBuffer2.Count == expectedCount2).ConfigureAwait(false); await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, "normal", CancellationToken.None).ConfigureAwait(false); }); var t2 = Task.Run(async () => { var buffer = new byte[50]; while (true) { var cRead = await stream1.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); if (cRead == 0) { break; } for (var i = 0; i < cRead; i++) { receivedBuffer1.Add(buffer[i]); } } }); var t3 = Task.Run(async () => { var buffer = new byte[50]; while (true) { var cRead = await stream2.ReadAsync(buffer, 0, buffer.Length).ConfigureAwait(false); if (cRead == 0) { break; } for (var i = 0; i < cRead; i++) { receivedBuffer2.Add(buffer[i]); } } }); await Task.WhenAll(t1, t2, t3).ConfigureAwait(false); Assert.True( receivedBuffer1.Count == expectedCount1, $"Demuxer error: expect to receive {expectedCount1} bytes, but actually got {receivedBuffer1.Count} bytes."); Assert.True( receivedBuffer2.Count == expectedCount2, $"Demuxer error: expect to receive {expectedCount2} bytes, but actually got {receivedBuffer2.Count} bytes."); Assert.True(receivedBuffer1[0] == 0xE1, "The first payload incorrect!"); Assert.True(receivedBuffer1[96] == 0xE1, "The first payload incorrect!"); Assert.True(receivedBuffer1[97] == 0xE3, "The second payload incorrect!"); Assert.True(receivedBuffer1[395] == 0xE3, "The second payload incorrect!"); Assert.True(receivedBuffer2[0] == 0xE2, "The first payload incorrect!"); Assert.True(receivedBuffer2[196] == 0xE2, "The first payload incorrect!"); } } private static byte[] GenerateRandomBuffer(int length, byte channelIndex, byte content, bool portForward) { var buffer = GenerateRandomBuffer(length, content); buffer[0] = channelIndex; if (portForward) { if (length > 1) { buffer[1] = 0xFF; // the first port bytes } if (length > 2) { buffer[2] = 0xFF; // the 2nd port bytes } } return buffer; } private static byte[] GenerateRandomBuffer(int length, byte content) { var buffer = new byte[length]; for (var i = 0; i < length; i++) { buffer[i] = content; } return buffer; } private async Task<bool> WaitForAsync(Func<bool> handler, float waitForSeconds = 1) { var w = Stopwatch.StartNew(); try { do { if (handler()) { return true; } await Task.Delay(10).ConfigureAwait(false); } while (w.Elapsed.Duration().TotalSeconds < waitForSeconds); return false; } finally { w.Stop(); } } } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// A cafe or coffee shop. /// </summary> public class CafeOrCoffeeShop_Core : TypeCore, IFoodEstablishment { public CafeOrCoffeeShop_Core() { this._TypeId = 50; this._Id = "CafeOrCoffeeShop"; this._Schema_Org_Url = "http://schema.org/CafeOrCoffeeShop"; string label = ""; GetLabel(out label, "CafeOrCoffeeShop", typeof(CafeOrCoffeeShop_Core)); this._Label = label; this._Ancestors = new int[]{266,193,155,106}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{106}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,47,75,77,94,95,130,137,36,60,152,156,167,1,139,205}; } /// <summary> /// Either <code>Yes/No</code>, or a URL at which reservations can be made. /// </summary> private AcceptsReservations_Core acceptsReservations; public AcceptsReservations_Core AcceptsReservations { get { return acceptsReservations; } set { acceptsReservations = value; SetPropertyInstance(acceptsReservations); } } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The larger organization that this local business is a branch of, if any. /// </summary> private BranchOf_Core branchOf; public BranchOf_Core BranchOf { get { return branchOf; } set { branchOf = value; SetPropertyInstance(branchOf); } } /// <summary> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// The currency accepted (in <a href=\http://en.wikipedia.org/wiki/ISO_4217\ target=\new\>ISO 4217 currency format</a>). /// </summary> private CurrenciesAccepted_Core currenciesAccepted; public CurrenciesAccepted_Core CurrenciesAccepted { get { return currenciesAccepted; } set { currenciesAccepted = value; SetPropertyInstance(currenciesAccepted); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// Either the actual menu or a URL of the menu. /// </summary> private Menu_Core menu; public Menu_Core Menu { get { return menu; } set { menu = value; SetPropertyInstance(menu); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code>&lt;time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\&gt;Tuesdays and Thursdays 4-8pm&lt;/time&gt;</code>. <br/>- If a business is open 7 days a week, then it can be specified as <code>&lt;time itemprop=\openingHours\ datetime=\Mo-Su\&gt;Monday through Sunday, all day&lt;/time&gt;</code>. /// </summary> private OpeningHours_Core openingHours; public OpeningHours_Core OpeningHours { get { return openingHours; } set { openingHours = value; SetPropertyInstance(openingHours); } } /// <summary> /// Cash, credit card, etc. /// </summary> private PaymentAccepted_Core paymentAccepted; public PaymentAccepted_Core PaymentAccepted { get { return paymentAccepted; } set { paymentAccepted = value; SetPropertyInstance(paymentAccepted); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// The price range of the business, for example <code>$$$</code>. /// </summary> private PriceRange_Core priceRange; public PriceRange_Core PriceRange { get { return priceRange; } set { priceRange = value; SetPropertyInstance(priceRange); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The cuisine of the restaurant. /// </summary> private ServesCuisine_Core servesCuisine; public ServesCuisine_Core ServesCuisine { get { return servesCuisine; } set { servesCuisine = value; SetPropertyInstance(servesCuisine); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
// // MonoTests.System.Xml.Serialization.XmlSerializationWriterTests // // Author: Erik LeBel <eriklebel@yahoo.ca> // // (C) Erik LeBel 2003 // // FIXME add tests for callbacks // FIXME add tests for writes that generate namespaces // FIXME add test that write XmlNode objects // using System; using System.IO; using System.Xml; using System.Xml.Serialization; using NUnit.Framework; namespace MonoTests.System.XmlSerialization { // base, common implementation of XmlSerializationWriter test harness. // the reason for this is that all auto generated namespace prefixes // of the form q# are modified by any Write* that defines a new namespace. // The result of this is that even though we redefine the string results // to exclude previous tests, the q#s will change depending on number of // namespace declarations were made prior to the perticual test. This // means that if the [Test] methods are called out of sequence, they // all start to fail. For this reason, tests that define and verify // temporary namespaces should be stored in a seperate class which protects // itself from accidental pre-definitions. public class XmlSerializarionWriterTester : XmlSerializationWriter { // appease the compiler protected override void InitCallbacks () { } StringWriter sw; XmlTextWriter writer; [SetUp] protected void Reset() { sw = new StringWriter (); writer = new XmlTextWriter (sw); writer.QuoteChar = '\''; writer.Formatting = Formatting.None; Writer = writer; } protected string Content { get { string val = sw.GetStringBuilder().ToString(); // Console.WriteLine(val); return val; } } } // this class tests the methods of the XmlSerializationWriter that // can be executed out of order. [TestFixture] public class XmlSerializationWriterSimpleTests : XmlSerializarionWriterTester { const string ANamespace = "some:urn"; // These TestFrom* methods indirectly test the functionality of XmlCustomFormatter [Test] public void TestFromByteArrayBase64() { // FIXME // This should work according to Mono's API, but .NET's FromByteArrayBase64 // returns a byte array. // //string val = this.FromByteArrayBase64(new byte [] {143, 144, 1, 0}); //Assertion.AssertEquals(FromByteArrayBase64(null), ""); //val = FromByteArrayBase64(null); //try/catch or AssertEruals? } [Test] public void TestFromByteArrayHex() { byte [] vals = {143, 144, 1, 0}; Assertion.AssertEquals("8F900100", FromByteArrayHex(vals)); Assertion.AssertEquals(null, FromByteArrayHex(null)); } [Test] public void TestFromChar() { Assertion.AssertEquals("97", FromChar('a')); Assertion.AssertEquals("0", FromChar('\0')); Assertion.AssertEquals("10", FromChar('\n')); Assertion.AssertEquals("65281", FromChar('\uFF01')); } [Test] public void TestFromDate() { DateTime d = new DateTime(); Assertion.AssertEquals("0001-01-01", FromDate(d)); } [Test] public void TestFromDateTime() { DateTime d = new DateTime(); Assertion.AssertEquals("0001-01-01T00:00:00.0000000", FromDateTime(d).Substring (0, 27)); } [Test] public void TestFromEnum() { long[] ids = {1, 2, 3, 4}; string[] values = {"one", "two", "three"}; Assertion.AssertEquals("one", FromEnum(1, values, ids)); Assertion.AssertEquals("", FromEnum(0, values, ids)); try { string dummy = FromEnum(4, values, ids); Assertion.Fail("This should fail with an array-out-of-bunds error"); } catch (Exception) { } } [Test] public void TestFromTime() { DateTime d = new DateTime(); // Don't include time zone. Assertion.AssertEquals("00:00:00.0000000", FromTime(d).Substring (0, 16)); } [Test] public void TestFromXmlName() { Assertion.AssertEquals("Hello", FromXmlName("Hello")); Assertion.AssertEquals("go_x0020_dogs_x0020_go", FromXmlName("go dogs go")); Assertion.AssertEquals("what_x0027_s_x0020_up", FromXmlName("what's up")); Assertion.AssertEquals("_x0031_23go", FromXmlName("123go")); Assertion.AssertEquals("Hello_x0020_what_x0027_s.up", FromXmlName("Hello what's.up")); } [Test] public void TestFromXmlNCName() { Assertion.AssertEquals("Hello", FromXmlNCName("Hello")); Assertion.AssertEquals("go_x0020_dogs_x0020_go", FromXmlNCName("go dogs go")); Assertion.AssertEquals("what_x0027_s_x0020_up", FromXmlNCName("what's up")); Assertion.AssertEquals("_x0031_23go", FromXmlNCName("123go")); Assertion.AssertEquals("Hello_x0020_what_x0027_s.up", FromXmlNCName("Hello what's.up")); } [Test] public void TestFromXmlNmToken() { Assertion.AssertEquals("Hello", FromXmlNmToken("Hello")); Assertion.AssertEquals("go_x0020_dogs_x0020_go", FromXmlNmToken("go dogs go")); Assertion.AssertEquals("what_x0027_s_x0020_up", FromXmlNmToken("what's up")); Assertion.AssertEquals("123go", FromXmlNmToken("123go")); Assertion.AssertEquals("Hello_x0020_what_x0027_s.up", FromXmlNmToken("Hello what's.up")); } [Test] public void TestFromXmlNmTokens() { Assertion.AssertEquals("Hello go dogs_go 123go what_x0027_s.up", FromXmlNmTokens("Hello go dogs_go 123go what's.up")); } [Test] public void TestWriteAttribute() { WriteStartElement("x"); WriteAttribute("a", "b"); WriteEndElement(); Assertion.AssertEquals("<x a='b' />", Content); Reset(); WriteStartElement("x"); WriteAttribute("a", new byte[] {1, 2, 3}); WriteEndElement(); Assertion.AssertEquals("<x a='AQID' />", Content); Reset(); WriteStartElement("x"); WriteAttribute("a", "<b"); WriteEndElement(); Assertion.AssertEquals("<x a='&lt;b' />", Content); Reset(); WriteStartElement("x"); string typedPlaceholder = null; WriteAttribute("a", typedPlaceholder); WriteEndElement(); Assertion.AssertEquals("<x />", Content); Reset(); WriteStartElement("x"); WriteAttribute("a", "\""); WriteEndElement(); Assertion.AssertEquals("<x a='\"' />", Content); Reset(); WriteStartElement("x"); WriteAttribute("a", "b\nc"); WriteEndElement(); Assertion.AssertEquals("<x a='b&#xA;c' />", Content); Reset(); WriteStartElement("x"); WriteAttribute("a", ANamespace, "b"); WriteEndElement(); Assertion.AssertEquals("<x d1p1:a='b' xmlns:d1p1='some:urn' />", Content); } [Test] public void TestWriteElementEncoded() { // FIXME // XmlNode related } [Test] public void TestWriteElementLiteral() { // FIXME // XmlNode related } [Test] public void TestWriteElementString() { WriteElementString("x", "a"); Assertion.AssertEquals("<x>a</x>", Content); Reset(); WriteElementString("x", "<a"); Assertion.AssertEquals("<x>&lt;a</x>", Content); } [Test] public void TestWriteElementStringRaw() { byte [] placeHolderArray = null; WriteElementStringRaw("x", placeHolderArray); Assertion.AssertEquals("", Content); Reset(); WriteElementStringRaw("x", new byte[] {0, 2, 4}); Assertion.AssertEquals("<x>AAIE</x>", Content); Reset(); WriteElementStringRaw("x", new byte[] {}); Assertion.AssertEquals("<x />", Content); // Note to reader, the output is not valid xml Reset(); WriteElementStringRaw("x", "a > 13 && a < 19"); Assertion.AssertEquals("<x>a > 13 && a < 19</x>", Content); } [Test] public void TestWriteEmptyTag() { WriteEmptyTag("x"); Assertion.AssertEquals("<x />", Content); } [Test] public void TestWriteNamespaceDeclarations() { XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); WriteStartElement("x"); WriteNamespaceDeclarations(ns); WriteEndElement(); Assertion.AssertEquals("<x />", Content); Reset(); ns.Add("mypref", ANamespace); WriteStartElement("x"); WriteNamespaceDeclarations(ns); WriteEndElement(); Assertion.AssertEquals(XmlSerializerTests.Infoset("<x xmlns:mypref='some:urn' />"), XmlSerializerTests.Infoset(Content)); Reset(); ns.Add("ns2", "another:urn"); WriteStartElement("x"); WriteNamespaceDeclarations(ns); WriteEndElement(); Assertion.AssertEquals(XmlSerializerTests.Infoset("<x xmlns:ns2='another:urn' xmlns:mypref='some:urn' />"), XmlSerializerTests.Infoset(Content)); Reset(); ns.Add("ns3", "ya:urn"); WriteStartElement("x"); WriteNamespaceDeclarations(ns); WriteEndElement(); Assertion.AssertEquals(XmlSerializerTests.Infoset("<x xmlns:ns3='ya:urn' xmlns:ns2='another:urn' xmlns:mypref='some:urn' />"), XmlSerializerTests.Infoset(Content)); } [Test] public void TestWriteNullableStringLiteral() { WriteNullableStringLiteral("x", null, null); Assertion.AssertEquals(XmlSerializerTests.Infoset("<x d1p1:nil='true' xmlns:d1p1='http://www.w3.org/2001/XMLSchema-instance' />"), XmlSerializerTests.Infoset(Content)); Reset(); WriteNullableStringLiteral("x", null, ""); Assertion.AssertEquals("<x />", Content); Reset(); WriteNullableStringLiteral("x", null, "a<b\'c"); Assertion.AssertEquals("<x>a&lt;b\'c</x>", Content); Reset(); WriteNullableStringLiteral("x", ANamespace, "b"); Assertion.AssertEquals("<x xmlns='some:urn'>b</x>", Content); } [Test] public void TestWriteNullableStringLiteralRaw() { WriteNullableStringLiteralRaw("x", null, new byte[] {1, 2, 244}); Assertion.AssertEquals("<x>AQL0</x>", Content); } [Test] public void TestWriteNullTagEncoded() { WriteNullTagEncoded("x"); Assertion.AssertEquals(XmlSerializerTests.Infoset("<x d1p1:nil='true' xmlns:d1p1='http://www.w3.org/2001/XMLSchema-instance' />"), XmlSerializerTests.Infoset(Content)); } [Test] public void TestWriteNullTagLiteral() { WriteNullTagLiteral("x"); Assertion.AssertEquals(XmlSerializerTests.Infoset("<x d1p1:nil='true' xmlns:d1p1='http://www.w3.org/2001/XMLSchema-instance' />"), XmlSerializerTests.Infoset(Content)); } [Test] public void TestWriteSerializable() { // FIXME //Assertion.AssertEquals(, ""); } public void TestWriteStartDocument() { Assertion.AssertEquals("", Content); WriteStartDocument(); Assertion.AssertEquals("<?xml version='1.0' encoding='utf-16'?>", Content); } [Test] public void TestWriteStartElement() { WriteStartElement("x"); WriteEndElement(); Assertion.AssertEquals("<x />", Content); Reset(); WriteStartElement("x"); WriteValue("a"); WriteEndElement(); Assertion.AssertEquals("<x>a</x>", Content); Reset(); WriteStartElement("x"); WriteStartElement("y", "z"); WriteEndElement(); WriteEndElement(); Assertion.AssertEquals("<x><y xmlns='z' /></x>", Content); Reset(); WriteStartElement("x"); WriteStartElement("y", "z", true); WriteEndElement(); WriteEndElement(); Assertion.AssertEquals("<x><q1:y xmlns:q1='z' /></x>", Content); } public void TestWriteTypedPrimitive() { // as long as WriteTypePrimitive's last argument is false, this is OK here. WriteTypedPrimitive("x", ANamespace, "hello", false); Assertion.AssertEquals("<x xmlns='some:urn'>hello</x>", Content); Reset(); WriteTypedPrimitive("x", ANamespace, 10, false); Assertion.AssertEquals("<x xmlns='some:urn'>10</x>", Content); try { WriteTypedPrimitive("x", ANamespace, null, false); Assertion.Fail("Should not be able to write a null primitive"); } catch (Exception) { } } public void TestWriteValue() { WriteValue(""); Assertion.AssertEquals("", Content); Reset(); WriteValue("hello"); Assertion.AssertEquals("hello", Content); Reset(); string v = null; WriteValue(v); Assertion.AssertEquals("", Content); Reset(); WriteValue(new byte[] {13, 8, 99}); Assertion.AssertEquals("DQhj", Content); } public void TestWriteXmlAttribute() { // FIXME // XmlNode related } public void TestWriteXsiType() { WriteStartElement("x"); WriteXsiType("pref", null); WriteEndElement(); Assertion.AssertEquals(XmlSerializerTests.Infoset("<x d1p1:type='pref' xmlns:d1p1='http://www.w3.org/2001/XMLSchema-instance' />"), XmlSerializerTests.Infoset(Content)); } } }
using System; using MLAPI.Serialization; using MLAPI.Serialization.Pooled; using NUnit.Framework; using UnityEngine; namespace MLAPI.EditorTests { public class NetworkSerializerTests { [Test] public void SerializeBool() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize bool outValueA = true; bool outValueB = false; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); // deserialize bool inValueA = default; bool inValueB = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); } } [Test] public void SerializeChar() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize char outValueA = 'U'; char outValueB = char.MinValue; char outValueC = char.MaxValue; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize char inValueA = default; char inValueB = default; char inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeSbyte() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize sbyte outValueA = -123; sbyte outValueB = sbyte.MinValue; sbyte outValueC = sbyte.MaxValue; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize sbyte inValueA = default; sbyte inValueB = default; sbyte inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeByte() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize byte outValueA = 123; byte outValueB = byte.MinValue; byte outValueC = byte.MaxValue; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize byte inValueA = default; byte inValueB = default; byte inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeShort() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize short outValueA = 12345; short outValueB = short.MinValue; short outValueC = short.MaxValue; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize short inValueA = default; short inValueB = default; short inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeUshort() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize ushort outValueA = 12345; ushort outValueB = ushort.MinValue; ushort outValueC = ushort.MaxValue; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize ushort inValueA = default; ushort inValueB = default; ushort inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeInt() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize int outValueA = 1234567890; int outValueB = int.MinValue; int outValueC = int.MaxValue; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize int inValueA = default; int inValueB = default; int inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeUint() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize uint outValueA = 1234567890; uint outValueB = uint.MinValue; uint outValueC = uint.MaxValue; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize uint inValueA = default; uint inValueB = default; uint inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeLong() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize long outValueA = 9876543210; long outValueB = long.MinValue; long outValueC = long.MaxValue; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize long inValueA = default; long inValueB = default; long inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeUlong() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize ulong outValueA = 9876543210; ulong outValueB = ulong.MinValue; ulong outValueC = ulong.MaxValue; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize ulong inValueA = default; ulong inValueB = default; ulong inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeFloat() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize float outValueA = 12345.6789f; float outValueB = float.MinValue; float outValueC = float.MaxValue; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize float inValueA = default; float inValueB = default; float inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeDouble() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize double outValueA = 12345.6789; double outValueB = double.MinValue; double outValueC = double.MaxValue; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize double inValueA = default; double inValueB = default; double inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeString() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize string outValueA = Guid.NewGuid().ToString("N"); string outValueB = string.Empty; string outValueC = null; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize string inValueA = default; string inValueB = default; string inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeColor() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Color outValueA = Color.black; Color outValueB = Color.white; Color outValueC = Color.red; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize Color inValueA = default; Color inValueB = default; Color inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeColor32() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Color32 outValueA = new Color32(0, 0, 0, byte.MaxValue); Color32 outValueB = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue); Color32 outValueC = new Color32(Byte.MaxValue, 0, 0, byte.MaxValue); var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize Color32 inValueA = default; Color32 inValueB = default; Color32 inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeVector2() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Vector2 outValueA = Vector2.up; Vector2 outValueB = Vector2.negativeInfinity; Vector2 outValueC = Vector2.positiveInfinity; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize Vector2 inValueA = default; Vector2 inValueB = default; Vector2 inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeVector3() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Vector3 outValueA = Vector3.forward; Vector3 outValueB = Vector3.negativeInfinity; Vector3 outValueC = Vector3.positiveInfinity; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize Vector3 inValueA = default; Vector3 inValueB = default; Vector3 inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeVector4() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Vector4 outValueA = Vector4.one; Vector4 outValueB = Vector4.negativeInfinity; Vector4 outValueC = Vector4.positiveInfinity; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize Vector4 inValueA = default; Vector4 inValueB = default; Vector4 inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeQuaternion() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Quaternion outValueA = Quaternion.identity; Quaternion outValueB = Quaternion.Euler(new Vector3(30, 45, -60)); Quaternion outValueC = Quaternion.Euler(new Vector3(90, -90, 180)); var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize Quaternion inValueA = default; Quaternion inValueB = default; Quaternion inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.Greater(Mathf.Abs(Quaternion.Dot(inValueA, outValueA)), 0.999f); Assert.Greater(Mathf.Abs(Quaternion.Dot(inValueB, outValueB)), 0.999f); Assert.Greater(Mathf.Abs(Quaternion.Dot(inValueC, outValueC)), 0.999f); } } [Test] public void SerializeRay() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Ray outValueA = new Ray(Vector3.zero, Vector3.forward); Ray outValueB = new Ray(Vector3.zero, Vector3.left); Ray outValueC = new Ray(Vector3.zero, Vector3.up); var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize Ray inValueA = default; Ray inValueB = default; Ray inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } [Test] public void SerializeRay2D() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Ray2D outValueA = new Ray2D(Vector2.zero, Vector2.up); Ray2D outValueB = new Ray2D(Vector2.zero, Vector2.left); Ray2D outValueC = new Ray2D(Vector2.zero, Vector2.right); var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); // deserialize Ray2D inValueA = default; Ray2D inValueB = default; Ray2D inValueC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); } } private enum EnumA // int { A, B, C } private enum EnumB : byte { X, Y, Z } private enum EnumC : ushort { U, N, I, T, Y } private enum EnumD : ulong { N, E, T } [Test] public void SerializeEnum() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize EnumA outValueA = EnumA.C; EnumB outValueB = EnumB.X; EnumC outValueC = EnumC.N; EnumD outValueD = EnumD.T; EnumD outValueX = (EnumD)123; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outValueA); outSerializer.Serialize(ref outValueB); outSerializer.Serialize(ref outValueC); outSerializer.Serialize(ref outValueD); outSerializer.Serialize(ref outValueX); // deserialize EnumA inValueA = default; EnumB inValueB = default; EnumC inValueC = default; EnumD inValueD = default; EnumD inValueX = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inValueA); inSerializer.Serialize(ref inValueB); inSerializer.Serialize(ref inValueC); inSerializer.Serialize(ref inValueD); inSerializer.Serialize(ref inValueX); // validate Assert.AreEqual(inValueA, outValueA); Assert.AreEqual(inValueB, outValueB); Assert.AreEqual(inValueC, outValueC); Assert.AreEqual(inValueD, outValueD); Assert.AreEqual(inValueX, outValueX); } } [Test] public void SerializeBoolArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize bool[] outArrayA = null; bool[] outArrayB = new bool[0]; bool[] outArrayC = { true, false, true }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize bool[] inArrayA = default; bool[] inArrayB = default; bool[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeCharArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize char[] outArrayA = null; char[] outArrayB = new char[0]; char[] outArrayC = { 'U', 'N', 'I', 'T', 'Y', '\0' }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize char[] inArrayA = default; char[] inArrayB = default; char[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeSbyteArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize sbyte[] outArrayA = null; sbyte[] outArrayB = new sbyte[0]; sbyte[] outArrayC = { -123, sbyte.MinValue, sbyte.MaxValue }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize sbyte[] inArrayA = default; sbyte[] inArrayB = default; sbyte[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeByteArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize byte[] outArrayA = null; byte[] outArrayB = new byte[0]; byte[] outArrayC = { 123, byte.MinValue, byte.MaxValue }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize byte[] inArrayA = default; byte[] inArrayB = default; byte[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeShortArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize short[] outArrayA = null; short[] outArrayB = new short[0]; short[] outArrayC = { 12345, short.MinValue, short.MaxValue }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize short[] inArrayA = default; short[] inArrayB = default; short[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeUshortArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize ushort[] outArrayA = null; ushort[] outArrayB = new ushort[0]; ushort[] outArrayC = { 12345, ushort.MinValue, ushort.MaxValue }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize ushort[] inArrayA = default; ushort[] inArrayB = default; ushort[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeIntArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize int[] outArrayA = null; int[] outArrayB = new int[0]; int[] outArrayC = { 1234567890, int.MinValue, int.MaxValue }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize int[] inArrayA = default; int[] inArrayB = default; int[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeUintArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize uint[] outArrayA = null; uint[] outArrayB = new uint[0]; uint[] outArrayC = { 1234567890, uint.MinValue, uint.MaxValue }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize uint[] inArrayA = default; uint[] inArrayB = default; uint[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeLongArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize long[] outArrayA = null; long[] outArrayB = new long[0]; long[] outArrayC = { 9876543210, long.MinValue, long.MaxValue }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize long[] inArrayA = default; long[] inArrayB = default; long[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeUlongArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize ulong[] outArrayA = null; ulong[] outArrayB = new ulong[0]; ulong[] outArrayC = { 9876543210, ulong.MinValue, ulong.MaxValue }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize ulong[] inArrayA = default; ulong[] inArrayB = default; ulong[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeFloatArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize float[] outArrayA = null; float[] outArrayB = new float[0]; float[] outArrayC = { 12345.6789f, float.MinValue, float.MaxValue }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize float[] inArrayA = default; float[] inArrayB = default; float[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeDoubleArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize double[] outArrayA = null; double[] outArrayB = new double[0]; double[] outArrayC = { 12345.6789, double.MinValue, double.MaxValue }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize double[] inArrayA = default; double[] inArrayB = default; double[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeStringArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize string[] outArrayA = null; string[] outArrayB = new string[0]; string[] outArrayC = { Guid.NewGuid().ToString("N"), String.Empty, null }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize string[] inArrayA = default; string[] inArrayB = default; string[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeColorArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Color[] outArrayA = null; Color[] outArrayB = new Color[0]; Color[] outArrayC = { Color.black, Color.red, Color.white }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize Color[] inArrayA = default; Color[] inArrayB = default; Color[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeColor32Array() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Color32[] outArrayA = null; Color32[] outArrayB = new Color32[0]; Color32[] outArrayC = { new Color32(0, 0, 0, byte.MaxValue), new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, byte.MaxValue), new Color32(Byte.MaxValue, 0, 0, byte.MaxValue) }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize Color32[] inArrayA = default; Color32[] inArrayB = default; Color32[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeVector2Array() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Vector2[] outArrayA = null; Vector2[] outArrayB = new Vector2[0]; Vector2[] outArrayC = { Vector2.up, Vector2.negativeInfinity, Vector2.positiveInfinity }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize Vector2[] inArrayA = default; Vector2[] inArrayB = default; Vector2[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeVector3Array() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Vector3[] outArrayA = null; Vector3[] outArrayB = new Vector3[0]; Vector3[] outArrayC = { Vector3.forward, Vector3.negativeInfinity, Vector3.positiveInfinity }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize Vector3[] inArrayA = default; Vector3[] inArrayB = default; Vector3[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeVector4Array() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Vector4[] outArrayA = null; Vector4[] outArrayB = new Vector4[0]; Vector4[] outArrayC = { Vector4.one, Vector4.negativeInfinity, Vector4.positiveInfinity }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize Vector4[] inArrayA = default; Vector4[] inArrayB = default; Vector4[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeQuaternionArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Quaternion[] outArrayA = null; Quaternion[] outArrayB = new Quaternion[0]; Quaternion[] outArrayC = { Quaternion.identity, Quaternion.Euler(new Vector3(30, 45, -60)), Quaternion.Euler(new Vector3(90, -90, 180)) }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize Quaternion[] inArrayA = default; Quaternion[] inArrayB = default; Quaternion[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.Null(inArrayA); Assert.AreEqual(inArrayB, outArrayB); for (int i = 0; i < outArrayC.Length; ++i) { Assert.Greater(Mathf.Abs(Quaternion.Dot(inArrayC[i], outArrayC[i])), 0.999f); } } } [Test] public void SerializeRayArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Ray[] outArrayA = null; Ray[] outArrayB = new Ray[0]; Ray[] outArrayC = { new Ray(Vector3.zero, Vector3.forward), new Ray(Vector3.zero, Vector3.left), new Ray(Vector3.zero, Vector3.up) }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize Ray[] inArrayA = default; Ray[] inArrayB = default; Ray[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeRay2DArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize Ray2D[] outArrayA = null; Ray2D[] outArrayB = new Ray2D[0]; Ray2D[] outArrayC = { new Ray2D(Vector2.zero, Vector2.up), new Ray2D(Vector2.zero, Vector2.left), new Ray2D(Vector2.zero, Vector2.right) }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize Ray2D[] inArrayA = default; Ray2D[] inArrayB = default; Ray2D[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } [Test] public void SerializeEnumArray() { using (var outStream = PooledNetworkBuffer.Get()) using (var outWriter = PooledNetworkWriter.Get(outStream)) using (var inStream = PooledNetworkBuffer.Get()) using (var inReader = PooledNetworkReader.Get(inStream)) { // serialize EnumA[] outArrayA = null; EnumB[] outArrayB = new EnumB[0]; EnumC[] outArrayC = { EnumC.U, EnumC.N, EnumC.I, EnumC.T, EnumC.Y, (EnumC)128 }; var outSerializer = new NetworkSerializer(outWriter); outSerializer.Serialize(ref outArrayA); outSerializer.Serialize(ref outArrayB); outSerializer.Serialize(ref outArrayC); // deserialize EnumA[] inArrayA = default; EnumB[] inArrayB = default; EnumC[] inArrayC = default; inStream.Write(outStream.ToArray()); inStream.Position = 0; var inSerializer = new NetworkSerializer(inReader); inSerializer.Serialize(ref inArrayA); inSerializer.Serialize(ref inArrayB); inSerializer.Serialize(ref inArrayC); // validate Assert.AreEqual(inArrayA, outArrayA); Assert.AreEqual(inArrayB, outArrayB); Assert.AreEqual(inArrayC, outArrayC); } } } }
using System; using CPUx86 = Cosmos.Assembler.x86; using Label = Cosmos.Assembler.Label; namespace Cosmos.IL2CPU.X86.IL { [Cosmos.IL2CPU.OpCode(ILOpCode.Code.Mul)] public class Mul : ILOp { public Mul(Cosmos.Assembler.Assembler aAsmblr) : base(aAsmblr) { } public override void Execute(MethodInfo aMethod, ILOpCode aOpCode) { var xStackContent = aOpCode.StackPopTypes[0]; var xStackContentSize = SizeOfType(xStackContent); var xStackContentIsFloat = TypeIsFloat(xStackContent); string BaseLabel = GetLabel(aMethod, aOpCode) + "."; DoExecute(xStackContentSize, xStackContentIsFloat, BaseLabel); } public static void DoExecute(uint xStackContentSize, bool xStackContentIsFloat, string aBaseLabel) { if (xStackContentSize > 4) { if (xStackContentIsFloat) { new CPUx86.x87.FloatLoad { DestinationReg = CPUx86.Registers.ESP, Size = 64, DestinationIsIndirect = true }; new CPUx86.Add { SourceValue = 8, DestinationReg = CPUx86.Registers.ESP }; new CPUx86.x87.FloatMul { DestinationReg = CPUx86.Registers.ESP, DestinationIsIndirect = true, Size = 64 }; new CPUx86.x87.FloatStoreAndPop { DestinationReg = CPUx86.Registers.ESP, Size = 64, DestinationIsIndirect = true }; } else { // div of both == LEFT_LOW * RIGHT_LOW + ((LEFT_LOW * RIGHT_HIGH + RIGHT_LOW * LEFT_HIGH) << 32) string Simple32Multiply = aBaseLabel + "Simple32Multiply"; string MoveReturnValue = aBaseLabel + "MoveReturnValue"; // right value // low // SourceReg = CPUx86.Registers.ESP, SourceIsIndirect = true // high // SourceReg = CPUx86.Registers.ESP, SourceIsIndirect = true, SourceDisplacement = 4 // left value // low // SourceReg = CPUx86.Registers.ESP, SourceIsIndirect = true, SourceDisplacement = 8 // high // SourceReg = CPUx86.Registers.ESP, SourceIsIndirect = true, SourceDisplacement = 12 // compair LEFT_HIGH, RIGHT_HIGH , on zero only simple multiply is used //mov RIGHT_HIGH to eax, is useable on Full 64 multiply new CPUx86.Mov { DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.ESP, SourceIsIndirect = true, SourceDisplacement = 4 }; new CPUx86.Or { DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.ESP, SourceIsIndirect = true, SourceDisplacement = 12 }; new CPUx86.ConditionalJump { Condition = CPUx86.ConditionalTestEnum.Zero, DestinationLabel = Simple32Multiply }; // Full 64 Multiply // copy again, or could change EAX //TODO is there an opcode that does OR without change EAX? new CPUx86.Mov { DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.ESP, SourceIsIndirect = true, SourceDisplacement = 4 }; // eax contains already RIGHT_HIGH // multiply with LEFT_LOW new CPUx86.Multiply { DestinationReg = CPUx86.Registers.ESP, DestinationIsIndirect = true, DestinationDisplacement = 8, Size = 32 }; // save result of LEFT_LOW * RIGHT_HIGH new CPUx86.Mov { DestinationReg = CPUx86.Registers.ECX, SourceReg = CPUx86.Registers.EAX }; //mov RIGHT_LOW to eax new CPUx86.Mov { DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.ESP, SourceIsIndirect = true }; // multiply with LEFT_HIGH new CPUx86.Multiply { DestinationReg = CPUx86.Registers.ESP, DestinationIsIndirect = true, DestinationDisplacement = 12, Size = 32 }; // add result of LEFT_LOW * RIGHT_HIGH + RIGHT_LOW + LEFT_HIGH new CPUx86.Add { DestinationReg = CPUx86.Registers.ECX, SourceReg = CPUx86.Registers.EAX }; //mov RIGHT_LOW to eax new CPUx86.Mov { DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.ESP, SourceIsIndirect = true }; // multiply with LEFT_LOW new CPUx86.Multiply { DestinationReg = CPUx86.Registers.ESP, DestinationIsIndirect = true, DestinationDisplacement = 8, Size = 32 }; // add LEFT_LOW * RIGHT_HIGH + RIGHT_LOW + LEFT_HIGH to high dword of last result new CPUx86.Add { DestinationReg = CPUx86.Registers.EDX, SourceReg = CPUx86.Registers.ECX }; new CPUx86.Jump { DestinationLabel = MoveReturnValue }; new Label(Simple32Multiply); //mov RIGHT_LOW to eax new CPUx86.Mov { DestinationReg = CPUx86.Registers.EAX, SourceReg = CPUx86.Registers.ESP, SourceIsIndirect = true }; // multiply with LEFT_LOW new CPUx86.Multiply { DestinationReg = CPUx86.Registers.ESP, DestinationIsIndirect = true, DestinationDisplacement = 8, Size = 32 }; new Label(MoveReturnValue); // move high result to left high new CPUx86.Mov { DestinationReg = CPUx86.Registers.ESP, DestinationIsIndirect = true, DestinationDisplacement = 12, SourceReg = CPUx86.Registers.EDX }; // move low result to left low new CPUx86.Mov { DestinationReg = CPUx86.Registers.ESP, DestinationIsIndirect = true, DestinationDisplacement = 8, SourceReg = CPUx86.Registers.EAX }; // pop right 64 value new CPUx86.Add { DestinationReg = CPUx86.Registers.ESP, SourceValue = 8 }; } } else { if (xStackContentIsFloat) { new CPUx86.SSE.MoveSS { DestinationReg = CPUx86.Registers.XMM0, SourceReg = CPUx86.Registers.ESP, SourceIsIndirect = true }; new CPUx86.Add { DestinationReg = CPUx86.Registers.ESP, SourceValue = 4 }; new CPUx86.SSE.MoveSS { DestinationReg = CPUx86.Registers.XMM1, SourceReg = CPUx86.Registers.ESP, SourceIsIndirect = true }; new CPUx86.SSE.MulSS { DestinationReg = CPUx86.Registers.XMM1, SourceReg = CPUx86.Registers.XMM0 }; new CPUx86.SSE.MoveSS { DestinationReg = CPUx86.Registers.ESP, DestinationIsIndirect = true, SourceReg = CPUx86.Registers.XMM1 }; } else { new CPUx86.Pop { DestinationReg = CPUx86.Registers.EAX }; new CPUx86.Multiply { DestinationReg = CPUx86.Registers.ESP, DestinationIsIndirect = true, Size = 32 }; new CPUx86.Add { DestinationReg = CPUx86.Registers.ESP, SourceValue = 4 }; new CPUx86.Push { DestinationReg = CPUx86.Registers.EAX }; } } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace System.Xml.Tests { public class ChildNodesTests { [Fact] public static void GetChildNodesOfAnElementNodeWithNoChildren() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<doc />"); Assert.Equal(0, xmlDocument.DocumentElement.ChildNodes.Count); } [Fact] public static void GetChildNodesOfAnElementNodeWithAttributesAndChildren() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<doc doc=\"doc\"><doc> doc </doc></doc>"); Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count); } [Fact] public static void GetChildNodesOfAnElementNodeWithAttributesButNoChildNodes() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<doc doc=\"doc\"></doc>"); Assert.Equal(0, xmlDocument.DocumentElement.ChildNodes.Count); } [Fact] public static void AddChildNode() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<doc/>"); var ch = xmlDocument.DocumentElement; var node = xmlDocument.CreateElement("newElem"); var nu = node.FirstChild; node.AppendChild(ch); node.InsertBefore(ch, nu); Assert.Equal(1, node.ChildNodes.Count); Assert.Equal("doc", node.ChildNodes[0].Name); } [Fact] public static void CountMixture1() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<root>text<node1><nestednode/></node1><node2/><?PI pi_info?><!-- comment --></root>"); Assert.Equal(5, xmlDocument.FirstChild.ChildNodes.Count); } [Fact] public static void XmlWithWhitespace() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(@"<a> this-is-a </a>"); Assert.Equal(1, xmlDocument.FirstChild.ChildNodes.Count); } [Fact] public static void ChildNodeOfAttribute() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(@"<a attr1='test' />"); var attr1 = xmlDocument.FirstChild.Attributes[0]; Assert.Equal(1, attr1.ChildNodes.Count); Assert.Equal("test", attr1.FirstChild.Value); } [Fact] public static void DocumentFragmentChildNodes() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(@"<a attr1='test' />"); var fragment = xmlDocument.CreateDocumentFragment(); fragment.AppendChild(xmlDocument.DocumentElement); Assert.Equal(1, fragment.ChildNodes.Count); } [Fact] public static void EmptyElementChildNodeCount() { var xmlDocument = new XmlDocument(); var item = xmlDocument.CreateElement("newElem"); var clonedTrue = item.CloneNode(true); var clonedFalse = item.CloneNode(false); Assert.Equal(0, item.ChildNodes.Count); Assert.Equal(0, clonedTrue.ChildNodes.Count); Assert.Equal(0, clonedFalse.ChildNodes.Count); } [Fact] public static void EmptyAttributeChildNodeCount() { var xmlDocument = new XmlDocument(); var item = xmlDocument.CreateAttribute("newElem"); var clonedTrue = item.CloneNode(true); var clonedFalse = item.CloneNode(false); Assert.Equal(0, item.ChildNodes.Count); Assert.Equal(0, clonedTrue.ChildNodes.Count); Assert.Equal(0, clonedFalse.ChildNodes.Count); } [Fact] public static void TextNodeChildNodeCount() { var xmlDocument = new XmlDocument(); var item = xmlDocument.CreateTextNode("text"); var clonedTrue = item.CloneNode(true); var clonedFalse = item.CloneNode(false); Assert.Equal(0, item.ChildNodes.Count); Assert.Equal(0, clonedTrue.ChildNodes.Count); Assert.Equal(0, clonedFalse.ChildNodes.Count); } [Fact] public static void CommentChildNodeCount() { var xmlDocument = new XmlDocument(); var item = xmlDocument.CreateComment("comment"); var clonedTrue = item.CloneNode(true); var clonedFalse = item.CloneNode(false); Assert.Equal(0, item.ChildNodes.Count); Assert.Equal(0, clonedTrue.ChildNodes.Count); Assert.Equal(0, clonedFalse.ChildNodes.Count); } [Fact] public static void CDataChildNodeCount() { var xmlDocument = new XmlDocument(); var item = xmlDocument.CreateCDataSection("cdata"); var clonedTrue = item.CloneNode(true); var clonedFalse = item.CloneNode(false); Assert.Equal(0, item.ChildNodes.Count); Assert.Equal(0, clonedTrue.ChildNodes.Count); Assert.Equal(0, clonedFalse.ChildNodes.Count); } [Fact] public static void ProcessingInstructionChildNodeCount() { var xmlDocument = new XmlDocument(); var item = xmlDocument.CreateProcessingInstruction("PI", "pi_info"); var clonedTrue = item.CloneNode(true); var clonedFalse = item.CloneNode(false); Assert.Equal(0, item.ChildNodes.Count); Assert.Equal(0, clonedTrue.ChildNodes.Count); Assert.Equal(0, clonedFalse.ChildNodes.Count); } [Fact] public static void EmptyXmlDocument() { XmlDocument xd = new XmlDocument(); Assert.Equal(0, xd.ChildNodes.Count); } [Fact] public static void ListWithMultipleKinds() { var xml = @"<root> text node one <elem1 child1="""" child2=""duu"" child3=""e1;e2;"" child4=""a1"" child5=""goody""> text node two e1; text node three </elem1><!-- comment3 --><?PI3 processing instruction?>e2;<foo /><![CDATA[ <opentag> without an </endtag> and & <! are all ok here ]]><elem2 att1=""id1"" att2=""up"" att3=""attribute3""><a /></elem2><elem2> elem2-text1 <a> this-is-a </a> elem2-text2 e3;e4;<!-- elem2-comment1--> elem2-text3 <b> this-is-b </b> elem2-text4 <?elem2_PI elem2-PI?> elem2-text5 </elem2></root>"; var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); Assert.Equal(9, xmlDocument.DocumentElement.ChildNodes.Count); } [Fact] public static void ElementNodeWithChildButNoAttribute() { var xml = @"<a> this-is-a </a>"; var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(xml); Assert.Equal(1, xmlDocument.DocumentElement.ChildNodes.Count); } [Fact] public static void ReplacingNodeDoesNotChangeChildNodesList() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml(@" <doc doc=""doc""><doc> doc </doc><html>Just for testing purpose</html></doc>"); var newNode = xmlDocument.CreateTextNode("new text node"); var countBefore = xmlDocument.DocumentElement.ChildNodes.Count; xmlDocument.DocumentElement.ReplaceChild(newNode, xmlDocument.DocumentElement.FirstChild); Assert.Equal(countBefore, xmlDocument.DocumentElement.ChildNodes.Count); } [Fact] public static void NestedChildren() { var xmlDocument = new XmlDocument(); xmlDocument.LoadXml("<doc><a><b><c><a><b><c_end></c_end></b></a></c></b></a></doc>"); XmlNode node = xmlDocument.DocumentElement; while (node.HasChildNodes) node = node.ChildNodes[0]; Assert.Equal(0, node.ChildNodes.Count); Assert.Equal("c_end", node.Name); } } }
// 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 { using System.Linq; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// A client for issuing REST requests to the Azure Batch service. /// </summary> public partial class BatchServiceClient : Microsoft.Rest.ServiceClient<BatchServiceClient>, IBatchServiceClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Credentials needed for the client to connect to Azure. /// </summary> public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Client API Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IApplicationOperations. /// </summary> public virtual IApplicationOperations Application { get; private set; } /// <summary> /// Gets the IPoolOperations. /// </summary> public virtual IPoolOperations Pool { get; private set; } /// <summary> /// Gets the IAccountOperations. /// </summary> public virtual IAccountOperations Account { get; private set; } /// <summary> /// Gets the IJobOperations. /// </summary> public virtual IJobOperations Job { get; private set; } /// <summary> /// Gets the ICertificateOperations. /// </summary> public virtual ICertificateOperations Certificate { get; private set; } /// <summary> /// Gets the IFileOperations. /// </summary> public virtual IFileOperations File { get; private set; } /// <summary> /// Gets the IJobScheduleOperations. /// </summary> public virtual IJobScheduleOperations JobSchedule { get; private set; } /// <summary> /// Gets the ITaskOperations. /// </summary> public virtual ITaskOperations Task { get; private set; } /// <summary> /// Gets the IComputeNodeOperations. /// </summary> public virtual IComputeNodeOperations ComputeNode { get; private set; } /// <summary> /// Initializes a new instance of the BatchServiceClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected BatchServiceClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the BatchServiceClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected BatchServiceClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the BatchServiceClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected BatchServiceClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the BatchServiceClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> protected BatchServiceClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the BatchServiceClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public BatchServiceClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the BatchServiceClient class. /// </summary> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public BatchServiceClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the BatchServiceClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public BatchServiceClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the BatchServiceClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Credentials needed for the client to connect to Azure. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public BatchServiceClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } if (credentials == null) { throw new System.ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// An optional partial-method to perform custom initialization. /// </summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.Application = new ApplicationOperations(this); this.Pool = new PoolOperations(this); this.Account = new AccountOperations(this); this.Job = new JobOperations(this); this.Certificate = new CertificateOperations(this); this.File = new FileOperations(this); this.JobSchedule = new JobScheduleOperations(this); this.Task = new TaskOperations(this); this.ComputeNode = new ComputeNodeOperations(this); this.BaseUri = new System.Uri("https://batch.core.windows.net"); this.ApiVersion = "2017-01-01.4.0"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; CustomInitialize(); DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter()); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the SysEstadoCivil class. /// </summary> [Serializable] public partial class SysEstadoCivilCollection : ActiveList<SysEstadoCivil, SysEstadoCivilCollection> { public SysEstadoCivilCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>SysEstadoCivilCollection</returns> public SysEstadoCivilCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { SysEstadoCivil o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Sys_EstadoCivil table. /// </summary> [Serializable] public partial class SysEstadoCivil : ActiveRecord<SysEstadoCivil>, IActiveRecord { #region .ctors and Default Settings public SysEstadoCivil() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public SysEstadoCivil(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public SysEstadoCivil(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public SysEstadoCivil(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Sys_EstadoCivil", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdEstadoCivil = new TableSchema.TableColumn(schema); colvarIdEstadoCivil.ColumnName = "idEstadoCivil"; colvarIdEstadoCivil.DataType = DbType.Int32; colvarIdEstadoCivil.MaxLength = 0; colvarIdEstadoCivil.AutoIncrement = true; colvarIdEstadoCivil.IsNullable = false; colvarIdEstadoCivil.IsPrimaryKey = true; colvarIdEstadoCivil.IsForeignKey = false; colvarIdEstadoCivil.IsReadOnly = false; colvarIdEstadoCivil.DefaultSetting = @""; colvarIdEstadoCivil.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdEstadoCivil); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.String; colvarNombre.MaxLength = 50; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @"('')"; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Sys_EstadoCivil",schema); } } #endregion #region Props [XmlAttribute("IdEstadoCivil")] [Bindable(true)] public int IdEstadoCivil { get { return GetColumnValue<int>(Columns.IdEstadoCivil); } set { SetColumnValue(Columns.IdEstadoCivil, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varNombre) { SysEstadoCivil item = new SysEstadoCivil(); item.Nombre = varNombre; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdEstadoCivil,string varNombre) { SysEstadoCivil item = new SysEstadoCivil(); item.IdEstadoCivil = varIdEstadoCivil; item.Nombre = varNombre; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdEstadoCivilColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string IdEstadoCivil = @"idEstadoCivil"; public static string Nombre = @"nombre"; } #endregion #region Update PK Collections #endregion #region Deep Save #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.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Microsoft.Win32.SafeHandles; internal static partial class Interop { internal static partial class Crypto { private delegate int NegativeSizeReadMethod<in THandle>(THandle handle, byte[] buf, int cBuf); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioTell")] internal static extern int CryptoNative_BioTell(SafeBioHandle bio); internal static int BioTell(SafeBioHandle bio) { int ret = CryptoNative_BioTell(bio); if (ret < 0) { throw CreateOpenSslCryptographicException(); } return ret; } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioSeek")] internal static extern int BioSeek(SafeBioHandle bio, int pos); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509Thumbprint")] private static extern int GetX509Thumbprint(SafeX509Handle x509, byte[] buf, int cBuf); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509NameRawBytes")] private static extern int GetX509NameRawBytes(IntPtr x509Name, byte[] buf, int cBuf); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_ReadX509AsDerFromBio")] internal static extern SafeX509Handle ReadX509AsDerFromBio(SafeBioHandle bio); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509NotBefore")] internal static extern IntPtr GetX509NotBefore(SafeX509Handle x509); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509NotAfter")] internal static extern IntPtr GetX509NotAfter(SafeX509Handle x509); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509CrlNextUpdate")] internal static extern IntPtr GetX509CrlNextUpdate(SafeX509CrlHandle crl); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509Version")] internal static extern int GetX509Version(SafeX509Handle x509); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509SignatureAlgorithm")] internal static extern IntPtr GetX509SignatureAlgorithm(SafeX509Handle x509); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509PublicKeyAlgorithm")] internal static extern IntPtr GetX509PublicKeyAlgorithm(SafeX509Handle x509); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509PublicKeyParameterBytes")] private static extern int GetX509PublicKeyParameterBytes(SafeX509Handle x509, byte[] buf, int cBuf); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509PublicKeyBytes")] internal static extern IntPtr GetX509PublicKeyBytes(SafeX509Handle x509); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509EkuFieldCount")] internal static extern int GetX509EkuFieldCount(SafeEkuExtensionHandle eku); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509EkuField")] internal static extern IntPtr GetX509EkuField(SafeEkuExtensionHandle eku, int loc); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509NameInfo")] internal static extern SafeBioHandle GetX509NameInfo(SafeX509Handle x509, int nameType, [MarshalAs(UnmanagedType.Bool)] bool forIssuer); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetAsn1StringBytes")] private static extern int GetAsn1StringBytes(IntPtr asn1, byte[] buf, int cBuf); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_PushX509StackField")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool PushX509StackField(SafeX509StackHandle stack, SafeX509Handle x509); internal static string GetX509RootStorePath() { return Marshal.PtrToStringAnsi(GetX509RootStorePath_private()); } internal static string GetX509RootStoreFile() { return Marshal.PtrToStringAnsi(GetX509RootStoreFile_private()); } [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509RootStorePath")] private static extern IntPtr GetX509RootStorePath_private(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetX509RootStoreFile")] private static extern IntPtr GetX509RootStoreFile_private(); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SetX509ChainVerifyTime")] private static extern int SetX509ChainVerifyTime( SafeX509StoreCtxHandle ctx, int year, int month, int day, int hour, int minute, int second, [MarshalAs(UnmanagedType.Bool)] bool isDst); [DllImport(Libraries.CryptoNative)] private static extern int CryptoNative_X509StoreSetVerifyTime( SafeX509StoreHandle ctx, int year, int month, int day, int hour, int minute, int second, [MarshalAs(UnmanagedType.Bool)] bool isDst); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_CheckX509IpAddress")] internal static extern int CheckX509IpAddress(SafeX509Handle x509, [In]byte[] addressBytes, int addressLen, string hostname, int cchHostname); [DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_CheckX509Hostname")] internal static extern int CheckX509Hostname(SafeX509Handle x509, string hostname, int cchHostname); internal static byte[] GetAsn1StringBytes(IntPtr asn1) { return GetDynamicBuffer((ptr, buf, i) => GetAsn1StringBytes(ptr, buf, i), asn1); } internal static ArraySegment<byte> RentAsn1StringBytes(IntPtr asn1) { return RentDynamicBuffer((ptr, buf, i) => GetAsn1StringBytes(ptr, buf, i), asn1); } internal static byte[] GetX509Thumbprint(SafeX509Handle x509) { return GetDynamicBuffer((handle, buf, i) => GetX509Thumbprint(handle, buf, i), x509); } internal static X500DistinguishedName LoadX500Name(IntPtr namePtr) { CheckValidOpenSslHandle(namePtr); byte[] buf = GetDynamicBuffer((ptr, buf1, i) => GetX509NameRawBytes(ptr, buf1, i), namePtr); return new X500DistinguishedName(buf); } internal static byte[] GetX509PublicKeyParameterBytes(SafeX509Handle x509) { return GetDynamicBuffer((handle, buf, i) => GetX509PublicKeyParameterBytes(handle, buf, i), x509); } internal static void SetX509ChainVerifyTime(SafeX509StoreCtxHandle ctx, DateTime verifyTime) { // OpenSSL is going to convert our input time to universal, so we should be in Local or // Unspecified (local-assumed). Debug.Assert(verifyTime.Kind != DateTimeKind.Utc, "UTC verifyTime should have been normalized to Local"); int succeeded = SetX509ChainVerifyTime( ctx, verifyTime.Year, verifyTime.Month, verifyTime.Day, verifyTime.Hour, verifyTime.Minute, verifyTime.Second, verifyTime.IsDaylightSavingTime()); if (succeeded != 1) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } } internal static void X509StoreSetVerifyTime(SafeX509StoreHandle ctx, DateTime verifyTime) { // OpenSSL is going to convert our input time to universal, so we should be in Local or // Unspecified (local-assumed). Debug.Assert(verifyTime.Kind != DateTimeKind.Utc, "UTC verifyTime should have been normalized to Local"); int succeeded = CryptoNative_X509StoreSetVerifyTime( ctx, verifyTime.Year, verifyTime.Month, verifyTime.Day, verifyTime.Hour, verifyTime.Minute, verifyTime.Second, verifyTime.IsDaylightSavingTime()); if (succeeded != 1) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } } private static byte[] GetDynamicBuffer<THandle>(NegativeSizeReadMethod<THandle> method, THandle handle) { int negativeSize = method(handle, null, 0); if (negativeSize > 0) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } byte[] bytes = new byte[-negativeSize]; int ret = method(handle, bytes, bytes.Length); if (ret != 1) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } return bytes; } private static ArraySegment<byte> RentDynamicBuffer<THandle>(NegativeSizeReadMethod<THandle> method, THandle handle) { int negativeSize = method(handle, null, 0); if (negativeSize > 0) { throw Interop.Crypto.CreateOpenSslCryptographicException(); } int targetSize = -negativeSize; byte[] bytes = ArrayPool<byte>.Shared.Rent(targetSize); int ret = method(handle, bytes, targetSize); if (ret != 1) { ArrayPool<byte>.Shared.Return(bytes); throw Interop.Crypto.CreateOpenSslCryptographicException(); } return new ArraySegment<byte>(bytes, 0, targetSize); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Xunit; namespace System.Diagnostics.ProcessTests { public class ProcessTests : ProcessTestBase { private void SetAndCheckBasePriority(ProcessPriorityClass exPriorityClass, int priority) { _process.PriorityClass = exPriorityClass; _process.Refresh(); Assert.Equal(priority, _process.BasePriority); } private void AssertNonZeroWindowsZeroUnix(long value) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.NotEqual(0, value); } else { Assert.Equal(0, value); } } [Fact, PlatformSpecific(PlatformID.Windows)] public void TestBasePriorityOnWindows() { ProcessPriorityClass originalPriority = _process.PriorityClass; Assert.Equal(ProcessPriorityClass.Normal, originalPriority); try { // We are not checking for RealTime case here, as RealTime priority process can // preempt the threads of all other processes, including operating system processes // performing important tasks, which may cause the machine to be unresponsive. //SetAndCheckBasePriority(ProcessPriorityClass.RealTime, 24); SetAndCheckBasePriority(ProcessPriorityClass.High, 13); SetAndCheckBasePriority(ProcessPriorityClass.Idle, 4); SetAndCheckBasePriority(ProcessPriorityClass.Normal, 8); } finally { _process.PriorityClass = originalPriority; } } [Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix public void TestBasePriorityOnUnix() { ProcessPriorityClass originalPriority = _process.PriorityClass; Assert.Equal(ProcessPriorityClass.Normal, originalPriority); try { SetAndCheckBasePriority(ProcessPriorityClass.High, -11); SetAndCheckBasePriority(ProcessPriorityClass.Idle, 19); SetAndCheckBasePriority(ProcessPriorityClass.Normal, 0); } finally { _process.PriorityClass = originalPriority; } } [Fact] public void TestEnableRaiseEvents() { { bool isExitedInvoked = false; // Test behavior when EnableRaisingEvent = true; // Ensure event is called. Process p = CreateProcessInfinite(); p.EnableRaisingEvents = true; p.Exited += delegate { isExitedInvoked = true; }; StartSleepKillWait(p); Assert.True(isExitedInvoked, String.Format("TestCanRaiseEvents0001: {0}", "isExited Event not called when EnableRaisingEvent is set to true.")); } { bool isExitedInvoked = false; // Check with the default settings (false, events will not be raised) Process p = CreateProcessInfinite(); p.Exited += delegate { isExitedInvoked = true; }; StartSleepKillWait(p); Assert.False(isExitedInvoked, String.Format("TestCanRaiseEvents0002: {0}", "isExited Event called with the default settings for EnableRaiseEvents")); } { bool isExitedInvoked = false; // Same test, this time explicitly set the property to false Process p = CreateProcessInfinite(); p.EnableRaisingEvents = false; p.Exited += delegate { isExitedInvoked = true; }; ; StartSleepKillWait(p); Assert.False(isExitedInvoked, String.Format("TestCanRaiseEvents0003: {0}", "isExited Event called with the EnableRaiseEvents = false")); } } [Fact] public void TestExitCode() { { Process p = CreateProcess(); p.Start(); Assert.True(p.WaitForExit(WaitInMS)); Assert.Equal(SuccessExitCode, p.ExitCode); } { Process p = CreateProcessInfinite(); StartSleepKillWait(p); Assert.NotEqual(0, p.ExitCode); } } [Fact] public void TestExitTime() { DateTime timeBeforeProcessStart = DateTime.UtcNow; Process p = CreateProcessInfinite(); p.Start(); Assert.Throws<InvalidOperationException>(() => p.ExitTime); p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); Assert.True(p.ExitTime.ToUniversalTime() >= timeBeforeProcessStart, "TestExitTime is incorrect."); } [Fact] public void TestId() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(_process.Id, Interop.GetProcessId(_process.SafeHandle)); } else { IEnumerable<int> testProcessIds = Process.GetProcessesByName(HostRunner).Select(p => p.Id); Assert.Contains(_process.Id, testProcessIds); } } [Fact] public void TestHasExited() { { Process p = CreateProcess(); p.Start(); Assert.True(p.WaitForExit(WaitInMS)); Assert.True(p.HasExited, "TestHasExited001 failed"); } { Process p = CreateProcessInfinite(); p.Start(); try { Assert.False(p.HasExited, "TestHasExited002 failed"); } finally { p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } Assert.True(p.HasExited, "TestHasExited003 failed"); } } [Fact] public void TestMachineName() { // Checking that the MachineName returns some value. Assert.NotNull(_process.MachineName); } [Fact, PlatformSpecific(~PlatformID.OSX)] public void TestMainModuleOnNonOSX() { string fileName = "corerun"; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) fileName = "CoreRun.exe"; Process p = Process.GetCurrentProcess(); Assert.True(p.Modules.Count > 0); Assert.Equal(fileName, p.MainModule.ModuleName); Assert.EndsWith(fileName, p.MainModule.FileName); Assert.Equal(string.Format("System.Diagnostics.ProcessModule ({0})", fileName), p.MainModule.ToString()); } [Fact] public void TestMaxWorkingSet() { using (Process p = Process.GetCurrentProcess()) { Assert.True((long)p.MaxWorkingSet > 0); Assert.True((long)p.MinWorkingSet >= 0); } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return; // doesn't support getting/setting working set for other processes long curValue = (long)_process.MaxWorkingSet; Assert.True(curValue >= 0); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { _process.MaxWorkingSet = (IntPtr)((int)curValue + 1024); IntPtr min, max; uint flags; Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags); curValue = (int)max; _process.Refresh(); Assert.Equal(curValue, (int)_process.MaxWorkingSet); } finally { _process.MaxWorkingSet = (IntPtr)curValue; } } } [Fact] public void TestMinWorkingSet() { using (Process p = Process.GetCurrentProcess()) { Assert.True((long)p.MaxWorkingSet > 0); Assert.True((long)p.MinWorkingSet >= 0); } if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return; // doesn't support getting/setting working set for other processes long curValue = (long)_process.MinWorkingSet; Assert.True(curValue >= 0); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { try { _process.MinWorkingSet = (IntPtr)((int)curValue - 1024); IntPtr min, max; uint flags; Interop.GetProcessWorkingSetSizeEx(_process.SafeHandle, out min, out max, out flags); curValue = (int)min; _process.Refresh(); Assert.Equal(curValue, (int)_process.MinWorkingSet); } finally { _process.MinWorkingSet = (IntPtr)curValue; } } } [Fact] public void TestModules() { ProcessModuleCollection moduleCollection = Process.GetCurrentProcess().Modules; foreach (ProcessModule pModule in moduleCollection) { // Validated that we can get a value for each of the following. Assert.NotNull(pModule); Assert.NotEqual(IntPtr.Zero, pModule.BaseAddress); Assert.NotNull(pModule.FileName); Assert.NotNull(pModule.ModuleName); // Just make sure these don't throw IntPtr addr = pModule.EntryPointAddress; int memSize = pModule.ModuleMemorySize; } } [Fact] public void TestNonpagedSystemMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.NonpagedSystemMemorySize64); } [Fact] public void TestPagedMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PagedMemorySize64); } [Fact] public void TestPagedSystemMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PagedSystemMemorySize64); } [Fact] public void TestPeakPagedMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PeakPagedMemorySize64); } [Fact] public void TestPeakVirtualMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PeakVirtualMemorySize64); } [Fact] public void TestPeakWorkingSet64() { AssertNonZeroWindowsZeroUnix(_process.PeakWorkingSet64); } [Fact] public void TestPrivateMemorySize64() { AssertNonZeroWindowsZeroUnix(_process.PrivateMemorySize64); } [Fact] public void TestVirtualMemorySize64() { Assert.True(_process.VirtualMemorySize64 > 0); } [Fact] public void TestWorkingSet64() { Assert.True(_process.WorkingSet64 > 0); } [Fact] public void TestProcessorTime() { Assert.True(_process.UserProcessorTime.TotalSeconds >= 0); Assert.True(_process.PrivilegedProcessorTime.TotalSeconds >= 0); double processorTimeBeforeSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds; double processorTimeAtHalfSpin = 0; // Perform loop to occupy cpu, takes less than a second. int i = int.MaxValue / 16; while (i > 0) { i--; if (i == int.MaxValue / 32) processorTimeAtHalfSpin = Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds; } Assert.InRange(processorTimeAtHalfSpin, processorTimeBeforeSpin, Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds); } [Fact] public void TestProcessStartTime() { DateTime timeBeforeCreatingProcess = DateTime.UtcNow; Process p = CreateProcessInfinite(); Assert.Throws<InvalidOperationException>(() => p.StartTime); try { p.Start(); // Time in unix, is measured in jiffies, which is incremented by one for every timer interrupt since the boot time. // Thus, because there are HZ timer interrupts in a second, there are HZ jiffies in a second. Hence 1\HZ, will // be the resolution of system timer. The lowest value of HZ on unix is 100, hence the timer resolution is 10 ms. // On Windows, timer resolution is 15 ms from MSDN DateTime.Now. Hence, allowing error in 15ms [max(10,15)]. long intervalTicks = new TimeSpan(0, 0, 0, 0, 15).Ticks; long beforeTicks = timeBeforeCreatingProcess.Ticks - intervalTicks; try { // Ensure the process has started, p.id throws InvalidOperationException, if the process has not yet started. Assert.Equal(p.Id, Process.GetProcessById(p.Id).Id); long startTicks = p.StartTime.ToUniversalTime().Ticks; long afterTicks = DateTime.UtcNow.Ticks + intervalTicks; Assert.InRange(startTicks, beforeTicks, afterTicks); } catch (InvalidOperationException) { Assert.True(p.StartTime.ToUniversalTime().Ticks > beforeTicks); } } finally { if (!p.HasExited) p.Kill(); Assert.True(p.WaitForExit(WaitInMS)); } } [Fact] [PlatformSpecific(~PlatformID.OSX)] // getting/setting affinity not supported on OSX public void TestProcessorAffinity() { IntPtr curProcessorAffinity = _process.ProcessorAffinity; try { _process.ProcessorAffinity = new IntPtr(0x1); Assert.Equal(new IntPtr(0x1), _process.ProcessorAffinity); } finally { _process.ProcessorAffinity = curProcessorAffinity; Assert.Equal(curProcessorAffinity, _process.ProcessorAffinity); } } [Fact] public void TestPriorityBoostEnabled() { bool isPriorityBoostEnabled = _process.PriorityBoostEnabled; try { _process.PriorityBoostEnabled = true; Assert.True(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled001 failed"); _process.PriorityBoostEnabled = false; Assert.False(_process.PriorityBoostEnabled, "TestPriorityBoostEnabled002 failed"); } finally { _process.PriorityBoostEnabled = isPriorityBoostEnabled; } } [Fact, PlatformSpecific(PlatformID.AnyUnix), OuterLoop] // This test requires admin elevation on Unix public void TestPriorityClassUnix() { ProcessPriorityClass priorityClass = _process.PriorityClass; try { _process.PriorityClass = ProcessPriorityClass.High; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High); _process.PriorityClass = ProcessPriorityClass.Normal; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal); } finally { _process.PriorityClass = priorityClass; } } [Fact, PlatformSpecific(PlatformID.Windows)] public void TestPriorityClassWindows() { ProcessPriorityClass priorityClass = _process.PriorityClass; try { _process.PriorityClass = ProcessPriorityClass.High; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.High); _process.PriorityClass = ProcessPriorityClass.Normal; Assert.Equal(_process.PriorityClass, ProcessPriorityClass.Normal); } finally { _process.PriorityClass = priorityClass; } } [Fact] public void TestInvalidPriorityClass() { Process p = new Process(); Assert.Throws<ArgumentException>(() => { p.PriorityClass = ProcessPriorityClass.Normal | ProcessPriorityClass.Idle; }); } [Fact] public void TestProcessName() { Assert.Equal(_process.ProcessName, HostRunner, StringComparer.OrdinalIgnoreCase); } [Fact] public void TestSafeHandle() { Assert.False(_process.SafeHandle.IsInvalid); } [Fact] public void TestSessionId() { uint sessionId; if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Interop.ProcessIdToSessionId((uint)_process.Id, out sessionId); } else { sessionId = (uint)Interop.getsid(_process.Id); } Assert.Equal(sessionId, (uint)_process.SessionId); } [Fact] public void TestGetCurrentProcess() { Process current = Process.GetCurrentProcess(); Assert.NotNull(current); int currentProcessId = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? Interop.GetCurrentProcessId() : Interop.getpid(); Assert.Equal(currentProcessId, current.Id); } [Fact] public void TestGetProcessById() { Process p = Process.GetProcessById(_process.Id); Assert.Equal(_process.Id, p.Id); Assert.Equal(_process.ProcessName, p.ProcessName); } [Fact] public void TestGetProcesses() { Process currentProcess = Process.GetCurrentProcess(); // Get all the processes running on the machine, and check if the current process is one of them. var foundCurrentProcess = (from p in Process.GetProcesses() where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName)) select p).Any(); Assert.True(foundCurrentProcess, "TestGetProcesses001 failed"); foundCurrentProcess = (from p in Process.GetProcesses(currentProcess.MachineName) where (p.Id == currentProcess.Id) && (p.ProcessName.Equals(currentProcess.ProcessName)) select p).Any(); Assert.True(foundCurrentProcess, "TestGetProcesses002 failed"); } [Fact] public void TestGetProcessesByName() { // Get the current process using its name Process currentProcess = Process.GetCurrentProcess(); Assert.True(Process.GetProcessesByName(currentProcess.ProcessName).Count() > 0, "TestGetProcessesByName001 failed"); Assert.True(Process.GetProcessesByName(currentProcess.ProcessName, currentProcess.MachineName).Count() > 0, "TestGetProcessesByName001 failed"); } public static IEnumerable<object[]> GetTestProcess() { Process currentProcess = Process.GetCurrentProcess(); yield return new object[] { currentProcess, Process.GetProcessById(currentProcess.Id, "127.0.0.1") }; yield return new object[] { currentProcess, Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1").Where(p => p.Id == currentProcess.Id).Single() }; } [Theory, PlatformSpecific(PlatformID.Windows)] [MemberData("GetTestProcess")] public void TestProcessOnRemoteMachineWindows(Process currentProcess, Process remoteProcess) { Assert.Equal(currentProcess.Id, remoteProcess.Id); Assert.Equal(currentProcess.BasePriority, remoteProcess.BasePriority); Assert.Equal(currentProcess.EnableRaisingEvents, remoteProcess.EnableRaisingEvents); Assert.Equal("127.0.0.1", remoteProcess.MachineName); // This property throws exception only on remote processes. Assert.Throws<NotSupportedException>(() => remoteProcess.MainModule); } [Fact, PlatformSpecific(PlatformID.AnyUnix)] public void TestProcessOnRemoteMachineUnix() { Process currentProcess = Process.GetCurrentProcess(); Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessesByName(currentProcess.ProcessName, "127.0.0.1")); Assert.Throws<PlatformNotSupportedException>(() => Process.GetProcessById(currentProcess.Id, "127.0.0.1")); } [Fact] public void TestStartInfo() { { Process process = CreateProcessInfinite(); process.Start(); Assert.Equal(HostRunner, process.StartInfo.FileName); process.Kill(); Assert.True(process.WaitForExit(WaitInMS)); } { Process process = CreateProcessInfinite(); process.Start(); Assert.Throws<System.InvalidOperationException>(() => (process.StartInfo = new ProcessStartInfo())); process.Kill(); Assert.True(process.WaitForExit(WaitInMS)); } { Process process = new Process(); process.StartInfo = new ProcessStartInfo(TestConsoleApp); Assert.Equal(TestConsoleApp, process.StartInfo.FileName); } { Process process = new Process(); Assert.Throws<ArgumentNullException>(() => process.StartInfo = null); } { Process process = Process.GetCurrentProcess(); Assert.Throws<System.InvalidOperationException>(() => process.StartInfo); } } // [Fact] // uncomment for diagnostic purposes to list processes to console public void TestDiagnosticsWithConsoleWriteLine() { foreach (var p in Process.GetProcesses().OrderBy(p => p.Id)) { Console.WriteLine("{0} : \"{1}\" (Threads: {2})", p.Id, p.ProcessName, p.Threads.Count); p.Dispose(); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace DataService.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// UI logic. Manages all UI, raycasting, touch/mouse events passing and uiItem event notifications. /// For any tk2dUIItem to work there needs to be a tk2dUIManager in the scene /// </summary> [AddComponentMenu("2D Toolkit/UI/Core/tk2dUIManager")] public class tk2dUIManager : MonoBehaviour { public static double version = 1.0; public static int releaseId = 0; // < -10000 = alpha, other negative = beta release, 0 = final, positive = final patch /// <summary> /// Used to reference tk2dUIManager without a direct reference via singleton structure (will not auto-create and only one can exist at a time) /// </summary> private static tk2dUIManager instance; public static tk2dUIManager Instance { get { if (instance == null) { instance = FindObjectOfType(typeof(tk2dUIManager)) as tk2dUIManager; if (instance == null) { GameObject go = new GameObject("tk2dUIManager"); instance = go.AddComponent<tk2dUIManager>(); } } return instance; } } public static tk2dUIManager Instance__NoCreate { get { return instance; } } /// <summary> /// UICamera which raycasts for mouse/touch inputs are cast from /// </summary> [SerializeField] #pragma warning disable 649 private Camera uiCamera; #pragma warning restore 649 public Camera UICamera { get { return uiCamera; } set { uiCamera = value; } } public Camera GetUICameraForControl( GameObject go ) { int layer = 1 << go.layer; foreach (tk2dUICamera camera in allCameras) { if ((camera.FilteredMask & layer) != 0) { return camera.HostCamera; } } Debug.LogError("Unable to find UI camera for " + go.name); return null; } static List<tk2dUICamera> allCameras = new List<tk2dUICamera>(); List<tk2dUICamera> sortedCameras = new List<tk2dUICamera>(); public static void RegisterCamera(tk2dUICamera cam) { allCameras.Add(cam); } public static void UnregisterCamera(tk2dUICamera cam) { allCameras.Remove(cam); } /// <summary> /// Which layer the raycast will be done using. Will ignore others /// </summary> public LayerMask raycastLayerMask = -1; private bool inputEnabled = true; /// <summary> /// Used to disable user input /// </summary> public bool InputEnabled { get { return inputEnabled; } set { if (inputEnabled && !value) //disable current presses/hovers { SortCameras(); inputEnabled = value; if (useMultiTouch) { CheckMultiTouchInputs(); } else { CheckInputs(); } } else { inputEnabled = value; } } } /// <summary> /// If hover events are to be tracked. If you don't not need hover events disable for increased performance (less raycasting). /// Only works when using mouse and multi-touch is disabled (tk2dUIManager.useMultiTouch) /// </summary> public bool areHoverEventsTracked = true; //if disable no hover events will be tracked (less overhead), only effects if using mouse private tk2dUIItem pressedUIItem = null; /// <summary> /// Most recent pressedUIItem (if one is pressed). If multi-touch gets the most recent /// </summary> public tk2dUIItem PressedUIItem { get { //if multi-touch return the last item (most recent touch) if (useMultiTouch) { if (pressedUIItems.Length > 0) { return pressedUIItems[pressedUIItems.Length-1]; } else { return null; } } else { return pressedUIItem; } } } /// <summary> /// All currently pressed down UIItems if using multi-touch /// </summary> public tk2dUIItem[] PressedUIItems { get { return pressedUIItems; } } private tk2dUIItem overUIItem = null; //current hover over uiItem private tk2dUITouch firstPressedUIItemTouch; //used to determine deltas private bool checkForHovers = true; //if internal we are checking for hovers /// <summary> /// Use multi-touch. Only enable if you need multi-touch support. When multi-touch is enabled, hover events are disabled. /// Multi-touch disable will provide better performance and accuracy. /// </summary> [SerializeField] private bool useMultiTouch = false; public bool UseMultiTouch { get { return useMultiTouch; } set { if (useMultiTouch != value && inputEnabled) //changed { InputEnabled = false; //clears existing useMultiTouch = value; InputEnabled = true; } else { useMultiTouch = value; } } } //multi-touch specifics private const int MAX_MULTI_TOUCH_COUNT = 5; //number of touches at the same time private tk2dUITouch[] allTouches = new tk2dUITouch[MAX_MULTI_TOUCH_COUNT]; //all multi-touches private List<tk2dUIItem> prevPressedUIItemList = new List<tk2dUIItem>(); //previous pressed and still pressed UIItems private tk2dUIItem[] pressedUIItems = new tk2dUIItem[MAX_MULTI_TOUCH_COUNT]; //pressed UIItem on the this frame private int touchCounter = 0; //touchs counter private Vector2 mouseDownFirstPos = Vector2.zero; //used to determine mouse position deltas while in multi-touch //end multi-touch specifics private const string MOUSE_WHEEL_AXES_NAME = "Mouse ScrollWheel"; //Input name of mouse scroll wheel //for update loop private tk2dUITouch primaryTouch = new tk2dUITouch(); //main touch (generally began, or actively press) private tk2dUITouch secondaryTouch = new tk2dUITouch(); //secondary touches (generally other fingers) private tk2dUITouch resultTouch = new tk2dUITouch(); //which touch is selected between primary and secondary private tk2dUIItem hitUIItem; //current uiItem hit private RaycastHit hit; private Ray ray; //for update loop (multi-touch) private tk2dUITouch currTouch; private tk2dUIItem currPressedItem; private tk2dUIItem prevPressedItem; /// <summary> /// Only any touch began or mouse click /// </summary> public event System.Action OnAnyPress; /// <summary> /// Fired at the end of every update /// </summary> public event System.Action OnInputUpdate; /// <summary> /// On mouse scroll wheel change (return direction of mouse scroll wheel change) /// </summary> public event System.Action<float> OnScrollWheelChange; void SortCameras() { sortedCameras.Clear(); foreach (tk2dUICamera c in allCameras) { if (c != null) { sortedCameras.Add( c ); } } // Largest depth gets priority sortedCameras.Sort( (a, b) => b.camera.depth.CompareTo( a.camera.depth ) ); } void Awake() { if (instance == null) { instance = this; if (Application.isPlaying) { DontDestroyOnLoad( gameObject ); } } else { //can only be one tk2dUIManager at one-time, if another one is found Destroy it if (instance != this) { Debug.Log("Discarding unnecessary tk2dUIManager instance."); return; } } tk2dUITime.Init(); Setup(); } void Start() { if (uiCamera != null && uiCamera.GetComponent<tk2dUICamera>() == null) { Debug.Log("It is no longer necessary to hook up a camera to the tk2dUIManager. You can simply attach a tk2dUICamera script to the cameras that interact with UI."); // Handle registration properly tk2dUICamera cam = uiCamera.gameObject.AddComponent<tk2dUICamera>(); cam.AssignRaycastLayerMask( raycastLayerMask ); uiCamera = null; } if (allCameras.Count == 0) { Debug.LogError("Unable to find any tk2dUICameras, and no cameras are connected to the tk2dUIManager. You will not be able to interact with the UI."); } } private void Setup() { if (!areHoverEventsTracked) { checkForHovers = false; } } void Update() { tk2dUITime.Update(); if (inputEnabled) { SortCameras(); if (useMultiTouch) { CheckMultiTouchInputs(); } else { CheckInputs(); } if (OnInputUpdate != null) { OnInputUpdate(); } if (OnScrollWheelChange != null) { float mouseWheel = Input.GetAxis(MOUSE_WHEEL_AXES_NAME); if (mouseWheel != 0) { OnScrollWheelChange(mouseWheel); } } } } //checks for inputs (non-multi-touch) private void CheckInputs() { bool isPrimaryTouchFound = false; bool isSecondaryTouchFound = false; bool isAnyPressBeganRecorded = false; primaryTouch = new tk2dUITouch(); secondaryTouch = new tk2dUITouch(); resultTouch = new tk2dUITouch(); hitUIItem = null; if (inputEnabled) { if (Input.touchCount > 0) { foreach (Touch touch in Input.touches) { if (touch.phase == TouchPhase.Began) { primaryTouch = new tk2dUITouch(touch); isPrimaryTouchFound = true; isAnyPressBeganRecorded = true; } else if (pressedUIItem != null && touch.fingerId == firstPressedUIItemTouch.fingerId) { secondaryTouch = new tk2dUITouch(touch); isSecondaryTouchFound = true; } } checkForHovers = false; } else { if (Input.GetMouseButtonDown(0)) { primaryTouch = new tk2dUITouch(TouchPhase.Began, tk2dUITouch.MOUSE_POINTER_FINGER_ID, Input.mousePosition, Vector2.zero, 0); isPrimaryTouchFound = true; isAnyPressBeganRecorded = true; } else if (Input.GetMouseButton(0) || Input.GetMouseButtonUp(0)) { Vector2 deltaPosition = Vector2.zero; TouchPhase mousePhase = TouchPhase.Moved; if (pressedUIItem != null) { deltaPosition = firstPressedUIItemTouch.position - new Vector2(Input.mousePosition.x, Input.mousePosition.y); } if (Input.GetMouseButtonUp(0)) { mousePhase = TouchPhase.Ended; } else if (deltaPosition == Vector2.zero) { mousePhase = TouchPhase.Stationary; } secondaryTouch = new tk2dUITouch(mousePhase, tk2dUITouch.MOUSE_POINTER_FINGER_ID, Input.mousePosition, deltaPosition, tk2dUITime.deltaTime); isSecondaryTouchFound = true; } } } if (isPrimaryTouchFound) { resultTouch = primaryTouch; } else if (isSecondaryTouchFound) { resultTouch = secondaryTouch; } if (isPrimaryTouchFound || isSecondaryTouchFound) //focus touch found { hitUIItem = RaycastForUIItem(resultTouch.position); if (resultTouch.phase == TouchPhase.Began) { if (pressedUIItem != null) { pressedUIItem.CurrentOverUIItem(hitUIItem); if (pressedUIItem != hitUIItem) { pressedUIItem.Release(); pressedUIItem = null; } else { firstPressedUIItemTouch = resultTouch; //just incase touch changed } } if (hitUIItem != null) { hitUIItem.Press(resultTouch); } pressedUIItem = hitUIItem; firstPressedUIItemTouch = resultTouch; } else if (resultTouch.phase == TouchPhase.Ended) { if (pressedUIItem != null) { pressedUIItem.CurrentOverUIItem(hitUIItem); pressedUIItem.UpdateTouch(resultTouch); pressedUIItem.Release(); pressedUIItem = null; } } else { if (pressedUIItem != null) { pressedUIItem.CurrentOverUIItem(hitUIItem); pressedUIItem.UpdateTouch(resultTouch); } } } else //no touches found { if (pressedUIItem != null) { pressedUIItem.CurrentOverUIItem(null); pressedUIItem.Release(); pressedUIItem = null; } } //only if hover events are enabled and only if no touch events have ever been recorded if (checkForHovers) { if (inputEnabled) //if input enabled and mouse button is not currently down { if (!isPrimaryTouchFound && !isSecondaryTouchFound && hitUIItem == null && !Input.GetMouseButton(0)) //if raycast for a button has not yet been done { hitUIItem = RaycastForUIItem( Input.mousePosition ); } else if (Input.GetMouseButton(0)) //if mouse button is down clear it { hitUIItem = null; } } if (hitUIItem != null) { if (hitUIItem.isHoverEnabled) { bool wasPrevOverFound = hitUIItem.HoverOver(overUIItem); if (!wasPrevOverFound && overUIItem != null) { overUIItem.HoverOut(hitUIItem); } overUIItem = hitUIItem; } else { if (overUIItem != null) { overUIItem.HoverOut(null); } } } else { if (overUIItem != null) { overUIItem.HoverOut(null); } } } if (isAnyPressBeganRecorded) { if (OnAnyPress != null) { OnAnyPress(); } } } //checks for inputs (multi-touch) private void CheckMultiTouchInputs() { bool isAnyPressBeganRecorded = false; int prevFingerID = -1; bool wasPrevTouchFound = false; bool isNewlyPressed = false; touchCounter = 0; if (inputEnabled) { if (Input.touchCount > 0) { foreach (Touch touch in Input.touches) { if (touchCounter < MAX_MULTI_TOUCH_COUNT) { allTouches[touchCounter] = new tk2dUITouch(touch); touchCounter++; } else { break; } } } else { if (Input.GetMouseButtonDown(0)) { allTouches[touchCounter] = new tk2dUITouch(TouchPhase.Began, tk2dUITouch.MOUSE_POINTER_FINGER_ID, Input.mousePosition, Vector2.zero, 0); mouseDownFirstPos = Input.mousePosition; touchCounter++; } else if (Input.GetMouseButton(0) || Input.GetMouseButtonUp(0)) { Vector2 deltaPosition = mouseDownFirstPos - new Vector2(Input.mousePosition.x, Input.mousePosition.y); TouchPhase mousePhase = TouchPhase.Moved; if (Input.GetMouseButtonUp(0)) { mousePhase = TouchPhase.Ended; } else if (deltaPosition == Vector2.zero) { mousePhase = TouchPhase.Stationary; } allTouches[touchCounter] = new tk2dUITouch(mousePhase, tk2dUITouch.MOUSE_POINTER_FINGER_ID, Input.mousePosition, deltaPosition, tk2dUITime.deltaTime); touchCounter++; } } } for (int p = 0; p < touchCounter; p++) { pressedUIItems[p] = RaycastForUIItem(allTouches[p].position); } //deals with all the previous presses for (int f=0; f<prevPressedUIItemList.Count; f++) { prevPressedItem = prevPressedUIItemList[f]; if (prevPressedItem != null) { prevFingerID = prevPressedItem.Touch.fingerId; wasPrevTouchFound=false; for (int t = 0; t < touchCounter; t++) { currTouch = allTouches[t]; if (currTouch.fingerId == prevFingerID) { wasPrevTouchFound=true; currPressedItem = pressedUIItems[t]; if (currTouch.phase == TouchPhase.Began) { prevPressedItem.CurrentOverUIItem(currPressedItem); if (prevPressedItem != currPressedItem) { prevPressedItem.Release(); prevPressedUIItemList.RemoveAt(f); f--; } } else if (currTouch.phase == TouchPhase.Ended) { prevPressedItem.CurrentOverUIItem(currPressedItem); prevPressedItem.UpdateTouch(currTouch); prevPressedItem.Release(); prevPressedUIItemList.RemoveAt(f); f--; } else { prevPressedItem.CurrentOverUIItem(currPressedItem); prevPressedItem.UpdateTouch(currTouch); } break; } } if(!wasPrevTouchFound) { prevPressedItem.CurrentOverUIItem(null); prevPressedItem.Release(); prevPressedUIItemList.RemoveAt(f); f--; } } } for (int f = 0; f < touchCounter; f++) { currPressedItem = pressedUIItems[f]; currTouch = allTouches[f]; if (currTouch.phase == TouchPhase.Began) { if (currPressedItem != null) { isNewlyPressed = currPressedItem.Press(currTouch); if (isNewlyPressed) { prevPressedUIItemList.Add(currPressedItem); } } isAnyPressBeganRecorded = true; } } if (isAnyPressBeganRecorded) { if (OnAnyPress != null) { OnAnyPress(); } } } tk2dUIItem RaycastForUIItem( Vector2 screenPos ) { foreach (tk2dUICamera currCamera in sortedCameras) { ray = currCamera.HostCamera.ScreenPointToRay( screenPos ); if (Physics.Raycast( ray, out hit, currCamera.HostCamera.farClipPlane, currCamera.FilteredMask )) { return hit.collider.GetComponent<tk2dUIItem>(); } } return null; } public void OverrideClearAllChildrenPresses(tk2dUIItem item) { if (useMultiTouch) { tk2dUIItem tempUIItem; for (int n = 0; n < pressedUIItems.Length; n++) { tempUIItem = pressedUIItems[n]; if (tempUIItem!=null) { if (item.CheckIsUIItemChildOfMe(tempUIItem)) { tempUIItem.CurrentOverUIItem(item); } } } } else { if (pressedUIItem != null) { if (item.CheckIsUIItemChildOfMe(pressedUIItem)) { pressedUIItem.CurrentOverUIItem(item); } } } } }
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System.IO; using NUnit.Framework; namespace DiscUtils.Partitions { [TestFixture] public class BiosPartitionTableTest { [Test] public void Initialize() { long capacity = 3 * 1024 * 1024; SparseMemoryStream ms = new SparseMemoryStream(); ms.SetLength(capacity); Geometry geom = Geometry.FromCapacity(capacity); BiosPartitionTable table = BiosPartitionTable.Initialize(ms, geom); Assert.AreEqual(0, table.Count); } [Test] public void CreateWholeDisk() { long capacity = 3 * 1024 * 1024; SparseMemoryStream ms = new SparseMemoryStream(); ms.SetLength(capacity); Geometry geom = Geometry.FromCapacity(capacity); BiosPartitionTable table = BiosPartitionTable.Initialize(ms, geom); int idx = table.Create(WellKnownPartitionType.WindowsFat, true); // Make sure the partition fills all but the first track on the disk. Assert.AreEqual(geom.TotalSectors, table[idx].SectorCount + geom.SectorsPerTrack); // Make sure FAT16 was selected for a disk of this size Assert.AreEqual(BiosPartitionTypes.Fat16, table[idx].BiosType); // Make sure partition starts where expected Assert.AreEqual(new ChsAddress(0, 1, 1), ((BiosPartitionInfo)table[idx]).Start); // Make sure partition ends at end of disk Assert.AreEqual(geom.ToLogicalBlockAddress(geom.LastSector), table[idx].LastSector); Assert.AreEqual(geom.LastSector, ((BiosPartitionInfo)table[idx]).End); // Make sure the 'active' flag made it through... Assert.IsTrue(((BiosPartitionInfo)table[idx]).IsActive); // Make sure the partition index is Zero Assert.AreEqual(0, ((BiosPartitionInfo)table[idx]).PrimaryIndex); } [Test] public void CreateWholeDiskAligned() { long capacity = 3 * 1024 * 1024; SparseMemoryStream ms = new SparseMemoryStream(); ms.SetLength(capacity); Geometry geom = Geometry.FromCapacity(capacity); BiosPartitionTable table = BiosPartitionTable.Initialize(ms, geom); int idx = table.CreateAligned(WellKnownPartitionType.WindowsFat, true, 64 * 1024); Assert.AreEqual(0, table[idx].FirstSector % 128); Assert.AreEqual(0, (table[idx].LastSector + 1) % 128); Assert.Greater(table[idx].SectorCount * 512, capacity * 0.9); // Make sure the partition index is Zero Assert.AreEqual(0, ((BiosPartitionInfo)table[idx]).PrimaryIndex); } [Test] public void CreateBySize() { long capacity = 3 * 1024 * 1024; SparseMemoryStream ms = new SparseMemoryStream(); ms.SetLength(capacity); Geometry geom = Geometry.FromCapacity(capacity); BiosPartitionTable table = BiosPartitionTable.Initialize(ms, geom); int idx = table.Create(2 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); // Make sure the partition is within 10% of the size requested. Assert.That((2 * 1024 * 2) * 0.9 < table[idx].SectorCount); Assert.AreEqual(geom.ToLogicalBlockAddress(new ChsAddress(0, 1, 1)), table[idx].FirstSector); Assert.AreEqual(geom.HeadsPerCylinder - 1, geom.ToChsAddress((int)table[idx].LastSector).Head); Assert.AreEqual(geom.SectorsPerTrack, geom.ToChsAddress((int)table[idx].LastSector).Sector); } [Test] public void CreateBySizeInGap() { SparseMemoryStream ms = new SparseMemoryStream(); Geometry geom = new Geometry(15, 30, 63); ms.SetLength(geom.Capacity); BiosPartitionTable table = BiosPartitionTable.Initialize(ms, geom); Assert.AreEqual(0, table.CreatePrimaryByCylinder(0, 4, 33, false)); Assert.AreEqual(1, table.CreatePrimaryByCylinder(10, 14, 33, false)); table.Create(geom.ToLogicalBlockAddress(new ChsAddress(4, 0, 1)) * 512, WellKnownPartitionType.WindowsFat, true); } [Test] public void CreateBySizeInGapAligned() { SparseMemoryStream ms = new SparseMemoryStream(); Geometry geom = new Geometry(15, 30, 63); ms.SetLength(geom.Capacity); BiosPartitionTable table = BiosPartitionTable.Initialize(ms, geom); Assert.AreEqual(0, table.CreatePrimaryByCylinder(0, 4, 33, false)); Assert.AreEqual(1, table.CreatePrimaryByCylinder(10, 14, 33, false)); int idx = table.CreateAligned(3 * 1024 * 1024, WellKnownPartitionType.WindowsFat, true, 64 * 1024); Assert.AreEqual(2, idx); Assert.AreEqual(0, table[idx].FirstSector % 128); Assert.AreEqual(0, (table[idx].LastSector + 1) % 128); } [Test] public void CreateByCylinder() { SparseMemoryStream ms = new SparseMemoryStream(); Geometry geom = new Geometry(15, 30, 63); ms.SetLength(geom.Capacity); BiosPartitionTable table = BiosPartitionTable.Initialize(ms, geom); Assert.AreEqual(0, table.CreatePrimaryByCylinder(0, 4, 33, false)); Assert.AreEqual(1, table.CreatePrimaryByCylinder(10, 14, 33, false)); Assert.AreEqual(geom.ToLogicalBlockAddress(new ChsAddress(0, 1, 1)), table[0].FirstSector); Assert.AreEqual(geom.ToLogicalBlockAddress(new ChsAddress(5, 0, 1)) - 1, table[0].LastSector); Assert.AreEqual(geom.ToLogicalBlockAddress(new ChsAddress(10, 0, 1)), table[1].FirstSector); Assert.AreEqual(geom.ToLogicalBlockAddress(new ChsAddress(14, 29, 63)), table[1].LastSector); } [Test] public void Delete() { long capacity = 10 * 1024 * 1024; SparseMemoryStream ms = new SparseMemoryStream(); ms.SetLength(capacity); Geometry geom = Geometry.FromCapacity(capacity); BiosPartitionTable table = BiosPartitionTable.Initialize(ms, geom); Assert.AreEqual(0, table.Create(1 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false)); Assert.AreEqual(1, table.Create(2 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false)); Assert.AreEqual(2, table.Create(3 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false)); long[] sectorCount = new long[] { table[0].SectorCount, table[1].SectorCount, table[2].SectorCount }; table.Delete(1); Assert.AreEqual(2, table.Count); Assert.AreEqual(sectorCount[2], table[1].SectorCount); } [Test] public void SetActive() { long capacity = 10 * 1024 * 1024; SparseMemoryStream ms = new SparseMemoryStream(); ms.SetLength(capacity); Geometry geom = Geometry.FromCapacity(capacity); BiosPartitionTable table = BiosPartitionTable.Initialize(ms, geom); table.Create(1 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); table.Create(2 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); table.Create(3 * 1024 * 1024, WellKnownPartitionType.WindowsFat, false); table.SetActivePartition(1); table.SetActivePartition(2); Assert.IsFalse(((BiosPartitionInfo)table.Partitions[1]).IsActive); Assert.IsTrue(((BiosPartitionInfo)table.Partitions[2]).IsActive); } [Test] public void LargeDisk() { long capacity = 300 * 1024L * 1024L * 1024; SparseMemoryStream ms = new SparseMemoryStream(); ms.SetLength(capacity); Geometry geom = Geometry.LbaAssistedBiosGeometry(capacity); BiosPartitionTable table = BiosPartitionTable.Initialize(ms, geom); table.Create(150 * 1024L * 1024L * 1024, WellKnownPartitionType.WindowsNtfs, false); table.Create(20 * 1024L * 1024L * 1024, WellKnownPartitionType.WindowsNtfs, false); table.Create(20 * 1024L * 1024L * 1024, WellKnownPartitionType.WindowsNtfs, false); Assert.AreEqual(3, table.Partitions.Count); Assert.Greater(table[0].SectorCount * 512L, 140 * 1024L * 1024L * 1024); Assert.Greater(table[1].SectorCount * 512L, 19 * 1024L * 1024L * 1024); Assert.Greater(table[2].SectorCount * 512L, 19 * 1024L * 1024L * 1024); Assert.Greater(table[0].FirstSector, 0); Assert.Greater(table[1].FirstSector, table[0].LastSector); Assert.Greater(table[2].FirstSector, table[1].LastSector); } [Test] public void VeryLargePartition() { long capacity = 1300 * 1024L * 1024L * 1024; SparseMemoryStream ms = new SparseMemoryStream(); ms.SetLength(capacity); Geometry geom = Geometry.LbaAssistedBiosGeometry(capacity); BiosPartitionTable table = BiosPartitionTable.Initialize(ms, geom); // exception occurs here int i = table.CreatePrimaryByCylinder(0, 150000, (byte)WellKnownPartitionType.WindowsNtfs, true); Assert.AreEqual(150000, geom.ToChsAddress(table[0].LastSector).Cylinder); } } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Security.Permissions; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { [ToolboxItem(false)] public partial class DockPane : UserControl, IDockDragSource { public enum AppearanceStyle { ToolWindow, Document } private enum HitTestArea { Caption, TabStrip, Content, None } private struct HitTestResult { public HitTestArea HitArea; public int Index; public HitTestResult(HitTestArea hitTestArea, int index) { HitArea = hitTestArea; Index = index; } } private DockPaneCaptionBase m_captionControl; private DockPaneCaptionBase CaptionControl { get { return m_captionControl; } } private DockPaneStripBase m_tabStripControl; public DockPaneStripBase TabStripControl { get { return m_tabStripControl; } } private bool m_isDisposed = false; public new bool IsDisposed { get { return m_isDisposed; } } internal protected DockPane(IDockContent content, DockState visibleState, bool show) { InternalConstruct(content, visibleState, false, Rectangle.Empty, null, DockAlignment.Right, 0.5, show); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")] internal protected DockPane(IDockContent content, FloatWindow floatWindow, bool show) { if (floatWindow == null) throw new ArgumentNullException(nameof(floatWindow)); InternalConstruct(content, DockState.Float, false, Rectangle.Empty, floatWindow.NestedPanes.GetDefaultPreviousPane(this), DockAlignment.Right, 0.5, show); } internal protected DockPane(IDockContent content, DockPane previousPane, DockAlignment alignment, double proportion, bool show) { if (previousPane == null) throw (new ArgumentNullException(nameof(previousPane))); InternalConstruct(content, previousPane.DockState, false, Rectangle.Empty, previousPane, alignment, proportion, show); } [SuppressMessage("Microsoft.Naming", "CA1720:AvoidTypeNamesInParameters", MessageId = "1#")] internal protected DockPane(IDockContent content, Rectangle floatWindowBounds, bool show) { InternalConstruct(content, DockState.Float, true, floatWindowBounds, null, DockAlignment.Right, 0.5, show); } private void InternalConstruct(IDockContent content, DockState dockState, bool flagBounds, Rectangle floatWindowBounds, DockPane prevPane, DockAlignment alignment, double proportion, bool show) { if (dockState == DockState.Hidden || dockState == DockState.Unknown) throw new ArgumentException(Strings.DockPane_SetDockState_InvalidState); if (content == null) throw new ArgumentNullException(Strings.DockPane_Constructor_NullContent); if (content.DockHandler.DockPanel == null) throw new ArgumentException(Strings.DockPane_Constructor_NullDockPanel); SuspendLayout(); SetStyle(ControlStyles.Selectable, false); m_isFloat = (dockState == DockState.Float); m_contents = new DockContentCollection(); m_displayingContents = new DockContentCollection(this); m_dockPanel = content.DockHandler.DockPanel; m_dockPanel.AddPane(this); m_splitter = content.DockHandler.DockPanel.Theme.Extender.DockPaneSplitterControlFactory.CreateSplitterControl(this); m_nestedDockingStatus = new NestedDockingStatus(this); m_captionControl = DockPanel.Theme.Extender.DockPaneCaptionFactory.CreateDockPaneCaption(this); m_tabStripControl = DockPanel.Theme.Extender.DockPaneStripFactory.CreateDockPaneStrip(this); Controls.AddRange(new Control[] { m_captionControl, m_tabStripControl }); DockPanel.SuspendLayout(true); if (flagBounds) FloatWindow = DockPanel.Theme.Extender.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds); else if (prevPane != null) DockTo(prevPane.NestedPanesContainer, prevPane, alignment, proportion); SetDockState(dockState); if (show) content.DockHandler.Pane = this; else if (this.IsFloat) content.DockHandler.FloatPane = this; else content.DockHandler.PanelPane = this; ResumeLayout(); DockPanel.ResumeLayout(true, true); } private bool m_isDisposing; protected override void Dispose(bool disposing) { if (disposing && !this.m_isDisposed) { // IMPORTANT: avoid nested call into this method on Mono. // https://github.com/dockpanelsuite/dockpanelsuite/issues/16 if (Win32Helper.IsRunningOnMono) { if (m_isDisposing) return; m_isDisposing = true; } m_dockState = DockState.Unknown; if (NestedPanesContainer != null) NestedPanesContainer.NestedPanes.Remove(this); if (DockPanel != null) { DockPanel.RemovePane(this); m_dockPanel = null; } Splitter.Dispose(); if (m_autoHidePane != null) m_autoHidePane.Dispose(); this.m_isDisposed = true; } base.Dispose(disposing); } private IDockContent m_activeContent = null; public virtual IDockContent ActiveContent { get { return m_activeContent; } set { if (ActiveContent == value) return; if (value != null) { if (!DisplayingContents.Contains(value)) throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue)); } else { if (DisplayingContents.Count != 0) throw (new InvalidOperationException(Strings.DockPane_ActiveContent_InvalidValue)); } IDockContent oldValue = m_activeContent; if (DockPanel.ActiveAutoHideContent == oldValue) DockPanel.ActiveAutoHideContent = null; m_activeContent = value; if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document) { if (m_activeContent != null) m_activeContent.DockHandler.Form.BringToFront(); } else { if (m_activeContent != null) m_activeContent.DockHandler.SetVisible(); if (oldValue != null && DisplayingContents.Contains(oldValue)) oldValue.DockHandler.SetVisible(); if (IsActivated && m_activeContent != null) m_activeContent.DockHandler.Activate(); } if (FloatWindow != null) FloatWindow.SetText(); if (DockPanel.DocumentStyle == DocumentStyle.DockingMdi && DockState == DockState.Document) RefreshChanges(false); // delayed layout to reduce screen flicker else RefreshChanges(); if (m_activeContent != null) TabStripControl.EnsureTabVisible(m_activeContent); } } internal void ClearLastActiveContent() { m_activeContent = null; } private bool m_allowDockDragAndDrop = true; public virtual bool AllowDockDragAndDrop { get { return m_allowDockDragAndDrop; } set { m_allowDockDragAndDrop = value; } } private IDisposable m_autoHidePane = null; internal IDisposable AutoHidePane { get { return m_autoHidePane; } set { m_autoHidePane = value; } } private object m_autoHideTabs = null; internal object AutoHideTabs { get { return m_autoHideTabs; } set { m_autoHideTabs = value; } } private object TabPageContextMenu { get { IDockContent content = ActiveContent; if (content == null) return null; if (content.DockHandler.TabPageContextMenuStrip != null) return content.DockHandler.TabPageContextMenuStrip; else if (content.DockHandler.TabPageContextMenu != null) return content.DockHandler.TabPageContextMenu; else return null; } } internal bool HasTabPageContextMenu { get { return TabPageContextMenu != null; } } internal void ShowTabPageContextMenu(Control control, Point position) { object menu = TabPageContextMenu; if (menu == null) return; ContextMenuStrip contextMenuStrip = menu as ContextMenuStrip; if (contextMenuStrip != null) { contextMenuStrip.Show(control, position); return; } ContextMenu contextMenu = menu as ContextMenu; if (contextMenu != null) contextMenu.Show(this, position); } private Rectangle CaptionRectangle { get { if (!HasCaption) return Rectangle.Empty; Rectangle rectWindow = DisplayingRectangle; int x, y, width; x = rectWindow.X; y = rectWindow.Y; width = rectWindow.Width; int height = CaptionControl.MeasureHeight(); return new Rectangle(x, y, width, height); } } internal protected virtual Rectangle ContentRectangle { get { Rectangle rectWindow = DisplayingRectangle; Rectangle rectCaption = CaptionRectangle; Rectangle rectTabStrip = TabStripRectangle; int x = rectWindow.X; int y = rectWindow.Y + (rectCaption.IsEmpty ? 0 : rectCaption.Height); if (DockState == DockState.Document && DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Top) y += rectTabStrip.Height; int width = rectWindow.Width; int height = rectWindow.Height - rectCaption.Height - rectTabStrip.Height; return new Rectangle(x, y, width, height); } } internal Rectangle TabStripRectangle { get { if (Appearance == AppearanceStyle.ToolWindow) return TabStripRectangle_ToolWindow; else return TabStripRectangle_Document; } } private Rectangle TabStripRectangle_ToolWindow { get { if (DisplayingContents.Count <= 1 || IsAutoHide) return Rectangle.Empty; Rectangle rectWindow = DisplayingRectangle; int width = rectWindow.Width; int height = TabStripControl.MeasureHeight(); int x = rectWindow.X; int y = rectWindow.Bottom - height; Rectangle rectCaption = CaptionRectangle; if (rectCaption.Contains(x, y)) y = rectCaption.Y + rectCaption.Height; return new Rectangle(x, y, width, height); } } private Rectangle TabStripRectangle_Document { get { if (DisplayingContents.Count == 0) return Rectangle.Empty; if (DisplayingContents.Count == 1 && DockPanel.DocumentStyle == DocumentStyle.DockingSdi) return Rectangle.Empty; Rectangle rectWindow = DisplayingRectangle; int x = rectWindow.X; int width = rectWindow.Width; int height = TabStripControl.MeasureHeight(); int y = 0; if (DockPanel.DocumentTabStripLocation == DocumentTabStripLocation.Bottom) y = rectWindow.Height - height; else y = rectWindow.Y; return new Rectangle(x, y, width, height); } } public virtual string CaptionText { get { return ActiveContent == null ? string.Empty : ActiveContent.DockHandler.TabText; } } private DockContentCollection m_contents; public DockContentCollection Contents { get { return m_contents; } } private DockContentCollection m_displayingContents; public DockContentCollection DisplayingContents { get { return m_displayingContents; } } private DockPanel m_dockPanel; public DockPanel DockPanel { get { return m_dockPanel; } } private bool HasCaption { get { if (DockState == DockState.Document || DockState == DockState.Hidden || DockState == DockState.Unknown || (DockState == DockState.Float && FloatWindow.VisibleNestedPanes.Count <= 1)) return false; else return true; } } private bool m_isActivated = false; public bool IsActivated { get { return m_isActivated; } } internal void SetIsActivated(bool value) { if (m_isActivated == value) return; m_isActivated = value; if (DockState != DockState.Document) RefreshChanges(false); OnIsActivatedChanged(EventArgs.Empty); } private bool m_isActiveDocumentPane = false; public bool IsActiveDocumentPane { get { return m_isActiveDocumentPane; } } internal void SetIsActiveDocumentPane(bool value) { if (m_isActiveDocumentPane == value) return; m_isActiveDocumentPane = value; if (DockState == DockState.Document) RefreshChanges(); OnIsActiveDocumentPaneChanged(EventArgs.Empty); } public bool IsActivePane { get { return this == DockPanel.ActivePane; } } public bool IsDockStateValid(DockState dockState) { foreach (IDockContent content in Contents) if (!content.DockHandler.IsDockStateValid(dockState)) return false; return true; } public bool IsAutoHide { get { return DockHelper.IsDockStateAutoHide(DockState); } } public AppearanceStyle Appearance { get { return (DockState == DockState.Document) ? AppearanceStyle.Document : AppearanceStyle.ToolWindow; } } public Rectangle DisplayingRectangle { get { return ClientRectangle; } } public void Activate() { if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel.ActiveAutoHideContent != ActiveContent) DockPanel.ActiveAutoHideContent = ActiveContent; else if (!IsActivated && ActiveContent != null) ActiveContent.DockHandler.Activate(); } internal void AddContent(IDockContent content) { if (Contents.Contains(content)) return; Contents.Add(content); } internal void Close() { Dispose(); } public void CloseActiveContent() { CloseContent(ActiveContent); } internal void CloseContent(IDockContent content) { if (content == null) return; if (!content.DockHandler.CloseButton) return; DockPanel dockPanel = DockPanel; dockPanel.SuspendLayout(true); try { if (content.DockHandler.HideOnClose) { content.DockHandler.Hide(); NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this); } else { content.DockHandler.Close(); // TODO: fix layout here for #519 } } finally { dockPanel.ResumeLayout(true, true); } } private HitTestResult GetHitTest(Point ptMouse) { Point ptMouseClient = PointToClient(ptMouse); Rectangle rectCaption = CaptionRectangle; if (rectCaption.Contains(ptMouseClient)) return new HitTestResult(HitTestArea.Caption, -1); Rectangle rectContent = ContentRectangle; if (rectContent.Contains(ptMouseClient)) return new HitTestResult(HitTestArea.Content, -1); Rectangle rectTabStrip = TabStripRectangle; if (rectTabStrip.Contains(ptMouseClient)) return new HitTestResult(HitTestArea.TabStrip, TabStripControl.HitTest(TabStripControl.PointToClient(ptMouse))); return new HitTestResult(HitTestArea.None, -1); } private bool m_isHidden = true; public bool IsHidden { get { return m_isHidden; } } private void SetIsHidden(bool value) { if (m_isHidden == value) return; m_isHidden = value; if (DockHelper.IsDockStateAutoHide(DockState)) { DockPanel.RefreshAutoHideStrip(); DockPanel.PerformLayout(); } else if (NestedPanesContainer != null) ((Control)NestedPanesContainer).PerformLayout(); } protected override void OnLayout(LayoutEventArgs e) { SetIsHidden(DisplayingContents.Count == 0); if (!IsHidden) { CaptionControl.Bounds = CaptionRectangle; TabStripControl.Bounds = TabStripRectangle; SetContentBounds(); foreach (IDockContent content in Contents) { if (DisplayingContents.Contains(content)) if (content.DockHandler.FlagClipWindow && content.DockHandler.Form.Visible) content.DockHandler.FlagClipWindow = false; } } base.OnLayout(e); } internal void SetContentBounds() { Rectangle rectContent = ContentRectangle; if (DockState == DockState.Document && DockPanel.DocumentStyle == DocumentStyle.DockingMdi) rectContent = DockPanel.RectangleToMdiClient(RectangleToScreen(rectContent)); Rectangle rectInactive = new Rectangle(-rectContent.Width, rectContent.Y, rectContent.Width, rectContent.Height); foreach (IDockContent content in Contents) if (content.DockHandler.Pane == this) { if (content == ActiveContent) content.DockHandler.Form.Bounds = rectContent; else content.DockHandler.Form.Bounds = rectInactive; } } internal void RefreshChanges() { RefreshChanges(true); } private void RefreshChanges(bool performLayout) { if (IsDisposed) return; CaptionControl.RefreshChanges(); TabStripControl.RefreshChanges(); if (DockState == DockState.Float && FloatWindow != null) FloatWindow.RefreshChanges(); if (DockHelper.IsDockStateAutoHide(DockState) && DockPanel != null) { DockPanel.RefreshAutoHideStrip(); DockPanel.PerformLayout(); } if (performLayout) PerformLayout(); } internal void RemoveContent(IDockContent content) { if (!Contents.Contains(content)) return; Contents.Remove(content); } public void SetContentIndex(IDockContent content, int index) { int oldIndex = Contents.IndexOf(content); if (oldIndex == -1) throw (new ArgumentException(Strings.DockPane_SetContentIndex_InvalidContent)); if (index < 0 || index > Contents.Count - 1) if (index != -1) throw (new ArgumentOutOfRangeException(Strings.DockPane_SetContentIndex_InvalidIndex)); if (oldIndex == index) return; if (oldIndex == Contents.Count - 1 && index == -1) return; Contents.Remove(content); if (index == -1) Contents.Add(content); else if (oldIndex < index) Contents.AddAt(content, index - 1); else Contents.AddAt(content, index); RefreshChanges(); } private void SetParent() { if (DockState == DockState.Unknown || DockState == DockState.Hidden) { SetParent(null); Splitter.Parent = null; } else if (DockState == DockState.Float) { SetParent(FloatWindow); Splitter.Parent = FloatWindow; } else if (DockHelper.IsDockStateAutoHide(DockState)) { SetParent(DockPanel.AutoHideControl); Splitter.Parent = null; } else { SetParent(DockPanel.DockWindows[DockState]); Splitter.Parent = Parent; } } private void SetParent(Control value) { if (Parent == value) return; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! IDockContent contentFocused = GetFocusedContent(); if (contentFocused != null) DockPanel.SaveFocus(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Parent = value; //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Workaround of .Net Framework bug: // Change the parent of a control with focus may result in the first // MDI child form get activated. //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! if (contentFocused != null) contentFocused.DockHandler.Activate(); //!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! } public new void Show() { Activate(); } internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline) { if (!dragSource.CanDockTo(this)) return; Point ptMouse = Control.MousePosition; HitTestResult hitTestResult = GetHitTest(ptMouse); if (hitTestResult.HitArea == HitTestArea.Caption) dockOutline.Show(this, -1); else if (hitTestResult.HitArea == HitTestArea.TabStrip && hitTestResult.Index != -1) dockOutline.Show(this, hitTestResult.Index); } internal void ValidateActiveContent() { if (ActiveContent == null) { if (DisplayingContents.Count != 0) ActiveContent = DisplayingContents[0]; return; } if (DisplayingContents.IndexOf(ActiveContent) >= 0) return; IDockContent prevVisible = null; for (int i = Contents.IndexOf(ActiveContent) - 1; i >= 0; i--) if (Contents[i].DockHandler.DockState == DockState) { prevVisible = Contents[i]; break; } IDockContent nextVisible = null; for (int i = Contents.IndexOf(ActiveContent) + 1; i < Contents.Count; i++) if (Contents[i].DockHandler.DockState == DockState) { nextVisible = Contents[i]; break; } if (prevVisible != null) ActiveContent = prevVisible; else if (nextVisible != null) ActiveContent = nextVisible; else ActiveContent = null; } private static readonly object DockStateChangedEvent = new object(); public event EventHandler DockStateChanged { add { Events.AddHandler(DockStateChangedEvent, value); } remove { Events.RemoveHandler(DockStateChangedEvent, value); } } protected virtual void OnDockStateChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[DockStateChangedEvent]; if (handler != null) handler(this, e); } private static readonly object IsActivatedChangedEvent = new object(); public event EventHandler IsActivatedChanged { add { Events.AddHandler(IsActivatedChangedEvent, value); } remove { Events.RemoveHandler(IsActivatedChangedEvent, value); } } protected virtual void OnIsActivatedChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[IsActivatedChangedEvent]; if (handler != null) handler(this, e); } private static readonly object IsActiveDocumentPaneChangedEvent = new object(); public event EventHandler IsActiveDocumentPaneChanged { add { Events.AddHandler(IsActiveDocumentPaneChangedEvent, value); } remove { Events.RemoveHandler(IsActiveDocumentPaneChangedEvent, value); } } protected virtual void OnIsActiveDocumentPaneChanged(EventArgs e) { EventHandler handler = (EventHandler)Events[IsActiveDocumentPaneChangedEvent]; if (handler != null) handler(this, e); } public DockWindow DockWindow { get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as DockWindow; } set { DockWindow oldValue = DockWindow; if (oldValue == value) return; DockTo(value); } } public FloatWindow FloatWindow { get { return (m_nestedDockingStatus.NestedPanes == null) ? null : m_nestedDockingStatus.NestedPanes.Container as FloatWindow; } set { FloatWindow oldValue = FloatWindow; if (oldValue == value) return; DockTo(value); } } private NestedDockingStatus m_nestedDockingStatus; public NestedDockingStatus NestedDockingStatus { get { return m_nestedDockingStatus; } } private bool m_isFloat; public bool IsFloat { get { return m_isFloat; } } public INestedPanesContainer NestedPanesContainer { get { if (NestedDockingStatus.NestedPanes == null) return null; else return NestedDockingStatus.NestedPanes.Container; } } private DockState m_dockState = DockState.Unknown; public DockState DockState { get { return m_dockState; } set { SetDockState(value); } } public DockPane SetDockState(DockState value) { if (value == DockState.Unknown || value == DockState.Hidden) throw new InvalidOperationException(Strings.DockPane_SetDockState_InvalidState); if ((value == DockState.Float) == this.IsFloat) { InternalSetDockState(value); return this; } if (DisplayingContents.Count == 0) return null; IDockContent firstContent = null; for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(value)) { firstContent = content; break; } } if (firstContent == null) return null; firstContent.DockHandler.DockState = value; DockPane pane = firstContent.DockHandler.Pane; DockPanel.SuspendLayout(true); for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(value)) content.DockHandler.Pane = pane; } DockPanel.ResumeLayout(true, true); return pane; } private void InternalSetDockState(DockState value) { if (m_dockState == value) return; DockState oldDockState = m_dockState; INestedPanesContainer oldContainer = NestedPanesContainer; m_dockState = value; SuspendRefreshStateChange(); IDockContent contentFocused = GetFocusedContent(); if (contentFocused != null) DockPanel.SaveFocus(); if (!IsFloat) DockWindow = DockPanel.DockWindows[DockState]; else if (FloatWindow == null) FloatWindow = DockPanel.Theme.Extender.FloatWindowFactory.CreateFloatWindow(DockPanel, this); if (contentFocused != null) { if (!Win32Helper.IsRunningOnMono) { DockPanel.ContentFocusManager.Activate(contentFocused); } } ResumeRefreshStateChange(oldContainer, oldDockState); } private int m_countRefreshStateChange = 0; private void SuspendRefreshStateChange() { m_countRefreshStateChange++; DockPanel.SuspendLayout(true); } private void ResumeRefreshStateChange() { m_countRefreshStateChange--; System.Diagnostics.Debug.Assert(m_countRefreshStateChange >= 0); DockPanel.ResumeLayout(true, true); } private bool IsRefreshStateChangeSuspended { get { return m_countRefreshStateChange != 0; } } private void ResumeRefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState) { ResumeRefreshStateChange(); RefreshStateChange(oldContainer, oldDockState); } private void RefreshStateChange(INestedPanesContainer oldContainer, DockState oldDockState) { if (IsRefreshStateChangeSuspended) return; SuspendRefreshStateChange(); DockPanel.SuspendLayout(true); IDockContent contentFocused = GetFocusedContent(); if (contentFocused != null) DockPanel.SaveFocus(); SetParent(); if (ActiveContent != null) ActiveContent.DockHandler.SetDockState(ActiveContent.DockHandler.IsHidden, DockState, ActiveContent.DockHandler.Pane); foreach (IDockContent content in Contents) { if (content.DockHandler.Pane == this) content.DockHandler.SetDockState(content.DockHandler.IsHidden, DockState, content.DockHandler.Pane); } if (oldContainer != null) { Control oldContainerControl = (Control)oldContainer; if (oldContainer.DockState == oldDockState && !oldContainerControl.IsDisposed) oldContainerControl.PerformLayout(); } if (DockHelper.IsDockStateAutoHide(oldDockState)) DockPanel.RefreshActiveAutoHideContent(); if (NestedPanesContainer.DockState == DockState) ((Control)NestedPanesContainer).PerformLayout(); if (DockHelper.IsDockStateAutoHide(DockState)) DockPanel.RefreshActiveAutoHideContent(); if (DockHelper.IsDockStateAutoHide(oldDockState) || DockHelper.IsDockStateAutoHide(DockState)) { DockPanel.RefreshAutoHideStrip(); DockPanel.PerformLayout(); } ResumeRefreshStateChange(); if (contentFocused != null) contentFocused.DockHandler.Activate(); DockPanel.ResumeLayout(true, true); if (oldDockState != DockState) OnDockStateChanged(EventArgs.Empty); } private IDockContent GetFocusedContent() { IDockContent contentFocused = null; foreach (IDockContent content in Contents) { if (content.DockHandler.Form.ContainsFocus) { contentFocused = content; break; } } return contentFocused; } public DockPane DockTo(INestedPanesContainer container) { if (container == null) throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer); DockAlignment alignment; if (container.DockState == DockState.DockLeft || container.DockState == DockState.DockRight) alignment = DockAlignment.Bottom; else alignment = DockAlignment.Right; return DockTo(container, container.NestedPanes.GetDefaultPreviousPane(this), alignment, 0.5); } public DockPane DockTo(INestedPanesContainer container, DockPane previousPane, DockAlignment alignment, double proportion) { if (container == null) throw new InvalidOperationException(Strings.DockPane_DockTo_NullContainer); if (container.IsFloat == this.IsFloat) { InternalAddToDockList(container, previousPane, alignment, proportion); return this; } IDockContent firstContent = GetFirstContent(container.DockState); if (firstContent == null) return null; DockPane pane; DockPanel.DummyContent.DockPanel = DockPanel; if (container.IsFloat) pane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, (FloatWindow)container, true); else pane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(DockPanel.DummyContent, container.DockState, true); pane.DockTo(container, previousPane, alignment, proportion); SetVisibleContentsToPane(pane); DockPanel.DummyContent.DockPanel = null; return pane; } private void SetVisibleContentsToPane(DockPane pane) { SetVisibleContentsToPane(pane, ActiveContent); } private void SetVisibleContentsToPane(DockPane pane, IDockContent activeContent) { for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(pane.DockState)) { content.DockHandler.Pane = pane; i--; } } if (activeContent.DockHandler.Pane == pane) pane.ActiveContent = activeContent; } private void InternalAddToDockList(INestedPanesContainer container, DockPane prevPane, DockAlignment alignment, double proportion) { if ((container.DockState == DockState.Float) != IsFloat) throw new InvalidOperationException(Strings.DockPane_DockTo_InvalidContainer); int count = container.NestedPanes.Count; if (container.NestedPanes.Contains(this)) count--; if (prevPane == null && count > 0) throw new InvalidOperationException(Strings.DockPane_DockTo_NullPrevPane); if (prevPane != null && !container.NestedPanes.Contains(prevPane)) throw new InvalidOperationException(Strings.DockPane_DockTo_NoPrevPane); if (prevPane == this) throw new InvalidOperationException(Strings.DockPane_DockTo_SelfPrevPane); INestedPanesContainer oldContainer = NestedPanesContainer; DockState oldDockState = DockState; container.NestedPanes.Add(this); NestedDockingStatus.SetStatus(container.NestedPanes, prevPane, alignment, proportion); if (DockHelper.IsDockWindowState(DockState)) m_dockState = container.DockState; RefreshStateChange(oldContainer, oldDockState); } public void SetNestedDockingProportion(double proportion) { NestedDockingStatus.SetStatus(NestedDockingStatus.NestedPanes, NestedDockingStatus.PreviousPane, NestedDockingStatus.Alignment, proportion); if (NestedPanesContainer != null) ((Control)NestedPanesContainer).PerformLayout(); } public DockPane Float() { DockPanel.SuspendLayout(true); IDockContent activeContent = ActiveContent; DockPane floatPane = GetFloatPaneFromContents(); if (floatPane == null) { IDockContent firstContent = GetFirstContent(DockState.Float); if (firstContent == null) { DockPanel.ResumeLayout(true, true); return null; } floatPane = DockPanel.Theme.Extender.DockPaneFactory.CreateDockPane(firstContent, DockState.Float, true); } SetVisibleContentsToPane(floatPane, activeContent); if (PatchController.EnableFloatSplitterFix == true) { if (IsHidden) { NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this); } } DockPanel.ResumeLayout(true, true); return floatPane; } private DockPane GetFloatPaneFromContents() { DockPane floatPane = null; for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (!content.DockHandler.IsDockStateValid(DockState.Float)) continue; if (floatPane != null && content.DockHandler.FloatPane != floatPane) return null; else floatPane = content.DockHandler.FloatPane; } return floatPane; } private IDockContent GetFirstContent(DockState dockState) { for (int i = 0; i < DisplayingContents.Count; i++) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.IsDockStateValid(dockState)) return content; } return null; } public void RestoreToPanel() { DockPanel.SuspendLayout(true); IDockContent activeContent = DockPanel.ActiveContent; for (int i = DisplayingContents.Count - 1; i >= 0; i--) { IDockContent content = DisplayingContents[i]; if (content.DockHandler.CheckDockState(false) != DockState.Unknown) content.DockHandler.IsFloat = false; } DockPanel.ResumeLayout(true, true); } [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] protected override void WndProc(ref Message m) { if (this.IsDisposed) return; if (m.Msg == (int)Win32.Msgs.WM_MOUSEACTIVATE) Activate(); base.WndProc(ref m); } #region IDockDragSource Members #region IDragSource Members Control IDragSource.DragControl { get { return this; } } public IDockContent MouseOverTab { get; set; } #endregion bool IDockDragSource.IsDockStateValid(DockState dockState) { return IsDockStateValid(dockState); } bool IDockDragSource.CanDockTo(DockPane pane) { if (!IsDockStateValid(pane.DockState)) return false; if (pane == this) return false; return true; } Rectangle IDockDragSource.BeginDrag(Point ptMouse) { Point location = PointToScreen(new Point(0, 0)); Size size; DockPane floatPane = ActiveContent.DockHandler.FloatPane; if (DockState == DockState.Float || floatPane == null || floatPane.FloatWindow.NestedPanes.Count != 1) size = DockPanel.DefaultFloatWindowSize; else size = floatPane.FloatWindow.Size; if (ptMouse.X > location.X + size.Width) location.X += ptMouse.X - (location.X + size.Width) + DockPanel.Theme.Measures.SplitterSize; return new Rectangle(location, size); } void IDockDragSource.EndDrag() { } public void FloatAt(Rectangle floatWindowBounds) { if (FloatWindow == null || FloatWindow.NestedPanes.Count != 1) FloatWindow = DockPanel.Theme.Extender.FloatWindowFactory.CreateFloatWindow(DockPanel, this, floatWindowBounds); else FloatWindow.Bounds = floatWindowBounds; DockState = DockState.Float; NestedDockingStatus.NestedPanes.SwitchPaneWithFirstChild(this); } public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) { if (dockStyle == DockStyle.Fill) { IDockContent activeContent = ActiveContent; for (int i = Contents.Count - 1; i >= 0; i--) { IDockContent c = Contents[i]; if (c.DockHandler.DockState == DockState) { c.DockHandler.Pane = pane; if (contentIndex != -1) pane.SetContentIndex(c, contentIndex); } } pane.ActiveContent = activeContent; } else { if (dockStyle == DockStyle.Left) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Left, 0.5); else if (dockStyle == DockStyle.Right) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Right, 0.5); else if (dockStyle == DockStyle.Top) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Top, 0.5); else if (dockStyle == DockStyle.Bottom) DockTo(pane.NestedPanesContainer, pane, DockAlignment.Bottom, 0.5); DockState = pane.DockState; } } public void DockTo(DockPanel panel, DockStyle dockStyle) { if (panel != DockPanel) throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, nameof(panel)); if (dockStyle == DockStyle.Top) DockState = DockState.DockTop; else if (dockStyle == DockStyle.Bottom) DockState = DockState.DockBottom; else if (dockStyle == DockStyle.Left) DockState = DockState.DockLeft; else if (dockStyle == DockStyle.Right) DockState = DockState.DockRight; else if (dockStyle == DockStyle.Fill) DockState = DockState.Document; } #endregion #region cachedLayoutArgs leak workaround /// <summary> /// There's a bug in the WinForms layout engine /// that can result in a deferred layout to not /// properly clear out the cached layout args after /// the layout operation is performed. /// Specifically, this bug is hit when the bounds of /// the Pane change, initiating a layout on the parent /// (DockWindow) which is where the bug hits. /// To work around it, when a pane loses the DockWindow /// as its parent, that parent DockWindow needs to /// perform a layout to flush the cached args, if they exist. /// </summary> private DockWindow _lastParentWindow; protected override void OnParentChanged(EventArgs e) { base.OnParentChanged(e); var newParent = Parent as DockWindow; if (newParent != _lastParentWindow) { if (_lastParentWindow != null) _lastParentWindow.PerformLayout(); _lastParentWindow = newParent; } } #endregion } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using OpenMetaverse; using OpenSim.Framework.Communications.Cache; using OpenSim.Framework.Servers.HttpServer; namespace OpenSim.Framework.Communications { /// <summary> /// This class manages references to OpenSim non-region services (asset, user, etc.) /// </summary> /// /// TODO: Service retrieval needs to be managed via plugin and interfaces requests, as happens for region /// modules from scene. Among other things, this will allow this class to be used in many different contexts /// (from a grid service executable, to provide services on a region) without lots of messy nulls and confusion. /// Also, a post initialize step on the plugins will be needed so that we don't get tortuous problems with /// circular dependencies between plugins. public class CommunicationsManager { //private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected Dictionary<UUID, string[]> m_nameRequestCache = new Dictionary<UUID, string[]>(); public IUserService UserService { get { return m_userService; } } protected IUserService m_userService; public IMessagingService MessageService { get { return m_messageService; } } protected IMessagingService m_messageService; public IGridServices GridService { get { return m_gridService; } } protected IGridServices m_gridService; public UserProfileCacheService UserProfileCacheService { get { return m_userProfileCacheService; } } protected UserProfileCacheService m_userProfileCacheService; // protected AgentAssetTransactionsManager m_transactionsManager; // public AgentAssetTransactionsManager TransactionsManager // { // get { return m_transactionsManager; } // } public IAvatarService AvatarService { get { return m_avatarService; } } protected IAvatarService m_avatarService; public IAssetCache AssetCache { get { return m_assetCache; } } protected IAssetCache m_assetCache; public NetworkServersInfo NetworkServersInfo { get { return m_networkServersInfo; } } protected NetworkServersInfo m_networkServersInfo; /// <summary> /// Interface to user service for administrating users. /// </summary> public IUserAdminService UserAdminService { get { return m_userAdminService; } } protected IUserAdminService m_userAdminService; /// <value> /// OpenSimulator's built in HTTP server /// </value> public IHttpServer HttpServer { get { return m_httpServer; } } protected IHttpServer m_httpServer; /// <summary> /// The root library folder. /// </summary> public readonly InventoryFolderImpl LibraryRoot; /// <summary> /// Constructor /// </summary> /// <param name="serversInfo"></param> /// <param name="httpServer"></param> /// <param name="assetCache"></param> public CommunicationsManager(NetworkServersInfo serversInfo, IHttpServer httpServer, IAssetCache assetCache, LibraryRootFolder libraryRootFolder) { m_networkServersInfo = serversInfo; m_assetCache = assetCache; m_userProfileCacheService = new UserProfileCacheService(this); m_httpServer = httpServer; LibraryRoot = libraryRootFolder; Preload(); } private static void PreloadMethods(Type type) { foreach (var method in type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) { if (method.IsAbstract) continue; if (method.ContainsGenericParameters || method.IsGenericMethod || method.IsGenericMethodDefinition) continue; if ((method.Attributes & MethodAttributes.PinvokeImpl) > 0) continue; try { System.Runtime.CompilerServices.RuntimeHelpers.PrepareMethod(method.MethodHandle); } catch { } } } private static void Preload() { //preload new Messages.AgentPutMessage(); new Messages.FriendsListRequest(); new Messages.FriendsListResponse(); new Messages.ObjectPostMessage(); ProtoBuf.Meta.RuntimeTypeModel.Default[typeof(Messages.AgentPutMessage)].CompileInPlace(); ProtoBuf.Meta.RuntimeTypeModel.Default[typeof(Messages.FriendsListRequest)].CompileInPlace(); ProtoBuf.Meta.RuntimeTypeModel.Default[typeof(Messages.FriendsListResponse)].CompileInPlace(); ProtoBuf.Meta.RuntimeTypeModel.Default[typeof(Messages.ObjectPostMessage)].CompileInPlace(); ProtoBuf.Meta.RuntimeTypeModel.Default[typeof(Messages.PackedAnimation)].CompileInPlace(); ProtoBuf.Meta.RuntimeTypeModel.Default[typeof(Messages.PackedAppearance)].CompileInPlace(); ProtoBuf.Meta.RuntimeTypeModel.Default[typeof(Messages.PackedGroupMembership)].CompileInPlace(); ProtoBuf.Meta.RuntimeTypeModel.Default[typeof(Messages.PackedWearable)].CompileInPlace(); foreach (var type in Assembly.GetExecutingAssembly().GetTypes()) { PreloadMethods(type); } } #region Friend Methods /// <summary> /// Adds a new friend to the database for XUser /// </summary> /// <param name="friendlistowner">The agent that who's friends list is being added to</param> /// <param name="friend">The agent that being added to the friends list of the friends list owner</param> /// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param> public void AddNewUserFriend(UUID friendlistowner, UUID friend, uint perms) { m_userService.AddNewUserFriend(friendlistowner, friend, perms); } /// <summary> /// Logs off a user and does the appropriate communications /// </summary> /// <param name="userid"></param> /// <param name="regionid"></param> /// <param name="regionhandle"></param> /// <param name="position"></param> /// <param name="lookat"></param> public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, Vector3 position, Vector3 lookat) { m_userService.LogOffUser(userid, regionid, regionhandle, position, lookat); } /// <summary> /// Logs off a user and does the appropriate communications (deprecated as of 2008-08-27) /// </summary> /// <param name="userid"></param> /// <param name="regionid"></param> /// <param name="regionhandle"></param> /// <param name="posx"></param> /// <param name="posy"></param> /// <param name="posz"></param> public void LogOffUser(UUID userid, UUID regionid, ulong regionhandle, float posx, float posy, float posz) { m_userService.LogOffUser(userid, regionid, regionhandle, posx, posy, posz); } /// <summary> /// Delete friend on friendlistowner's friendlist. /// </summary> /// <param name="friendlistowner">The agent that who's friends list is being updated</param> /// <param name="friend">The Ex-friend agent</param> public void RemoveUserFriend(UUID friendlistowner, UUID friend) { m_userService.RemoveUserFriend(friendlistowner, friend); } /// <summary> /// Update permissions for friend on friendlistowner's friendlist. /// </summary> /// <param name="friendlistowner">The agent that who's friends list is being updated</param> /// <param name="friend">The agent that is getting or loosing permissions</param> /// <param name="perms">A uint bit vector for set perms that the friend being added has; 0 = none, 1=This friend can see when they sign on, 2 = map, 4 edit objects </param> public void UpdateUserFriendPerms(UUID friendlistowner, UUID friend, uint perms) { m_userService.UpdateUserFriendPerms(friendlistowner, friend, perms); } /// <summary> /// Returns a list of FriendsListItems that describe the friends and permissions in the friend relationship for UUID friendslistowner /// </summary> /// <param name="friendlistowner">The agent that we're retreiving the friends Data.</param> public List<FriendListItem> GetUserFriendList(UUID friendlistowner) { return m_userService.GetUserFriendList(friendlistowner); } public Dictionary<UUID, FriendRegionInfo> GetFriendRegionInfos(List<UUID> uuids) { return m_messageService.GetFriendRegionInfos(uuids); } #endregion #region Packet Handlers public void UpdateAvatarPropertiesRequest(IClientAPI remote_client, UserProfileData UserProfile) { m_userService.UpdateUserProfile(UserProfile); return; } public void HandleUUIDNameRequest(UUID uuid, IClientAPI remote_client) { if (uuid == LibraryRoot.Owner) { remote_client.SendNameReply(uuid, "Mr", "OpenSim"); } else { doUUIDNameRequest(uuid, delegate(string[] names) { if (names.Length == 2) { remote_client.SendNameReply(uuid, names[0], names[1]); } }, true); } } private delegate void NameFoundCallback(string[] names); private void doUUIDNameRequest(UUID uuid, NameFoundCallback callBack, bool async) { string[] returnstring = new string[0]; bool doLookup = false; lock (m_nameRequestCache) { if (m_nameRequestCache.ContainsKey(uuid)) { returnstring = m_nameRequestCache[uuid]; } else { // we don't want to lock the dictionary while we're doing the lookup doLookup = true; } } if (!doLookup) { callBack(returnstring); return; } else { if (async) { Util.FireAndForget(Util.PoolSelection.LongIO, delegate(object obj) { doUUIDSyncRequest(uuid, callBack); }); } else { doUUIDSyncRequest(uuid, callBack); } return; } } private void doUUIDSyncRequest(UUID uuid, NameFoundCallback callBack) { string[] returnstring = new string[0]; //first see if by chance we have this is the profile cache CachedUserInfo uInfo = m_userProfileCacheService.GetUserDetails(uuid); UserProfileData profileData = (uInfo != null) ? uInfo.UserProfile : null; if (profileData != null) { returnstring = new string[2]; // UUID profileId = profileData.ID; returnstring[0] = profileData.FirstName; returnstring[1] = profileData.SurName; lock (m_nameRequestCache) { if (!m_nameRequestCache.ContainsKey(uuid)) m_nameRequestCache.Add(uuid, returnstring); } } callBack(returnstring); } public bool UUIDNameCachedTest(UUID uuid) { lock (m_nameRequestCache) return m_nameRequestCache.ContainsKey(uuid); } public string UUIDNameRequestString(UUID uuid) { string firstName = null; string lastName = null; doUUIDNameRequest(uuid, delegate(string[] names) { if (names.Length == 2) { firstName = names[0]; lastName = names[1]; } }, false); if (firstName != null && lastName != null) { return firstName + " " + lastName; } else { return "(unknown)"; } } public List<AvatarPickerAvatar> GenerateAgentPickerRequestResponse(UUID queryID, string query) { List<AvatarPickerAvatar> pickerlist = m_userService.GenerateAgentPickerRequestResponse(queryID, query); return pickerlist; } #endregion } }
using System; using System.Drawing; using System.Windows.Forms; using System.Security.Permissions; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { public class FloatWindow : Form, INestedPanesContainer, IDockDragSource { private NestedPaneCollection m_nestedPanes; internal const int WM_CHECKDISPOSE = (int)(Win32.Msgs.WM_USER + 1); internal protected FloatWindow(DockPanel dockPanel, DockPane pane) { InternalConstruct(dockPanel, pane, false, Rectangle.Empty); } internal protected FloatWindow(DockPanel dockPanel, DockPane pane, Rectangle bounds) { InternalConstruct(dockPanel, pane, true, bounds); } private void InternalConstruct(DockPanel dockPanel, DockPane pane, bool boundsSpecified, Rectangle bounds) { if (dockPanel == null) throw(new ArgumentNullException(Strings.FloatWindow_Constructor_NullDockPanel)); m_nestedPanes = new NestedPaneCollection(this); FormBorderStyle = FormBorderStyle.SizableToolWindow; ShowInTaskbar = false; if (dockPanel.RightToLeft != RightToLeft) RightToLeft = dockPanel.RightToLeft; if (RightToLeftLayout != dockPanel.RightToLeftLayout) RightToLeftLayout = dockPanel.RightToLeftLayout; SuspendLayout(); if (boundsSpecified) { Bounds = bounds; StartPosition = FormStartPosition.Manual; } else { StartPosition = FormStartPosition.WindowsDefaultLocation; Size = dockPanel.DefaultFloatWindowSize; } m_dockPanel = dockPanel; Owner = DockPanel.FindForm(); DockPanel.AddFloatWindow(this); if (pane != null) pane.FloatWindow = this; ResumeLayout(); } protected override void Dispose(bool disposing) { if (disposing) { if (DockPanel != null) DockPanel.RemoveFloatWindow(this); m_dockPanel = null; } base.Dispose(disposing); } private bool m_allowEndUserDocking = true; public bool AllowEndUserDocking { get { return m_allowEndUserDocking; } set { m_allowEndUserDocking = value; } } private bool m_doubleClickTitleBarToDock = true; public bool DoubleClickTitleBarToDock { get { return m_doubleClickTitleBarToDock; } set { m_doubleClickTitleBarToDock = value; } } public NestedPaneCollection NestedPanes { get { return m_nestedPanes; } } public VisibleNestedPaneCollection VisibleNestedPanes { get { return NestedPanes.VisibleNestedPanes; } } private DockPanel m_dockPanel; public DockPanel DockPanel { get { return m_dockPanel; } } public DockState DockState { get { return DockState.Float; } } public bool IsFloat { get { return DockState == DockState.Float; } } internal bool IsDockStateValid(DockState dockState) { foreach (DockPane pane in NestedPanes) foreach (IDockContent content in pane.Contents) if (!DockHelper.IsDockStateValid(dockState, content.DockHandler.DockAreas)) return false; return true; } protected override void OnActivated(EventArgs e) { DockPanel.FloatWindows.BringWindowToFront(this); base.OnActivated (e); // Propagate the Activated event to the visible panes content objects foreach (DockPane pane in VisibleNestedPanes) foreach (IDockContent content in pane.Contents) content.OnActivated(e); } protected override void OnDeactivate(EventArgs e) { base.OnDeactivate(e); // Propagate the Deactivate event to the visible panes content objects foreach (DockPane pane in VisibleNestedPanes) foreach (IDockContent content in pane.Contents) content.OnDeactivate(e); } protected override void OnLayout(LayoutEventArgs levent) { VisibleNestedPanes.Refresh(); RefreshChanges(); Visible = (VisibleNestedPanes.Count > 0); SetText(); base.OnLayout(levent); } [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters", MessageId = "System.Windows.Forms.Control.set_Text(System.String)")] internal void SetText() { DockPane theOnlyPane = (VisibleNestedPanes.Count == 1) ? VisibleNestedPanes[0] : null; if (theOnlyPane == null || theOnlyPane.ActiveContent == null) { Text = " "; // use " " instead of string.Empty because the whole title bar will disappear when ControlBox is set to false. Icon = null; } else { Text = theOnlyPane.ActiveContent.DockHandler.TabText; Icon = theOnlyPane.ActiveContent.DockHandler.Icon; } } protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) { Rectangle rectWorkArea = SystemInformation.VirtualScreen; if (y + height > rectWorkArea.Bottom) y -= (y + height) - rectWorkArea.Bottom; if (y < rectWorkArea.Top) y += rectWorkArea.Top - y; base.SetBoundsCore (x, y, width, height, specified); } [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] protected override void WndProc(ref Message m) { switch (m.Msg) { case (int)Win32.Msgs.WM_NCLBUTTONDOWN: { if (IsDisposed) return; uint result = Win32Helper.IsRunningOnMono ? 0 : NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam); if (result == 2 && DockPanel.AllowEndUserDocking && this.AllowEndUserDocking) // HITTEST_CAPTION { Activate(); m_dockPanel.BeginDrag(this); } else base.WndProc(ref m); return; } case (int)Win32.Msgs.WM_NCRBUTTONDOWN: { uint result = Win32Helper.IsRunningOnMono ? 0 : NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam); if (result == 2) // HITTEST_CAPTION { DockPane theOnlyPane = (VisibleNestedPanes.Count == 1) ? VisibleNestedPanes[0] : null; if (theOnlyPane != null && theOnlyPane.ActiveContent != null) { theOnlyPane.ShowTabPageContextMenu(this, PointToClient(Control.MousePosition)); return; } } base.WndProc(ref m); return; } case (int)Win32.Msgs.WM_CLOSE: if (NestedPanes.Count == 0) { base.WndProc(ref m); return; } for (int i = NestedPanes.Count - 1; i >= 0; i--) { DockContentCollection contents = NestedPanes[i].Contents; for (int j = contents.Count - 1; j >= 0; j--) { IDockContent content = contents[j]; if (content.DockHandler.DockState != DockState.Float) continue; if (!content.DockHandler.CloseButton) continue; if (content.DockHandler.HideOnClose) content.DockHandler.Hide(); else content.DockHandler.Close(); } } return; case (int)Win32.Msgs.WM_NCLBUTTONDBLCLK: { uint result = !DoubleClickTitleBarToDock || Win32Helper.IsRunningOnMono ? 0 : NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, (uint)m.LParam); if (result != 2) // HITTEST_CAPTION { base.WndProc(ref m); return; } DockPanel.SuspendLayout(true); // Restore to panel foreach (DockPane pane in NestedPanes) { if (pane.DockState != DockState.Float) continue; pane.RestoreToPanel(); } DockPanel.ResumeLayout(true, true); return; } case WM_CHECKDISPOSE: if (NestedPanes.Count == 0) Dispose(); return; } base.WndProc(ref m); } internal void RefreshChanges() { if (IsDisposed) return; if (VisibleNestedPanes.Count == 0) { ControlBox = true; return; } for (int i=VisibleNestedPanes.Count - 1; i>=0; i--) { DockContentCollection contents = VisibleNestedPanes[i].Contents; for (int j=contents.Count - 1; j>=0; j--) { IDockContent content = contents[j]; if (content.DockHandler.DockState != DockState.Float) continue; if (content.DockHandler.CloseButton && content.DockHandler.CloseButtonVisible) { ControlBox = true; return; } } } //Only if there is a ControlBox do we turn it off //old code caused a flash of the window. if (ControlBox) ControlBox = false; } public virtual Rectangle DisplayingRectangle { get { return ClientRectangle; } } internal void TestDrop(IDockDragSource dragSource, DockOutlineBase dockOutline) { if (VisibleNestedPanes.Count == 1) { DockPane pane = VisibleNestedPanes[0]; if (!dragSource.CanDockTo(pane)) return; Point ptMouse = Control.MousePosition; uint lParam = Win32Helper.MakeLong(ptMouse.X, ptMouse.Y); if (!Win32Helper.IsRunningOnMono) { if (NativeMethods.SendMessage(Handle, (int)Win32.Msgs.WM_NCHITTEST, 0, lParam) == (uint)Win32.HitTest.HTCAPTION) { dockOutline.Show(VisibleNestedPanes[0], -1); } } } } #region IDockDragSource Members #region IDragSource Members Control IDragSource.DragControl { get { return this; } } #endregion bool IDockDragSource.IsDockStateValid(DockState dockState) { return IsDockStateValid(dockState); } bool IDockDragSource.CanDockTo(DockPane pane) { if (!IsDockStateValid(pane.DockState)) return false; if (pane.FloatWindow == this) return false; return true; } private int m_preDragExStyle; Rectangle IDockDragSource.BeginDrag(Point ptMouse) { m_preDragExStyle = NativeMethods.GetWindowLong(this.Handle, (int)Win32.GetWindowLongIndex.GWL_EXSTYLE); NativeMethods.SetWindowLong(this.Handle, (int)Win32.GetWindowLongIndex.GWL_EXSTYLE, m_preDragExStyle | (int)(Win32.WindowExStyles.WS_EX_TRANSPARENT | Win32.WindowExStyles.WS_EX_LAYERED) ); return Bounds; } void IDockDragSource.EndDrag() { NativeMethods.SetWindowLong(this.Handle, (int)Win32.GetWindowLongIndex.GWL_EXSTYLE, m_preDragExStyle); Invalidate(true); NativeMethods.SendMessage(this.Handle, (int)Win32.Msgs.WM_NCPAINT, 1, 0); } public void FloatAt(Rectangle floatWindowBounds) { Bounds = floatWindowBounds; } public void DockTo(DockPane pane, DockStyle dockStyle, int contentIndex) { if (dockStyle == DockStyle.Fill) { for (int i = NestedPanes.Count - 1; i >= 0; i--) { DockPane paneFrom = NestedPanes[i]; for (int j = paneFrom.Contents.Count - 1; j >= 0; j--) { IDockContent c = paneFrom.Contents[j]; c.DockHandler.Pane = pane; if (contentIndex != -1) pane.SetContentIndex(c, contentIndex); c.DockHandler.Activate(); } } } else { DockAlignment alignment = DockAlignment.Left; if (dockStyle == DockStyle.Left) alignment = DockAlignment.Left; else if (dockStyle == DockStyle.Right) alignment = DockAlignment.Right; else if (dockStyle == DockStyle.Top) alignment = DockAlignment.Top; else if (dockStyle == DockStyle.Bottom) alignment = DockAlignment.Bottom; MergeNestedPanes(VisibleNestedPanes, pane.NestedPanesContainer.NestedPanes, pane, alignment, 0.5); } } public void DockTo(DockPanel panel, DockStyle dockStyle) { if (panel != DockPanel) throw new ArgumentException(Strings.IDockDragSource_DockTo_InvalidPanel, "panel"); NestedPaneCollection nestedPanesTo = null; if (dockStyle == DockStyle.Top) nestedPanesTo = DockPanel.DockWindows[DockState.DockTop].NestedPanes; else if (dockStyle == DockStyle.Bottom) nestedPanesTo = DockPanel.DockWindows[DockState.DockBottom].NestedPanes; else if (dockStyle == DockStyle.Left) nestedPanesTo = DockPanel.DockWindows[DockState.DockLeft].NestedPanes; else if (dockStyle == DockStyle.Right) nestedPanesTo = DockPanel.DockWindows[DockState.DockRight].NestedPanes; else if (dockStyle == DockStyle.Fill) nestedPanesTo = DockPanel.DockWindows[DockState.Document].NestedPanes; DockPane prevPane = null; for (int i = nestedPanesTo.Count - 1; i >= 0; i--) if (nestedPanesTo[i] != VisibleNestedPanes[0]) prevPane = nestedPanesTo[i]; MergeNestedPanes(VisibleNestedPanes, nestedPanesTo, prevPane, DockAlignment.Left, 0.5); } private static void MergeNestedPanes(VisibleNestedPaneCollection nestedPanesFrom, NestedPaneCollection nestedPanesTo, DockPane prevPane, DockAlignment alignment, double proportion) { if (nestedPanesFrom.Count == 0) return; int count = nestedPanesFrom.Count; DockPane[] panes = new DockPane[count]; DockPane[] prevPanes = new DockPane[count]; DockAlignment[] alignments = new DockAlignment[count]; double[] proportions = new double[count]; for (int i = 0; i < count; i++) { panes[i] = nestedPanesFrom[i]; prevPanes[i] = nestedPanesFrom[i].NestedDockingStatus.PreviousPane; alignments[i] = nestedPanesFrom[i].NestedDockingStatus.Alignment; proportions[i] = nestedPanesFrom[i].NestedDockingStatus.Proportion; } DockPane pane = panes[0].DockTo(nestedPanesTo.Container, prevPane, alignment, proportion); panes[0].DockState = nestedPanesTo.DockState; for (int i = 1; i < count; i++) { for (int j = i; j < count; j++) { if (prevPanes[j] == panes[i - 1]) prevPanes[j] = pane; } pane = panes[i].DockTo(nestedPanesTo.Container, prevPanes[i], alignments[i], proportions[i]); panes[i].DockState = nestedPanesTo.DockState; } } #endregion } }
// *********************************************************************** // Copyright (c) 2007-2016 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. // *********************************************************************** #if !(NETSTANDARD1_6 || NETSTANDARD2_0) using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using Microsoft.Win32; namespace NUnit.Framework.Internal { /// <summary> /// Enumeration identifying a common language /// runtime implementation. /// </summary> public enum RuntimeType { /// <summary>Any supported runtime framework</summary> Any, /// <summary>Microsoft .NET Framework</summary> Net, /// <summary>Microsoft Shared Source CLI</summary> SSCLI, /// <summary>Mono</summary> Mono, /// <summary>MonoTouch</summary> MonoTouch } /// <summary> /// RuntimeFramework represents a particular version /// of a common language runtime implementation. /// </summary> [Serializable] public sealed class RuntimeFramework { // NOTE: This version of RuntimeFramework is for use // within the NUnit framework assembly. It is simpler // than the version in the test engine because it does // not need to know what frameworks are available, // only what framework is currently running. #region Static and Instance Fields /// <summary> /// DefaultVersion is an empty Version, used to indicate that /// NUnit should select the CLR version to use for the test. /// </summary> public static readonly Version DefaultVersion = new Version(0,0); private static readonly Lazy<RuntimeFramework> currentFramework = new Lazy<RuntimeFramework>(() => { Type monoRuntimeType = Type.GetType("Mono.Runtime", false); Type monoTouchType = Type.GetType("MonoTouch.UIKit.UIApplicationDelegate,monotouch"); bool isMonoTouch = monoTouchType != null; bool isMono = monoRuntimeType != null; RuntimeType runtime = isMonoTouch ? RuntimeType.MonoTouch : isMono ? RuntimeType.Mono : RuntimeType.Net; int major = Environment.Version.Major; int minor = Environment.Version.Minor; if (isMono) { switch (major) { case 1: minor = 0; break; case 2: major = 3; minor = 5; break; } } else /* It's windows */ if (major == 2) { using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\.NETFramework")) { if (key != null) { string installRoot = key.GetValue("InstallRoot") as string; if (installRoot != null) { if (Directory.Exists(Path.Combine(installRoot, "v3.5"))) { major = 3; minor = 5; } else if (Directory.Exists(Path.Combine(installRoot, "v3.0"))) { major = 3; minor = 0; } } } } } else if (major == 4 && Type.GetType("System.Reflection.AssemblyMetadataAttribute") != null) { minor = 5; } var currentFramework = new RuntimeFramework( runtime, new Version (major, minor) ) { ClrVersion = Environment.Version }; if (isMono) { MethodInfo getDisplayNameMethod = monoRuntimeType.GetMethod( "GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding); if (getDisplayNameMethod != null) currentFramework.DisplayName = (string)getDisplayNameMethod.Invoke(null, new object[0]); } return currentFramework; }); #endregion #region Constructor /// <summary> /// Construct from a runtime type and version. If the version has /// two parts, it is taken as a framework version. If it has three /// or more, it is taken as a CLR version. In either case, the other /// version is deduced based on the runtime type and provided version. /// </summary> /// <param name="runtime">The runtime type of the framework</param> /// <param name="version">The version of the framework</param> public RuntimeFramework( RuntimeType runtime, Version version) { Runtime = runtime; if (version.Build < 0) InitFromFrameworkVersion(version); else InitFromClrVersion(version); DisplayName = GetDefaultDisplayName(runtime, version); } private void InitFromFrameworkVersion(Version version) { FrameworkVersion = ClrVersion = version; if (version.Major > 0) // 0 means any version switch (Runtime) { case RuntimeType.Net: case RuntimeType.Mono: case RuntimeType.Any: switch (version.Major) { case 1: switch (version.Minor) { case 0: ClrVersion = Runtime == RuntimeType.Mono ? new Version(1, 1, 4322) : new Version(1, 0, 3705); break; case 1: if (Runtime == RuntimeType.Mono) FrameworkVersion = new Version(1, 0); ClrVersion = new Version(1, 1, 4322); break; default: ThrowInvalidFrameworkVersion(version); break; } break; case 2: case 3: ClrVersion = new Version(2, 0, 50727); break; case 4: ClrVersion = new Version(4, 0, 30319); break; default: ThrowInvalidFrameworkVersion(version); break; } break; } } private static void ThrowInvalidFrameworkVersion(Version version) { throw new ArgumentException("Unknown framework version " + version, "version"); } private void InitFromClrVersion(Version version) { FrameworkVersion = new Version(version.Major, version.Minor); ClrVersion = version; if (Runtime == RuntimeType.Mono && version.Major == 1) FrameworkVersion = new Version(1, 0); } #endregion #region Properties /// <summary> /// Static method to return a RuntimeFramework object /// for the framework that is currently in use. /// </summary> public static RuntimeFramework CurrentFramework { get { return currentFramework.Value; } } /// <summary> /// The type of this runtime framework /// </summary> public RuntimeType Runtime { get; private set; } /// <summary> /// The framework version for this runtime framework /// </summary> public Version FrameworkVersion { get; private set; } /// <summary> /// The CLR version for this runtime framework /// </summary> public Version ClrVersion { get; private set; } /// <summary> /// Return true if any CLR version may be used in /// matching this RuntimeFramework object. /// </summary> public bool AllowAnyVersion { get { return ClrVersion == DefaultVersion; } } /// <summary> /// Returns the Display name for this framework /// </summary> public string DisplayName { get; private set; } #endregion #region Public Methods /// <summary> /// Parses a string representing a RuntimeFramework. /// The string may be just a RuntimeType name or just /// a Version or a hyphenated RuntimeType-Version or /// a Version prefixed by 'versionString'. /// </summary> /// <param name="s"></param> /// <returns></returns> public static RuntimeFramework Parse(string s) { RuntimeType runtime = RuntimeType.Any; Version version = DefaultVersion; string[] parts = s.Split('-'); if (parts.Length == 2) { runtime = (RuntimeType)Enum.Parse(typeof(RuntimeType), parts[0], true); string vstring = parts[1]; if (vstring != "") version = new Version(vstring); } else if (char.ToLower(s[0]) == 'v') { version = new Version(s.Substring(1)); } else if (IsRuntimeTypeName(s)) { runtime = (RuntimeType)Enum.Parse(typeof(RuntimeType), s, true); } else { version = new Version(s); } return new RuntimeFramework(runtime, version); } /// <summary> /// Overridden to return the short name of the framework /// </summary> /// <returns></returns> public override string ToString() { if (AllowAnyVersion) { return Runtime.ToString().ToLower(); } else { string vstring = FrameworkVersion.ToString(); if (Runtime == RuntimeType.Any) return "v" + vstring; else return Runtime.ToString().ToLower() + "-" + vstring; } } /// <summary> /// Returns true if the current framework matches the /// one supplied as an argument. Two frameworks match /// if their runtime types are the same or either one /// is RuntimeType.Any and all specified version components /// are equal. Negative (i.e. unspecified) version /// components are ignored. /// </summary> /// <param name="target">The RuntimeFramework to be matched.</param> /// <returns>True on match, otherwise false</returns> public bool Supports(RuntimeFramework target) { if (Runtime != RuntimeType.Any && target.Runtime != RuntimeType.Any && Runtime != target.Runtime) return false; if (AllowAnyVersion || target.AllowAnyVersion) return true; if (!VersionsMatch(ClrVersion, target.ClrVersion)) return false; return FrameworkVersion.Major >= target.FrameworkVersion.Major && FrameworkVersion.Minor >= target.FrameworkVersion.Minor; } #endregion #region Helper Methods private static bool IsRuntimeTypeName(string name) { return Enum.GetNames( typeof(RuntimeType)).Any( item => item.ToLower() == name.ToLower() ); } private static string GetDefaultDisplayName(RuntimeType runtime, Version version) { if (version == DefaultVersion) return runtime.ToString(); else if (runtime == RuntimeType.Any) return "v" + version; else return runtime + " " + version; } private static bool VersionsMatch(Version v1, Version v2) { return v1.Major == v2.Major && v1.Minor == v2.Minor && (v1.Build < 0 || v2.Build < 0 || v1.Build == v2.Build) && (v1.Revision < 0 || v2.Revision < 0 || v1.Revision == v2.Revision); } #endregion } } #endif
//By Jean-Pierre Bachmann //http://www.codeproject.com/Articles/682642/Using-a-Plugin-Based-Application //Questions? Ask me! //Microsoft Public License (MS-PL) /* This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. All at all - Be carefull when using this code and do not remove the License! */ #region Jean-Pierre Bachmann // Erstellt von Jean-Pierre Bachmann am 10:57 #endregion using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Runtime.InteropServices; using JPB.Shell.Contracts.Interfaces.Metadata; using JPB.Shell.Contracts.Interfaces.Services; using JPB.Shell.Contracts.Interfaces.Services.ShellServices; namespace JPB.Shell.MEF.Services.Extentions { public static class ServicePoolExtentions { #region Metadata public static IServiceMetadata GetSingelMetadata(this IServicePool source) { return source.GetServiceInternal().Select(s => s.Metadata).FirstOrDefault(); } public static bool TryGetSingelMetadata(this IServicePool source, [Out] IServiceMetadata output) { output = default(IServiceMetadata); try { output = source.GetServiceInternal().Select(s => s.Metadata).FirstOrDefault(); return true; } catch (Exception) { return false; } } #endregion #region TryGetServices public static bool TryGetServices<T>(this IServicePool source, [Out] [Required] IEnumerable<T> output, string descriptor) where T : class, IService { output = default(IEnumerable<T>); try { output = source.GetServiceInternal() .Where( m => m.Metadata.Contracts.Any(f => f == typeof (T)) && m.Metadata.Descriptor == descriptor) .Select(m => m.Value as T); return true; } catch (Exception) { return false; } } public static bool TryGetServices<T>(this IServicePool source, [Out] [Required] IEnumerable<T> output, IServiceMetadata metadata) where T : class, IService { output = default(IEnumerable<T>); try { output = source.GetServiceInternal() .Where(m => m.Metadata == metadata) .Select(m => m.Value as T); return true; } catch (Exception) { return false; } } #endregion #region GetServices public static IEnumerable<T> GetServices<T>(this IServicePool source, string descriptor) where T : class, IService { return source.GetServiceInternal() .Where( m => m.Metadata.Contracts.Any(f => f == typeof (T)) && m.Metadata.Descriptor == descriptor) .Select(s => s.Value as T); } public static IEnumerable<T> GetServices<T>(this IServicePool source, [Required] IServiceMetadata metadata) where T : class, IService { return source.GetServiceInternal() .Where(m => m.Metadata.Contracts == metadata.Contracts && m.Metadata.Descriptor == metadata.Descriptor && m.Metadata.IsDefauldService == metadata.IsDefauldService && m.Metadata.ToString() == metadata.ToString()) .Select(s => s.Value as T); } #endregion #region GetSingelService public static T GetFirstOrDefault<T>(this IServicePool source, Func<Lazy<IService, IServiceMetadata>, bool> selector) where T:class, IService { var firstOrDefault = source.GetServiceInternal().FirstOrDefault(selector); if (firstOrDefault != null) { return firstOrDefault.Value as T; } return null; } public static T GetSingelService<T>(this IServicePool source, [Required] IServiceMetadata metadata) where T : class, IService { return source.GetFirstOrDefault<T>( m => m.Metadata.Contracts == metadata.Contracts && m.Metadata.Descriptor == metadata.Descriptor && m.Metadata.ToString() == metadata.ToString()); } public static T GetSingelService<T>(this IServicePool source, string descriptor) where T : class, IService { return source.GetFirstOrDefault<T>( m => m.Metadata.Contracts.Any(f => f == typeof (T)) && m.Metadata.Descriptor == descriptor); } private static T GetSingelDefauldService<T>(this IServicePool source) where T : class, IService { return source.GetFirstOrDefault<T>(m => m.Metadata.Contracts.Any(f => f == typeof (T))); } #endregion #region TryGetSingelService public static bool TryGetSingelService<T>(this IServicePool source, [Out] [Required] T output, IServiceMetadata metadata) where T : class { output = default(T); try { output = source.GetServiceInternal() .Where(m => m.Metadata == metadata) .Select(m => m.Value as T).FirstOrDefault(); return true; } catch (Exception) { return false; } } public static bool TryGetSingelService<T>(this IServicePool source, [Out] [Required] T output, string descriptor) where T : class { //Requires.NotNull<ICompositionService>(compositionService, "compositionService"); //Requires.NotNull<object>(attributedPart, "attributedPart"); output = default(T); try { output = source.GetServiceInternal() .Where( m => m.Metadata.Contracts.Any(f => f == typeof (T)) && m.Metadata.Descriptor == descriptor) .Select(m => m.Value as T).FirstOrDefault(); return true; } catch (Exception) { return false; } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; namespace System.Data { /// <summary> /// Represents a bindable, queryable DataView of DataRow, that can be created from from LINQ queries over DataTable /// and from DataTable. /// </summary> internal sealed class LinqDataView : DataView, IBindingList, IBindingListView { /// <summary> /// A Comparer that compares a Key and a Row. /// </summary> internal Func<object, DataRow, int> comparerKeyRow; // comparer for DataView.Find(.. /// <summary> /// Builds the sort expression in case multiple selector/comparers are added /// </summary> internal readonly SortExpressionBuilder<DataRow> sortExpressionBuilder; /// <summary> /// Constructs a LinkDataView and its parent DataView. /// Does not create index on the DataView since filter and sort expressions are not yet provided. /// </summary> /// <param name="table">The input table from which LinkDataView is to be created.</param> internal LinqDataView(DataTable table, SortExpressionBuilder<DataRow> sortExpressionBuilder) : base(table) { Debug.Assert(table != null, "null DataTable"); this.sortExpressionBuilder = sortExpressionBuilder ?? new SortExpressionBuilder<DataRow>(); } /// <summary> /// /// </summary> /// <param name="table">Table from which to create the view</param> /// <param name="predicate_system">User-provided predicate but in the form of System.Predicate&lt;DataRow&gt; /// Predicates are being replicated in different forms so that nulls can be passed in. /// For e.g. when user provides null predicate, base.Predicate should be set to null. I cant do that in the constructor initialization /// if I will have to create System.Predicate delegate from Func. /// </param> /// <param name="comparison">The comparer function of DataRow to be used for sorting. </param> /// <param name="comparerKeyRow">A comparer function that compares a Key value to DataRow.</param> /// <param name="sortExpressionBuilder">Combined sort expression build using mutiple sort expressions.</param> internal LinqDataView( DataTable table, Predicate<DataRow> predicate_system, Comparison<DataRow> comparison, Func<object, DataRow, int> comparerKeyRow, SortExpressionBuilder<DataRow> sortExpressionBuilder) : base(table, predicate_system, comparison, DataViewRowState.CurrentRows) { this.sortExpressionBuilder = (sortExpressionBuilder == null) ? this.sortExpressionBuilder : sortExpressionBuilder; this.comparerKeyRow = comparerKeyRow; } /// <summary> /// Gets or sets the expression used to filter which rows are viewed in the LinqDataView /// </summary> public override string RowFilter { get { if (base.RowPredicate == null)// using string based filter or no filter { return base.RowFilter; } else // using expression based filter { return null; } } set { if (value == null) { base.RowPredicate = null; base.RowFilter = String.Empty; // INDEX rebuild twice } else { base.RowFilter = value; base.RowPredicate = null; } } } #region Find /// <summary> /// Searches the index and finds a single row where the sort-key matches the input key /// </summary> /// <param name="key">Value of the key to find</param> /// <returns>Index of the first match of input key</returns> internal override int FindByKey(object key) { Debug.Assert(base.Sort != null); Debug.Assert(!(!String.IsNullOrEmpty(base.Sort) && base.SortComparison != null), "string and expression based sort cannot both be set"); if (!String.IsNullOrEmpty(base.Sort)) // use find for DV's sort string { return base.FindByKey(key); } else if (base.SortComparison == null) // neither string or expr set { // This is the exception message from DataView that we want to use throw ExceptionBuilder.IndexKeyLength(0, 0); } else // find for expression based sort { if (sortExpressionBuilder.Count !=1) throw DataSetUtil.InvalidOperation(SR.Format(SR.LDV_InvalidNumOfKeys, sortExpressionBuilder.Count)); Index.ComparisonBySelector<object, DataRow> compareDelg = new Index.ComparisonBySelector<object, DataRow>(comparerKeyRow); List<object> keyList = new List<object>(); keyList.Add(key); Range range = FindRecords<object, DataRow>(compareDelg, keyList); return (range.Count == 0) ? -1 : range.Min; } } /// <summary> /// Since LinkDataView does not support multiple selectors/comparers, it does not make sense for /// them to Find using multiple keys. /// This overriden method prevents users calling multi-key find on dataview. /// </summary> internal override int FindByKey(object[] key) { // must have string or expression based sort specified if (base.SortComparison == null && String.IsNullOrEmpty(base.Sort)) { // This is the exception message from DataView that we want to use throw ExceptionBuilder.IndexKeyLength(0, 0); } else if (base.SortComparison != null && key.Length != sortExpressionBuilder.Count) { throw DataSetUtil.InvalidOperation(SR.Format(SR.LDV_InvalidNumOfKeys, sortExpressionBuilder.Count)); } if (base.SortComparison == null) { // using string to sort return base.FindByKey(key); } else { Index.ComparisonBySelector<object, DataRow> compareDelg = new Index.ComparisonBySelector<object, DataRow>(comparerKeyRow); List<object> keyList = new List<object>(); foreach (object singleKey in key) { keyList.Add(singleKey); } Range range = FindRecords<object, DataRow>(compareDelg, keyList); return (range.Count == 0) ? -1 : range.Min; } } /// <summary> /// Searches the index and finds rows where the sort-key matches the input key. /// Since LinkDataView does not support multiple selectors/comparers, it does not make sense for /// them to Find using multiple keys. This overriden method prevents users calling multi-key find on dataview. /// </summary> internal override DataRowView[] FindRowsByKey(object[] key) { // must have string or expression based sort specified if (base.SortComparison == null && String.IsNullOrEmpty(base.Sort)) { // This is the exception message from DataView that we want to use throw ExceptionBuilder.IndexKeyLength(0, 0); } else if (base.SortComparison != null && key.Length != sortExpressionBuilder.Count) { throw DataSetUtil.InvalidOperation(SR.Format(SR.LDV_InvalidNumOfKeys, sortExpressionBuilder.Count)); } if (base.SortComparison == null)// using string to sort { return base.FindRowsByKey(key); } else { Range range = FindRecords<object, DataRow>( new Index.ComparisonBySelector<object, DataRow>(comparerKeyRow), new List<object>(key)); return base.GetDataRowViewFromRange(range); } } #endregion #region Misc Overrides /// <summary> /// Overriding DataView's SetIndex to prevent users from setting RowState filter to anything other /// than CurrentRows. /// </summary> internal override void SetIndex(string newSort, DataViewRowState newRowStates, IFilter newRowFilter) { // Throw only if expressions (filter or sort) are used and rowstate is not current rows if ( (base.SortComparison != null || base.RowPredicate != null) && newRowStates != DataViewRowState.CurrentRows) { throw DataSetUtil.Argument(SR.LDVRowStateError); } else { base.SetIndex(newSort, newRowStates, newRowFilter); } } #endregion #region IBindingList /// <summary> /// Clears both expression-based and DataView's string-based sorting. /// </summary> void IBindingList.RemoveSort() { base.Sort = String.Empty; base.SortComparison = null; } /// <summary> /// Overrides IBindingList's SortProperty so that it returns null if expression based sort /// is used in the LinkDataView, otherwise it defers the result to DataView /// </summary> PropertyDescriptor IBindingList.SortProperty { get { return (base.SortComparison == null) ? base.GetSortProperty() : null; } } /// <summary> /// Overrides IBindingList's SortDescriptions so that it returns null if expression based sort /// is used in the LinkDataView, otherwise it defers the result to DataView /// </summary> ListSortDescriptionCollection IBindingListView.SortDescriptions { get { if (base.SortComparison == null) { return base.GetSortDescriptions(); } else { return new ListSortDescriptionCollection(); } } } /// <summary> /// Tells whether the LinqDataView is sorted or not /// </summary> bool IBindingList.IsSorted { get { // Sorted if either expression based sort or string based sort is set return !(base.SortComparison == null && base.Sort.Length == 0); } } #endregion } }
using System; using System.IO; using NUnit.Framework; using Raksha.Asn1; using Raksha.Asn1.Cms; using Raksha.Utilities.IO; using Raksha.Utilities.Encoders; namespace Raksha.Tests.Asn1 { [TestFixture] public class ParseTest { private static readonly byte[] classCastTest = Base64.Decode( "MIIXqAYJKoZIhvcNAQcDoIIXmTCCF5UCAQAxggG1MIIBsQIBADCBmDCBkDEL" + "MAkGA1UEBhMCVVMxETAPBgNVBAgTCE1pY2hpZ2FuMQ0wCwYDVQQHEwRUcm95" + "MQwwCgYDVQQKEwNFRFMxGTAXBgNVBAsTEEVMSVQgRW5naW5lZXJpbmcxJDAi" + "BgkqhkiG9w0BCQEWFUVsaXQuU2VydmljZXNAZWRzLmNvbTEQMA4GA1UEAxMH" + "RURTRUxJVAIDD6FBMA0GCSqGSIb3DQEBAQUABIIBAGh04C2SyEnH9J2Va18w" + "3vdp5L7immD5h5CDZFgdgHln5QBzT7hodXMVHmyGnycsWnAjYqpsil96H3xQ" + "A6+9a7yB6TYSLTNv8zhL2qU3IrfdmUJyxxfsFJlWFO1MlRmu9xEAW5CeauXs" + "RurQCT+C5tLc5uytbvw0Jqbz+Qp1+eaRbfvyhWFGkO/BYZ89hVL9Yl1sg/Ls" + "mA5jwTj2AvHkAwis+F33ZhYlto2QDvbPsUa0cldnX8+1Pz4QzKMHmfUbFD2D" + "ngaYN1tDlmezCsYFQmNx1th1SaQtTefvPr+qaqRsm8KEXlWbJQXmIfdyi0zY" + "qiwztEtO81hXZYkKqc5fKMMwghXVBgkqhkiG9w0BBwEwFAYIKoZIhvcNAwcE" + "CEq3cLLWVds9gIIVsAAik3al6Nn5pr7r0mSy9Ki3vEeCBcV9EzEG44BvNHNA" + "WyEsqQsdSxuF7h1/DJAMuZFwCbGflaRGx/1L94zrmtpeuH501lzPMvvZCmpj" + "KrOF8e1B4MVQ5TfQTdUVyRnbcDa6E4V1ZZIdAI7BgDeJttS4+L6btquXfxUg" + "ttPYQkevF7MdShYNnfLkY4vUMDOp3+iVzrOlq0elM95dfSA7OdBavgDJbz/7" + "mro3AFTytnWjGz8TUos+oUujTk9/kHOn4cEAIm0hHrNhPS5qoj3QnNduNrad" + "rLpGtcYyNlHIsYCsvPMxwoHmIw+r9xQQRjjzmVYzidn+cNOt0FmLs6YE8ds4" + "wvHRO9S69TgKPHRgk2bihgHqII9lF9qIzfG40YwJLHzGoEwVO1O0+wn8j2EP" + "O9I/Q3vreCH+5VbpUD2NGTwsMwZ3YlUesurLwse/YICxmgdN5Ro4DeQJSa9M" + "iJnRFYWRq+58cKgr+L11mNc9nApZBShlpPP7pdNqWOafStIEjo+dsY/J+iyS" + "6WLlUvNt/12qF4NAgZMb3FvRQ9PrMe87lqSRnHcpLWHcFjuKbMKCBvcdWGWI" + "R7JR8UNzUvoLGGAUI9Ck+yTq4QtfgtL5MLmdBGxSKzgs44Mmek+LnrFx+e9n" + "pkrdDf2gM/m7E50FnLYqzUjctKYGLNYpXQorq9MJx6TB20CHXcqOOoQqesXa" + "9jL9PIOtBQy1Ow5Bh4SP07nTFWFSMI/Wt4ZvNvWJj3ecA9KjMOA9EXWUDS/H" + "k9iCb2EEMo7fe5mhoyxMxPO+EIa1sEC9A1+rDACKPQCHOLI0uPmsdo0AEECC" + "QLgOQkcwQlkHexOyHiOOtBxehtGZ1eBQQZ+31DF+RRU6WvS6grg58eS4gGOQ" + "bd7CS9yYebvAQkz61J8KprWdtZuG1gBGma12wKMuQuC6RuWlKsj+rPMvaQCt" + "8mucGbkElPGZVhdyD8/BvpSCNbgRwb6iSiw4EECovu4P4GFJaMGUYEuCA711" + "itEieYc1QqS6ULjb3LFL/RcwSw0fGdjnt6B2nHckC2VsYKU1NwU7j0R1Omb4" + "y5AvSgpuWjTXWnHnE9Ey0B+KP5ERZA+jJGiwYz48ynYlvQFSbBm4I6nh/DuI" + "dWB2dLNxWuhdfzafBGtEHhLHzjW3WQwwRZsKesgHLrrj9hBUObodl1uvqvZN" + "AjMOj8DrqbGOhAClj1t4S1Zk1ZekuMjsuoxEL+/lgtbT+056ES0k3A/LnpRb" + "uxA1ZBr26Im+GVFzEcsV0hB4vNujSwStTTZH5jX5rMyi085yJfnikcLYUn9N" + "apl+srhpIZlDJPw7IHaw8tsqXKDxF7MozIXo8B45CKv5Am+BMrIemCMX/ehu" + "PODICl98Ur8tNAn1L+m0nj7H3c8HW2vNuBLEI3SEHHgm2Ij3IY5pyyeVUaWC" + "pumhy8Ru5dj3fZcfKgYuJBQxWMf+UqPsf4iUK3923pouJ1cQ8XU8gOXIRrtX" + "e41d/yR+UAZXSig6SITLw+wLtvitSvtxvjcUSUOI9CYTovKyuz1PQKiaLsV5" + "4CoJhMQ5uRlVFS3H829I2d2gLRpSp6pNWeIZO2NMBxPYf2qcSHyHqQjR7xP2" + "ZTg7U3OO6dZHORfXxzAnW2ExavBIYQmZh1gLn5jSS4wXFPXyvnJAsF4s5wed" + "YHsyAqM/ek0n2Oo/zAh7UcP2vcb9FOoeRK8qC9HjTciS6WbjskRN0ft4T69G" + "+1RsH8/edBxo2LZeA48BSCXDXOlBZJBsOptzYJD8HSZONPnef0jn23lk0fkU" + "C3BjJu2ubFChctRvJniTko4klpidkHwuJgrTnL4er8rG3RfiiEHn/d5era15" + "E1cekdVYWqwQOObOd4v+0gZSJgI48TBc5Qdy8F6wIU38DR2pn/5uNthNDgXk" + "NcV9a2gOE3DoLe8CEIPMihqYMPY8NuSp97eHB2YhKpjP7qX9TUMoOdE2Iat2" + "klNxadJt6JTFeiBPL6R9RHAD5sVBrkrl0S+oYtgF92f9WHVwAXU7zP6IgM4x" + "hhzeJT07yyIp44mKd//F+7ntbgQjZ/iLbHh0mtOlUmzkFsDR0UNSXEQoourZ" + "EY4A62HXj0DMqEQbik6QwEF7FKuwZX2opdOyVKH9MzJxNfDLd5dc8wAc8bCX" + "jcCx5/GzHx2S5DndWQEVhp2hOQYuoJS3r6QCYFaHtDPKnFHS2PBFyFWL+2UK" + "c0WsvVaHYqYKnksmxse9I9oU75kx5O05DZCThPX6h8J8MHRuxU9tcuuleIUQ" + "XY8On+JeEtLSUZgp+Z7ITLuagf6yuKQpaR396MlDii/449/dvBiXAXeduyO1" + "QzSkQCh37fdasqGL3mP0ssMcxM/qpOwQsx3gMtwiHQRi1oQE1QHb8qZHDE4m" + "I5afQJ9O/H/m/EVlGUSn2yYOsPlZrWuI3BBZKoRzRq1lZOQDtOh18BE3tWmX" + "viGIAxajam0i2Ce3h2U7vNwtiePRNEgPmQ7RwTTv0U6X8qqkjeYskiF4Cv9G" + "nrB0WreC19ih5psEWLIkCYKTr+OhQuRrtv7RcyUi9QSneh7BjcvRjlGB6joA" + "F6J4Y6ENAA/nzOZJ699VkljTi59bbNJYlONpQhOeRTu8M/wExkIJz7yR9DTY" + "bY4/JdbdHNFf5DSDmYAHaFLmdnnfuRy+tC9CGGJvlcLVv5LMFJQGt2Wi15p8" + "lctx7sL6yNCi7OakWbEOCvGPOxY7ejnvOjVK/Krx1T+dAXNUqrsDZmvmakOP" + "We+P4Di1GqcyLVOTP8wNCkuAUoN0JFoBHy336/Xnae91KlY4DciPMpEOIpPN" + "oB+3h6CozV7IWX5Wh3rhfC25nyGJshIBUS6cMXAsswQI8rOylMlGaekNcSU4" + "gNKNDZAK5jNkS0Z/ziIrElSvMNTfYbnx3gCkY0pV18uadmchXihVT11Bt77O" + "8KCKHycR39WYFIRO09wvGv6P42CRBFTdQbWFtkSwRiH8l6x39Z7pIkDFxokT" + "Dp6Htkj3ywfQXNbFgRXZUXqgD1gZVFDFx920hcJnuu65CKz6pEL6X0XUwNPg" + "vtraA2nj4wjVB/y+Cxc+1FgzeELB4CAmWO1OfRVLjYe7WEe/X5DPT6p8HBkB" + "5mWuv+iQ3e37e1Lrsjt2frRYQWoOSP5Lv7c8tZiNfuIp07IYnJKBWZLTqNf9" + "60uiY93ssE0gr3mfYOj+fSbbjy6NgAenT7NRZmFCjFwAfmapIV0hJoqnquaN" + "jj5KKOP72hp+Zr9l8cEcvIhG/BbkY3kYbx3JJ9lnujBVr69PphHQTdw67CNB" + "mDkH7y3bvZ+YaDY0vdKOJif9YwW2qoALXKgVBu1T2BONbCTIUTOzrKhWEvW8" + "D6x03JsWrMMqOKeoyomf1iMt4dIOjp7yGl/lQ3iserzzLsAzR699W2+PWrAT" + "5vLgklJPX/Fb3Tojbsc074lBq669WZe3xzlj85hFcBmoLPPyBE91BLhEwlGC" + "+lWmwFOENLFGZE0mGoRN+KYxwqfA2N6H8TWoz6m0oPUW4uQvy9sGtYTSyQO9" + "6ZwVNT3ndlFrP5p2atdEFVc5aO5FsK8/Fenwez06B2wv9cE9QTVpFrnJkKtF" + "SaPCZkignj64XN7cHbk7Ys6nC3WIrTCcj1UOyp5ihuMS9eL9vosYADsmrR6M" + "uqqeqHsf2+6U1sO1JBkDYtLzoaILTJoqg9/eH7cTA0T0mEfxVos9kAzk5nVN" + "nVOKFrCGVIbOStpYlWP6wyykIKVkssfO6D42D5Im0zmgUwgNEkB+Vxvs8bEs" + "l1wPuB2YPRDCEvwM3A5d5vTKhPtKMECIcDxpdwkD5RmLt+iaYN6oSFzyeeU0" + "YvXBQzq8gfpqJu/lP8cFsjEJ0qCKdDHVTAAeWE6s5XpIzXt5cEWa5JK7Us+I" + "VbSmri4z0sVwSpuopXmhLqLlNWLGXRDyTjZSGGJbguczXCq5XJ2E3E4WGYd6" + "mUWhnP5H7gfW7ILOUN8HLbwOWon8A6xZlMQssL/1PaP3nL8ukvOqzbIBCZQY" + "nrIYGowGKDU83zhO6IOgO8RIVQBJsdjXbN0FyV/sFCs5Sf5WyPlXw/dUAXIA" + "cQiVKM3GiVeAg/q8f5nfrr8+OD4TGMVtUVYujfJocDEtdjxBuyFz3aUaKj0F" + "r9DM3ozAxgWcEvl2CUqJLPHH+AWn5kM7bDyQ2sTIUf5M6hdeick09hwrmXRF" + "NdIoUpn7rZORh0h2VX3XytLj2ERmvv/jPVC97VKU916n1QeMJLprjIsp7GsH" + "KieC1RCKEfg4i9uHoIyHo/VgnKrnTOGX/ksj2ArMhviUJ0yjDDx5jo/k5wLn" + "Rew2+bhiQdghRSriUMkubFh7TN901yl1kF2BBP5PHbpgfTP6R7qfl8ZEwzzO" + "elHe7t7SvI7ff5LkwDvUXSEIrHPGajYvBNZsgro+4Sx5rmaE0QSXACG228OQ" + "Qaju8qWqA2UaPhcHSPHO/u7ad/r8kHceu0dYnSFNe1p5v9Tjux0Yn6y1c+xf" + "V1cu3plCwzW3Byw14PH9ATmi8KJpZQaJOqTxn+zD9TvOa93blK/9b5KDY1QM" + "1s70+VOq0lEMI6Ch3QhFbXaslpgMUJLgvEa5fz3GhmD6+BRHkqjjwlLdwmyR" + "qbr4v6o+vnJKucoUmzvDT8ZH9nH2WCtiiEtQaLNU2vsJ4kZvEy0CEajOrqUF" + "d8qgEAHgh9it5oiyGBB2X/52notXWOi6OMKgWlxxKHPTJDvEVcQ4zZUverII" + "4vYrveRXdiDodggfrafziDrA/0eEKWpcZj7fDBYjUBazwjrsn5VIWfwP2AUE" + "wNn+xR81/so8Nl7EDBeoRXttyH7stbZYdRnkPK025CQug9RLzfhEAgjdgQYw" + "uG+z0IuyctJW1Q1E8YSOpWEFcOK5okQkLFUfB63sO1M2LS0dDHzmdZriCfIE" + "F+9aPMzojaHg3OQmZD7MiIjioV6w43bzVmtMRG22weZIYH/Sh3lDRZn13AS9" + "YV6L7hbFtKKYrie79SldtYazYT8FTSNml/+Qv2TvYTjVwYwHpm7t479u+MLh" + "LxMRVsVeJeSxjgufHmiLk7yYJajNyS2j9Kx/fmXmJbWZNcerrfLP+q+b594Y" + "1TGWr8E6ZTh9I1gU2JR7WYl/hB2/eT6sgSYHTPyGSxTEvEHP242lmjkiHY94" + "CfiTMDu281gIsnAskl05aeCBkj2M5S0BWCxy7bpVAVFf5nhf74EFIBOtHaJl" + "/8psz1kGVF3TzgYHkZXpUjVX/mJX8FG0R8HN7g/xK73HSvqeamr4qVz3Kmm/" + "kMtYRbZre7E1D10qh/ksNYnOkYBcG4P2JyjZ5q+8CQNungz2/b0Glg5LztNz" + "hUgG27xDOUraJXjkkZl/GOh0eTqhfLHXC/TfyoEAQOPcA59MKqvroFC5Js0Q" + "sTgqm2lWzaLNz+PEXpJHuSifHFXaYIkLUJs+8X5711+0M03y8iP4jZeEOrjI" + "l9t3ZYbazwsI3hBIke2hGprw4m3ZmSvQ22g+N6+hnitnDALMsZThesjb6aJd" + "XOwhjLkWRD4nQN594o6ZRrfv4bFEPTp4ev8l6diouKlXSFFnVqz7AZw3Pe53" + "BvIsoh66zHBpZhauPV/s/uLb5x6Z8sU2OK6AoJ7b8R9V/AT7zvonBi/XQNw3" + "nwkwGnTS9Mh7PFnGHLJWTKKlYXrSpNviR1vPxqHMO6b+Lki10d/YMY0vHQrY" + "P6oSVkA6RIKsepHWo11+rV838+2NRrdedCe91foUmOs+eoWQnwmTy2CTZmQ5" + "b7/TTcau9ewimZAqI+MtDWcmWoZfgibZmnIITGcduNOJDRn+aLt9dz+zr1qA" + "HxlLXCOyBPdtfx6eo4Jon+fVte37i3HmxHk+8ZGMMSS9hJbLQEkA59b4E+7L" + "GI3JZjvEkhizB4n/aFeG7KT7K3x072DMbHLZ7VgsXQ1VDDmcZmizFwgyNqKy" + "hKCKxU+I2O10IMtiZUpEzV1Pw7hD5Kv/eFCsJFPXOJ2j3KP6qPtX5IYki1qH" + "Juo5C5uGKtqNc6OzkXsvNUfBz5sJkEYl0WfitSSo4ARyshFUNh2hGxNxUVKM" + "2opOcuHSxBgwUSmVprym50C305zdHulBXv3mLzGjvRstE9qfkQ8qVJYLQEkL" + "1Yn7E92ex71YsC8JhNNMy0/YZwMkiFrqyaFd/LrblWpBbGumhe4reCJ4K3mk" + "lFGEsICcMoe+zU1+QuLlz/bQ+UtvClHUe8hTyIjfY04Fwo2vbdSc1U/SHho5" + "thQy+lOZ/HijzCmfWK3aTqYMdwCUTCsoxri2N8vyD/K2kbMLQWUfUlBQfDOK" + "VrksBoSfcluNVaO56uEUw3enPhhJghfNlJnpr5gUcrAMES53DfkjNr0dCsfM" + "JOY2ZfQEwwYey1c4W1MNNMoegSTg4aXzjVc0xDgKa7RGbtRmVNbOxIhUNAVi" + "thQV3Qujoz1ehDt2GyLpjGjHSpQo3WlIU4OUqJaQfF6EH+3khFqUmp1LT7Iq" + "zH3ydYsoCDjvdXSSEY3hLcZVijUJqoaNWBLb/LF8OG5qTjsM2gLgy2vgO/lM" + "NsqkHnWTtDimoaRRjZBlYLhdzf6QlfLi7RPmmRriiAOM0nXmylF5xBPHQLoz" + "LO9lXYIfNbVJVqQsV43z52MvEQCqPNpGqjB+Au/PZalYHbosiVOQLgTB9hTI" + "sGutSXXeLnf5rftCFvWyL3n5DgURzDFLibrbyVGGKAk166bK1RyVP9XZJonr" + "hPYELk4KawCysJJSmC0E8sSsuXpfd6PPDru6nCV1EdXKR7DybS7NVHCktiPR" + "4B4y8O/AgfJX8sb6LuxmjaINtUKEJ1+O88Gb69uy6b/Kpu2ri/SUBaNNw4Sn" + "/tuaD+jxroL7RlZmt9ME/saNKn9OmLuggd6IUKAL4Ifsx9i7+JKcYuP8Cjdf" + "Rx6U6H4qkEwwYGXnZYqF3jxplyOfqA2Vpvp4rnf8mST6dRLKk49IhKGTzwZr" + "4za/RZhyl6lyoRAFDrVs1b+tj6RYZk0QnK3dLiN1MFYojLyz5Uvi5KlSyFw9" + "trsvXyfyWdyRmJqo1fT7OUe0ImJW2RN3v/qs1k+EXizgb7DW4Rc2goDsCGrZ" + "ZdMwuAdpRnyg9WNtmWwp4XXeb66u3hJHr4RwMd5oyKFB1GsmzZF7aOhSIb2B" + "t3coNXo/Y+WpEj9fD7/snq7I1lS2+3Jrnna1048O7N4b5S4b5TtEcCBILP1C" + "SRvaHyZhBtJpoH6UyimKfabXi08ksrcHmbs1+HRvn+3pl0bHcdeBIQS/wjk1" + "TVEDtaP+K9zkJxaExtoa45QvqowxtcKtMftNoznF45LvwriXEDV9jCXvKMcO" + "nxG5aQ//fbnn4j4q1wsKXxn61wuLUW5Nrg9fIhX7nTNAAooETO7bMUeOWjig" + "2S1nscmtwaV+Sumyz/XUhvWynwE0AXveLrA8Gxfx"); private static readonly byte[] derExpTest = Base64.Decode( "MIIS6AYJKoZIhvcNAQcDoIIS2TCCEtUCAQAxggG1MIIBsQIBADCBmDCBkDEL" + "MAkGA1UEBhMCVVMxETAPBgNVBAgTCE1pY2hpZ2FuMQ0wCwYDVQQHEwRUcm95" + "MQwwCgYDVQQKEwNFRFMxGTAXBgNVBAsTEEVMSVQgRW5naW5lZXJpbmcxJDAi" + "BgkqhkiG9w0BCQEWFUVsaXQuU2VydmljZXNAZWRzLmNvbTEQMA4GA1UEAxMH" + "RURTRUxJVAIDD6FBMA0GCSqGSIb3DQEBAQUABIIBAGsRYK/jP1YujirddAMl" + "ATysfLCwd0eZhENohVqLiMleH25Dnwf+tBaH4a9hyW+7VrWw/LC6ILPVbKpo" + "oLBAOical40cw6C3zulajc4gM3AlE2KEeAWtI+bgPMXhumqiWDb4byX/APYk" + "53Gk7WXF6Xs4hj3tmrHSJxCUOsTdHKUJYvOqjwKGARPQDjP0EUbVJezeAwBA" + "RMlJ/qBVLBj2UW28n5oJZm3oaSaU93Uc6GPVIk43IWrmEUcWVPiMfUtUCwcX" + "tRNtHuQ9os++rmdNBiuB5p+vtUeA45KWnTUtkwJXvrzE6Sf9AUH/p8uOvvZJ" + "3yt9LhPxcZukGIVvcQnBxLswghEVBgkqhkiG9w0BBwEwFAYIKoZIhvcNAwcE" + "CGObmTycubs2gIIQ8AKUC8ciGPxa3sFJ1EPeX/nRwYGNAarlpVnG+07NITL2" + "pUzqZSgsYh5JiKd8TptQBZNdebzNmCvjrVv5s9PaescGcypL7FNVPEubh0w/" + "8h9rTACqUpF5yRgfcgpAGeK29F1hyZ1WaIH43avUCaDnrZcOKB7wc1ats1aQ" + "TSDLImyFn4KjSo5k0Ec/xSoWnfg391vebp8eOsyHZhFMffFtKQMaayZNHJ7Q" + "BzG3r/ysUbkgI5x+0bX0QfZjEIs7yuV5Wt8DxMTueCm3RQ+HkR4lNdTBkM4V" + "qozCqC1SjcAF5YHB0WFkGouEPGgTlmyvLqR2xerEXVZn9YwSnT48kOde3oGt" + "EAYyg0yHbNbL0sp6LDM7upRmrgWwxf0BR6lP4wyWdv/XSLatEB7twSNiPBJ4" + "PJ+QagK08yQJ84UB7YpMTudKsaUs7zW76eA7KkW3TndfDYGdhbmZ5wxNl+5x" + "yPZc/jcQHW7vplMfWglUVxnzibNW12th0QXSB57Mzk8v1Rvc/HLGvAOJZG/S" + "N12FZOxbUrMIHGi3kXsmfWznVyq92X4P9tuDDD7sxkSGsyUAm/UJIZ3KsXhV" + "QeaRHVTVDxtJtnbYxBupy1FDBO6AhVrp16Blvnip9cPn/aLfxDoFHzmsZmEg" + "IcOFqpT1fW+KN6i/JxLD3mn3gKzzdL1/8F36A2GxhCbefQFp0MfIovlnMLFv" + "mrINwMP8a9VnP8gIV5oW5CxmmMUPHuGkXrfg+69iVACaC2sTq6KGebhtg9OC" + "8vZhmu7+Eescst694pYa3b8Sbr5bTFXV68mMMjuRnhvF2NZgF+O0jzU+sFps" + "o7s1rUloCBk1clJUJ/r+j9vbhVahCeJQw62JAqjZu4R1JYAzON3S7jWU5zJ7" + "pWYPSAQkLYUz3FmRRS2Yv65mXDNHqR9vqkHTIphwA9CLMKC2rIONxSVB57q1" + "Npa/TFkVdXnw+cmYjyFWiWeDP7Mw0Kwy7tO008UrBY0rKQU466RI5ezDqYPc" + "Lm73dUH2EjUYmKUi8zCtXpzgfTYVa/DmkbVUL9ThHMVRq1OpT2nctE7kpXZk" + "OsZjEZHZX4MCrSOlc10ZW7MJIRreWMs70n7JX7MISU+8fK6JKOuaQNG8XcQp" + "5IrCTIH8vmN2rVt4UT8zgm640FtO3jWUxScvxCtUJJ49hGCwK+HwDDpO6fLw" + "LFuybey+6hnAbtaDyqgsgDh2KN8GSkQT9wixqwQPWsMQ4h0xQixf4IMdFOjP" + "ciwp3ul8KAp/q70i0xldWGqcDjUasx6WHKc++rFjVJjoVvijKgEhlod5wJIw" + "BqQVMKRsXle07NS1MOB+CRTVW6mwBEhDDERL+ym2GT2Q4uSDzoolmLq2y5vL" + "+RfDHuh3W0UeC3Q5D2bJclgMsVjgfQUN19iD+lPFp2xvLTaNWi5fYDn4uuJL" + "lgVDXIMmM8I+Z2hlTXTM1Pldz2/UFe3QXTbYnjP6kfd7Bo2Webhhgs/YmSR2" + "XPuA42tWNAAjlK77lETWodxi3UC7XELjZ9xoGPRbxjOklXXvev9v5Vo+vcmN" + "0KrLXhLdkyHRSm81SRsWoadCTSyT8ibv66P00GOt+OlIUOt0YKSUkULQfPvC" + "EgMpeTm1/9l8n9bJ6td5fpJFDqLDm+FpJX6T2sWevV/Tyt6aoDPuET5iHBHW" + "PoHxKl8YPRHBf+nRWoh45QMGQWNSrJRDlO8oYOhdznh4wxLn3DXEfDr0Z7Kd" + "gEg6xr1XCobBn6Gi7wWXp5FDTaRF41t7fH8VxPwwDa8Yfu3vsgB6q426kjAj" + "Q77wx1QFIg8gOYopTOgqze1i4h1U8ehP9btznDD6OR8+hPsVKoXYGp8Ukkc7" + "JBA0o8l9O2DSGh0StsD94UhdYzn+ri7ozkXFy2SHFT2/saC34NHLoIF0v/aw" + "L9G506Dtz6xXOACZ4brCG+NNnPLIcGblXIrYTy4+sm0KSdsl6BGzYh9uc8tu" + "tfCh+iDuhT0n+nfnvdCmPwonONFb53Is1+dz5sisILfjB7OPRW4ngyfjgfHm" + "oxxHDC/N01uoJIdmQRIisLi2nLhG+si8+Puz0SyPaB820VuV2mp77Y2osTAB" + "0hTDv/sU0DQjqcuepYPUMvMs3SlkEmaEzNSiu7xOOBQYB8FoK4PeOXDIW6n2" + "0hv6iS17hcZ+8GdhwC4x2Swkxt99ikRM0AxWrh1lCk5BagVN5xG79c/ZQ1M7" + "a0k3WTzYF1Y4d6QPNOYeOBP9+G7/a2o3hGXDRRXnFpO7gQtlXy9A15RfvsWH" + "O+UuFsOTtuiiZk1qRgWW5nkSCPCl2rP1Z7bwr3VD7o6VYhNCSdjuFfxwgNbW" + "x8t35dBn6xLkc6QcBs2SZaRxvPTSAfjON++Ke0iK5w3mec0Br4QSNB1B0Aza" + "w3t3AleqPyJC6IP1OQl5bi+PA+h3YZthwQmcwgXgW9bWxNDqUjUPZfsnNNDX" + "MU9ANDLjITxvwr3F3ZSfJyeeDdbhr3EJUTtnzzWC6157EL9dt0jdPO35V0w4" + "iUyZIW1FcYlCJp6t6Sy9n3TmxeLbq2xML4hncJBClaDMOp2QfabJ0XEYrD8F" + "jq+aDM0NEUHng+Gt9WNqnjc8GzNlhxTNm3eQ6gyM/9Ip154GhH6c9hsmkMy5" + "DlMjGFpFnsSTNFka2+DOzumWUiXLGbe4M3RePl1N4MLwXrkR2llguQynyoqF" + "Ptat2Ky5yW2q9+IQHY49NJTlsCpunE5HFkAK9rY/4lM4/Q7hVunP6U4a0Kbu" + "beFuOQMKQlBZvcplnYBefXD79uarY/q7ui6nFHlqND5mlXMknMrsQk3papfp" + "OpMS4T07rCTLek0ODtb5KsHdIF76NZXevko4+d/xbv7HLCUYd8xuOuqf+y4I" + "VJiT1FmYtZd9w+ubfHrOfHxY+SBtN6fs02WAccZqBXUYzZEijRbN2YUv1OnG" + "rfYe4EcfOu/Sa+wLbB7msYpLfvUfEO3iseKf4LXZkgtF5P610PBZR8edeSgr" + "YZW+J0K78PRAl5nEi1mvzBxi9DyNf6iQ9mWLyyCmr9p9HGE+aCMKVCn9jfZH" + "WeBDAJNYDcUh5NEckqJtbEc2S1FJM7yZBWLQUt3NCQvj+nvQT45osZ3BJvFg" + "IcGJ0CysoblVz4fCLybrYxby9HP89WMLHqdqsIeVX8IJ3x84SqLPuzrqf9FT" + "ZVYLo0F2oBjAzjT7obt9+NJc/psOMCg+OGQkAfwj3VNvaqkkQsVxSiozgxrC" + "7KaTXuAL6eKKspman96kz4QVk9P0usUPii+LFnW4XYc0RNfgJVO6BgJT7pLX" + "NWwv/izMIMNAqSiWfzHHRVkhq4f1TMSF91auXOSICpJb3QQ4XFh52Mgl8+zs" + "fobsb0geyb49WqFrZhUu+X+8LfQztppGmiUpFL+8EW0aPHbfaf4y9J1/Wthy" + "c28Yqu62j/ljXq4Qa21uaEkoxzH1wPKCoKM9TXJtZJ39Yl9cf119Qy4M6QsB" + "6oMXExlMjqIMCCWaLXLRiqbc2Y7rZHgEr08msibdoYHbSkEl8U+Kii2p6Vdx" + "zyiEIz4CadrFbrAzxmrR/+3u8JuBdq0K3KNR0WWx73BU+G0rgBX56GnP7Ixy" + "fuvkRb4YfJUF4PkDa50BGVhybPrIhoFteT6bSh6LQtBm9c4Kop8Svx3ZbqOT" + "kgQDa0n+O0iR7x3fvNZ0Wz4YJrKGnVOPCqJSlSsnX6v2JScmaNdrSwkMTnUf" + "F9450Hasd88+skC4jVAv3WAB03Gz1MtiGDhdUKFnHnU9HeHUnh38peCFEfnK" + "WihakVQNfc72YoFVZHeJI5fJAW8P7xGTZ95ysyirtirxt2zkRVJa5p7semOw" + "bL/lBC1bp4J6xHF/NHY8NQjvuhqkDyNlh3dRpIBVBu6Z04hRhLFW6IBxcCCv" + "pjfoxJoox9yxKQKpr3J6MiZKBlndZRbSogO/wYwFeh7HhUzMNM1xIy3jWVVC" + "CrzWp+Q1uxnL74SwrMP/EcZh+jZO4CYWk6guUMhTo1kbW03BZfyAqbPM+X+e" + "ZqMZljydH8AWgl0MZd2IAfajDxI03/6XZSgzq24n+J7wKMYWS3WzB98OIwr+" + "oKoQ7aKwaaT/KtR8ggUVYsCLs4ScFY24MnjUvMm+gQcVyeX74UlqR30Aipnf" + "qzDRVcAUMMNcs0fuqePcrZ/yxPo+P135YClPDo9J8bwNpioUY8g+BQxjEQTj" + "py3i2rAoX+Z5fcGjnZQVPMog0niIvLPRJ1Xl7yzPW0SevhlnMo6uDYDjWgQ2" + "TLeTehRCiSd3z7ZunYR3kvJIw1Kzo4YjdO3l3WNf3RQvxPmJcSKzeqKVxWxU" + "QBMIC/dIzmRDcY787qjAlKDZOdDp7qBKIqnfodWolxBA0KhvE61eYabZqUCT" + "G2HJaQE1SvOdL9KM4ORFlxE3/dqv8ttBJ6N1qKk423CJjajZHYTwf1dCfj8T" + "VAE/A3INTc6vg02tfkig+7ebmbeXJRH93KveEo2Wi1xQDsWNA+3DVzsMyTqV" + "+AgfSjjwKouXAznhpgNc5QjmD2I6RyTf+hngftve18ZmVhtlW5+K6qi62M7o" + "aM83KweH1QgCS12/p2tMEAfz//pPbod2NrFDxnmozhp2ZnD04wC+6HGz6bX/" + "h8x2PDaXrpuqnZREFEYzUDKQqxdglXj5oE/chBR8+eBfYSS4JW3TBkW6RfwM" + "KOBBOOv8pe3Sfq/bg7OLq5bn0jKwulqP50bysZJNlQUG/KqJagKRx60fnTqB" + "7gZRebvtqgn3JQU3fRCm8ikmGz9XHruoPlrUQJitWIt4AWFxjyl3oj+suLJn" + "7sK62KwsqAztLV7ztoC9dxldJF34ykok1XQ2cMT+uSrD6ghYZrmrG5QDkiKW" + "tOQCUvVh/CorZNlON2rt67UvueMoW+ua25K4pLKDW316c2hGZRf/jmCpRSdb" + "Xr3RDaRFIK6JpmEiFMMOEnk9yf4rChnS6MHrun7vPkf82w6Q0VxoR8NRdFyW" + "3mETtm2mmG5zPFMMD8uM0BYJ/mlJ2zUcD4P3hWZ8NRiU5y1kazvrC6v7NijV" + "o459AKOasZUj1rDMlXDLPloTHT2ViURHh/8GKqFHi2PDhIjPYUlLR5IrPRAl" + "3m6DLZ7/tvZ1hHEu9lUMMcjrt7EJ3ujS/RRkuxhrM9BFlwzpa2VK8eckuCHm" + "j89UH5Nn7TvH964K67hp3TeV5DKV6WTJmtIoZKCxSi6FFzMlky73gHZM4Vur" + "eccwycFHu+8o+tQqbIAVXaJvdDstHpluUCMtb2SzVmI0bxABXp5XrkOOCg8g" + "EDZz1I7rKLFcyERSifhsnXaC5E99BY0DJ/7v668ZR3bE5cU7Pmo/YmJctK3n" + "m8cThrYDXJNbUi0c5vrAs36ZQECn7BY/bdDDk2NPgi36UfePI8XsbezcyrUR" + "ZZwT+uQ5LOB931NjD5GOMEb96cjmECONcRjB0uD7DoTiVeS3QoWmf7Yz4g0p" + "v9894YWQgOl+CvmTERO4dxd7X5wJsM3Y0acGPwneDF+HtQrIpJlslm2DivEv" + "sikc6DtAQrnVRSNDr67HPPeIpgzThbxH3bm5UjvnP/zcGV1W8Nzk/OBQWi0l" + "fQM9DccS6P/DW3XPSD1+fDtUK5dfH8DFf8wwgnxeVwi/1hCBq9+33XPwiVpz" + "489DnjGhHqq7BdHjTIqAZvNm8UPQfXRpeexbkFZx1mJvS7so54Cs58/hHgQN" + "GHJh4AUCLEt0v7Hc3CMy38ovLr3Q8eZsyNGKO5GvGNa7EffGjzOKxgqtMwT2" + "yv8TOTFCWnZEUTtVA9+2CpwfmuEjD2UQ4vxoM+o="); private static readonly byte[] longTagged = Hex.Decode("9f1f023330"); [Test] public void TestClassCast() { ParseEnveloped(classCastTest); } [Test] public void TestDerExp() { ParseEnveloped(derExpTest); } [Test] public void TestLongTag() { Asn1StreamParser aIn = new Asn1StreamParser(longTagged); Asn1TaggedObjectParser tagged = (Asn1TaggedObjectParser)aIn.ReadObject(); Assert.AreEqual(31, tagged.TagNo); } private void ParseEnveloped( byte[] data) { Asn1StreamParser aIn = new Asn1StreamParser(data); ContentInfoParser cP = new ContentInfoParser((Asn1SequenceParser)aIn.ReadObject()); EnvelopedDataParser eP = new EnvelopedDataParser((Asn1SequenceParser)cP.GetContent(Asn1Tags.Sequence)); eP.GetRecipientInfos().ToAsn1Object(); // Must drain the parser! EncryptedContentInfoParser ecP = eP.GetEncryptedContentInfo(); Asn1OctetStringParser content = (Asn1OctetStringParser)ecP.GetEncryptedContent(Asn1Tags.OctetString); Streams.Drain(content.GetOctetStream()); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using 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.V10.Services { /// <summary>Settings for <see cref="ReachPlanServiceClient"/> instances.</summary> public sealed partial class ReachPlanServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="ReachPlanServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="ReachPlanServiceSettings"/>.</returns> public static ReachPlanServiceSettings GetDefault() => new ReachPlanServiceSettings(); /// <summary>Constructs a new <see cref="ReachPlanServiceSettings"/> object with default settings.</summary> public ReachPlanServiceSettings() { } private ReachPlanServiceSettings(ReachPlanServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); ListPlannableLocationsSettings = existing.ListPlannableLocationsSettings; ListPlannableProductsSettings = existing.ListPlannableProductsSettings; GenerateProductMixIdeasSettings = existing.GenerateProductMixIdeasSettings; GenerateReachForecastSettings = existing.GenerateReachForecastSettings; OnCopy(existing); } partial void OnCopy(ReachPlanServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>ReachPlanServiceClient.ListPlannableLocations</c> and /// <c>ReachPlanServiceClient.ListPlannableLocationsAsync</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 ListPlannableLocationsSettings { 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>ReachPlanServiceClient.ListPlannableProducts</c> and <c>ReachPlanServiceClient.ListPlannableProductsAsync</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 ListPlannableProductsSettings { 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>ReachPlanServiceClient.GenerateProductMixIdeas</c> and /// <c>ReachPlanServiceClient.GenerateProductMixIdeasAsync</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 GenerateProductMixIdeasSettings { 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>ReachPlanServiceClient.GenerateReachForecast</c> and <c>ReachPlanServiceClient.GenerateReachForecastAsync</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 GenerateReachForecastSettings { 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="ReachPlanServiceSettings"/> object.</returns> public ReachPlanServiceSettings Clone() => new ReachPlanServiceSettings(this); } /// <summary> /// Builder class for <see cref="ReachPlanServiceClient"/> to provide simple configuration of credentials, endpoint /// etc. /// </summary> internal sealed partial class ReachPlanServiceClientBuilder : gaxgrpc::ClientBuilderBase<ReachPlanServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public ReachPlanServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public ReachPlanServiceClientBuilder() { UseJwtAccessWithScopes = ReachPlanServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref ReachPlanServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<ReachPlanServiceClient> task); /// <summary>Builds the resulting client.</summary> public override ReachPlanServiceClient Build() { ReachPlanServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<ReachPlanServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<ReachPlanServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private ReachPlanServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return ReachPlanServiceClient.Create(callInvoker, Settings); } private async stt::Task<ReachPlanServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return ReachPlanServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => ReachPlanServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => ReachPlanServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => ReachPlanServiceClient.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>ReachPlanService client wrapper, for convenient use.</summary> /// <remarks> /// Reach Plan Service gives users information about audience size that can /// be reached through advertisement on YouTube. In particular, /// GenerateReachForecast provides estimated number of people of specified /// demographics that can be reached by an ad in a given market by a campaign of /// certain duration with a defined budget. /// </remarks> public abstract partial class ReachPlanServiceClient { /// <summary> /// The default endpoint for the ReachPlanService 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 ReachPlanService scopes.</summary> /// <remarks> /// The default ReachPlanService 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="ReachPlanServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="ReachPlanServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="ReachPlanServiceClient"/>.</returns> public static stt::Task<ReachPlanServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new ReachPlanServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="ReachPlanServiceClient"/> using the default credentials, endpoint and /// settings. To specify custom credentials or other settings, use <see cref="ReachPlanServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="ReachPlanServiceClient"/>.</returns> public static ReachPlanServiceClient Create() => new ReachPlanServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="ReachPlanServiceClient"/> 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="ReachPlanServiceSettings"/>.</param> /// <returns>The created <see cref="ReachPlanServiceClient"/>.</returns> internal static ReachPlanServiceClient Create(grpccore::CallInvoker callInvoker, ReachPlanServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } ReachPlanService.ReachPlanServiceClient grpcClient = new ReachPlanService.ReachPlanServiceClient(callInvoker); return new ReachPlanServiceClientImpl(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 ReachPlanService client</summary> public virtual ReachPlanService.ReachPlanServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of plannable locations (for example, countries &amp;amp; DMAs). /// /// 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 ListPlannableLocationsResponse ListPlannableLocations(ListPlannableLocationsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of plannable locations (for example, countries &amp;amp; DMAs). /// /// 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<ListPlannableLocationsResponse> ListPlannableLocationsAsync(ListPlannableLocationsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of plannable locations (for example, countries &amp;amp; DMAs). /// /// 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<ListPlannableLocationsResponse> ListPlannableLocationsAsync(ListPlannableLocationsRequest request, st::CancellationToken cancellationToken) => ListPlannableLocationsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// 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 ListPlannableProductsResponse ListPlannableProducts(ListPlannableProductsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// 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<ListPlannableProductsResponse> ListPlannableProductsAsync(ListPlannableProductsRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// 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<ListPlannableProductsResponse> ListPlannableProductsAsync(ListPlannableProductsRequest request, st::CancellationToken cancellationToken) => ListPlannableProductsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="plannableLocationId"> /// Required. The ID of the selected location for planning. To list the available /// plannable location ids use [ReachPlanService.ListPlannableLocations][google.ads.googleads.v10.services.ReachPlanService.ListPlannableLocations]. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual ListPlannableProductsResponse ListPlannableProducts(string plannableLocationId, gaxgrpc::CallSettings callSettings = null) => ListPlannableProducts(new ListPlannableProductsRequest { PlannableLocationId = gax::GaxPreconditions.CheckNotNullOrEmpty(plannableLocationId, nameof(plannableLocationId)), }, callSettings); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="plannableLocationId"> /// Required. The ID of the selected location for planning. To list the available /// plannable location ids use [ReachPlanService.ListPlannableLocations][google.ads.googleads.v10.services.ReachPlanService.ListPlannableLocations]. /// </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<ListPlannableProductsResponse> ListPlannableProductsAsync(string plannableLocationId, gaxgrpc::CallSettings callSettings = null) => ListPlannableProductsAsync(new ListPlannableProductsRequest { PlannableLocationId = gax::GaxPreconditions.CheckNotNullOrEmpty(plannableLocationId, nameof(plannableLocationId)), }, callSettings); /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RequestError]() /// </summary> /// <param name="plannableLocationId"> /// Required. The ID of the selected location for planning. To list the available /// plannable location ids use [ReachPlanService.ListPlannableLocations][google.ads.googleads.v10.services.ReachPlanService.ListPlannableLocations]. /// </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<ListPlannableProductsResponse> ListPlannableProductsAsync(string plannableLocationId, st::CancellationToken cancellationToken) => ListPlannableProductsAsync(plannableLocationId, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [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 GenerateProductMixIdeasResponse GenerateProductMixIdeas(GenerateProductMixIdeasRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [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<GenerateProductMixIdeasResponse> GenerateProductMixIdeasAsync(GenerateProductMixIdeasRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [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<GenerateProductMixIdeasResponse> GenerateProductMixIdeasAsync(GenerateProductMixIdeasRequest request, st::CancellationToken cancellationToken) => GenerateProductMixIdeasAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="plannableLocationId"> /// Required. The ID of the location, this is one of the ids returned by /// [ReachPlanService.ListPlannableLocations][google.ads.googleads.v10.services.ReachPlanService.ListPlannableLocations]. /// </param> /// <param name="currencyCode"> /// Required. Currency code. /// Three-character ISO 4217 currency code. /// </param> /// <param name="budgetMicros"> /// Required. Total budget. /// Amount in micros. One million is equivalent to one unit. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual GenerateProductMixIdeasResponse GenerateProductMixIdeas(string customerId, string plannableLocationId, string currencyCode, long budgetMicros, gaxgrpc::CallSettings callSettings = null) => GenerateProductMixIdeas(new GenerateProductMixIdeasRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), PlannableLocationId = gax::GaxPreconditions.CheckNotNullOrEmpty(plannableLocationId, nameof(plannableLocationId)), CurrencyCode = gax::GaxPreconditions.CheckNotNullOrEmpty(currencyCode, nameof(currencyCode)), BudgetMicros = budgetMicros, }, callSettings); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="plannableLocationId"> /// Required. The ID of the location, this is one of the ids returned by /// [ReachPlanService.ListPlannableLocations][google.ads.googleads.v10.services.ReachPlanService.ListPlannableLocations]. /// </param> /// <param name="currencyCode"> /// Required. Currency code. /// Three-character ISO 4217 currency code. /// </param> /// <param name="budgetMicros"> /// Required. Total budget. /// Amount in micros. One million is equivalent to one unit. /// </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<GenerateProductMixIdeasResponse> GenerateProductMixIdeasAsync(string customerId, string plannableLocationId, string currencyCode, long budgetMicros, gaxgrpc::CallSettings callSettings = null) => GenerateProductMixIdeasAsync(new GenerateProductMixIdeasRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), PlannableLocationId = gax::GaxPreconditions.CheckNotNullOrEmpty(plannableLocationId, nameof(plannableLocationId)), CurrencyCode = gax::GaxPreconditions.CheckNotNullOrEmpty(currencyCode, nameof(currencyCode)), BudgetMicros = budgetMicros, }, callSettings); /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="plannableLocationId"> /// Required. The ID of the location, this is one of the ids returned by /// [ReachPlanService.ListPlannableLocations][google.ads.googleads.v10.services.ReachPlanService.ListPlannableLocations]. /// </param> /// <param name="currencyCode"> /// Required. Currency code. /// Three-character ISO 4217 currency code. /// </param> /// <param name="budgetMicros"> /// Required. Total budget. /// Amount in micros. One million is equivalent to one unit. /// </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<GenerateProductMixIdeasResponse> GenerateProductMixIdeasAsync(string customerId, string plannableLocationId, string currencyCode, long budgetMicros, st::CancellationToken cancellationToken) => GenerateProductMixIdeasAsync(customerId, plannableLocationId, currencyCode, budgetMicros, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [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 GenerateReachForecastResponse GenerateReachForecast(GenerateReachForecastRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [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<GenerateReachForecastResponse> GenerateReachForecastAsync(GenerateReachForecastRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [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<GenerateReachForecastResponse> GenerateReachForecastAsync(GenerateReachForecastRequest request, st::CancellationToken cancellationToken) => GenerateReachForecastAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="campaignDuration"> /// Required. Campaign duration. /// </param> /// <param name="plannedProducts"> /// Required. The products to be forecast. /// The max number of allowed planned products is 15. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual GenerateReachForecastResponse GenerateReachForecast(string customerId, CampaignDuration campaignDuration, scg::IEnumerable<PlannedProduct> plannedProducts, gaxgrpc::CallSettings callSettings = null) => GenerateReachForecast(new GenerateReachForecastRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), CampaignDuration = gax::GaxPreconditions.CheckNotNull(campaignDuration, nameof(campaignDuration)), PlannedProducts = { gax::GaxPreconditions.CheckNotNull(plannedProducts, nameof(plannedProducts)), }, }, callSettings); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="campaignDuration"> /// Required. Campaign duration. /// </param> /// <param name="plannedProducts"> /// Required. The products to be forecast. /// The max number of allowed planned products is 15. /// </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<GenerateReachForecastResponse> GenerateReachForecastAsync(string customerId, CampaignDuration campaignDuration, scg::IEnumerable<PlannedProduct> plannedProducts, gaxgrpc::CallSettings callSettings = null) => GenerateReachForecastAsync(new GenerateReachForecastRequest { CustomerId = gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), CampaignDuration = gax::GaxPreconditions.CheckNotNull(campaignDuration, nameof(campaignDuration)), PlannedProducts = { gax::GaxPreconditions.CheckNotNull(plannedProducts, nameof(plannedProducts)), }, }, callSettings); /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [RequestError]() /// </summary> /// <param name="customerId"> /// Required. The ID of the customer. /// </param> /// <param name="campaignDuration"> /// Required. Campaign duration. /// </param> /// <param name="plannedProducts"> /// Required. The products to be forecast. /// The max number of allowed planned products is 15. /// </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<GenerateReachForecastResponse> GenerateReachForecastAsync(string customerId, CampaignDuration campaignDuration, scg::IEnumerable<PlannedProduct> plannedProducts, st::CancellationToken cancellationToken) => GenerateReachForecastAsync(customerId, campaignDuration, plannedProducts, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>ReachPlanService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Reach Plan Service gives users information about audience size that can /// be reached through advertisement on YouTube. In particular, /// GenerateReachForecast provides estimated number of people of specified /// demographics that can be reached by an ad in a given market by a campaign of /// certain duration with a defined budget. /// </remarks> public sealed partial class ReachPlanServiceClientImpl : ReachPlanServiceClient { private readonly gaxgrpc::ApiCall<ListPlannableLocationsRequest, ListPlannableLocationsResponse> _callListPlannableLocations; private readonly gaxgrpc::ApiCall<ListPlannableProductsRequest, ListPlannableProductsResponse> _callListPlannableProducts; private readonly gaxgrpc::ApiCall<GenerateProductMixIdeasRequest, GenerateProductMixIdeasResponse> _callGenerateProductMixIdeas; private readonly gaxgrpc::ApiCall<GenerateReachForecastRequest, GenerateReachForecastResponse> _callGenerateReachForecast; /// <summary> /// Constructs a client wrapper for the ReachPlanService service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="ReachPlanServiceSettings"/> used within this client.</param> public ReachPlanServiceClientImpl(ReachPlanService.ReachPlanServiceClient grpcClient, ReachPlanServiceSettings settings) { GrpcClient = grpcClient; ReachPlanServiceSettings effectiveSettings = settings ?? ReachPlanServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callListPlannableLocations = clientHelper.BuildApiCall<ListPlannableLocationsRequest, ListPlannableLocationsResponse>(grpcClient.ListPlannableLocationsAsync, grpcClient.ListPlannableLocations, effectiveSettings.ListPlannableLocationsSettings); Modify_ApiCall(ref _callListPlannableLocations); Modify_ListPlannableLocationsApiCall(ref _callListPlannableLocations); _callListPlannableProducts = clientHelper.BuildApiCall<ListPlannableProductsRequest, ListPlannableProductsResponse>(grpcClient.ListPlannableProductsAsync, grpcClient.ListPlannableProducts, effectiveSettings.ListPlannableProductsSettings); Modify_ApiCall(ref _callListPlannableProducts); Modify_ListPlannableProductsApiCall(ref _callListPlannableProducts); _callGenerateProductMixIdeas = clientHelper.BuildApiCall<GenerateProductMixIdeasRequest, GenerateProductMixIdeasResponse>(grpcClient.GenerateProductMixIdeasAsync, grpcClient.GenerateProductMixIdeas, effectiveSettings.GenerateProductMixIdeasSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callGenerateProductMixIdeas); Modify_GenerateProductMixIdeasApiCall(ref _callGenerateProductMixIdeas); _callGenerateReachForecast = clientHelper.BuildApiCall<GenerateReachForecastRequest, GenerateReachForecastResponse>(grpcClient.GenerateReachForecastAsync, grpcClient.GenerateReachForecast, effectiveSettings.GenerateReachForecastSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId); Modify_ApiCall(ref _callGenerateReachForecast); Modify_GenerateReachForecastApiCall(ref _callGenerateReachForecast); 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_ListPlannableLocationsApiCall(ref gaxgrpc::ApiCall<ListPlannableLocationsRequest, ListPlannableLocationsResponse> call); partial void Modify_ListPlannableProductsApiCall(ref gaxgrpc::ApiCall<ListPlannableProductsRequest, ListPlannableProductsResponse> call); partial void Modify_GenerateProductMixIdeasApiCall(ref gaxgrpc::ApiCall<GenerateProductMixIdeasRequest, GenerateProductMixIdeasResponse> call); partial void Modify_GenerateReachForecastApiCall(ref gaxgrpc::ApiCall<GenerateReachForecastRequest, GenerateReachForecastResponse> call); partial void OnConstruction(ReachPlanService.ReachPlanServiceClient grpcClient, ReachPlanServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC ReachPlanService client</summary> public override ReachPlanService.ReachPlanServiceClient GrpcClient { get; } partial void Modify_ListPlannableLocationsRequest(ref ListPlannableLocationsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListPlannableProductsRequest(ref ListPlannableProductsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GenerateProductMixIdeasRequest(ref GenerateProductMixIdeasRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GenerateReachForecastRequest(ref GenerateReachForecastRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the list of plannable locations (for example, countries &amp;amp; DMAs). /// /// 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 ListPlannableLocationsResponse ListPlannableLocations(ListPlannableLocationsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPlannableLocationsRequest(ref request, ref callSettings); return _callListPlannableLocations.Sync(request, callSettings); } /// <summary> /// Returns the list of plannable locations (for example, countries &amp;amp; DMAs). /// /// 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<ListPlannableLocationsResponse> ListPlannableLocationsAsync(ListPlannableLocationsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPlannableLocationsRequest(ref request, ref callSettings); return _callListPlannableLocations.Async(request, callSettings); } /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// 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 ListPlannableProductsResponse ListPlannableProducts(ListPlannableProductsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPlannableProductsRequest(ref request, ref callSettings); return _callListPlannableProducts.Sync(request, callSettings); } /// <summary> /// Returns the list of per-location plannable YouTube ad formats with allowed /// targeting. /// /// 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<ListPlannableProductsResponse> ListPlannableProductsAsync(ListPlannableProductsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListPlannableProductsRequest(ref request, ref callSettings); return _callListPlannableProducts.Async(request, callSettings); } /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [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 GenerateProductMixIdeasResponse GenerateProductMixIdeas(GenerateProductMixIdeasRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GenerateProductMixIdeasRequest(ref request, ref callSettings); return _callGenerateProductMixIdeas.Sync(request, callSettings); } /// <summary> /// Generates a product mix ideas given a set of preferences. This method /// helps the advertiser to obtain a good mix of ad formats and budget /// allocations based on its preferences. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [ReachPlanError]() /// [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<GenerateProductMixIdeasResponse> GenerateProductMixIdeasAsync(GenerateProductMixIdeasRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GenerateProductMixIdeasRequest(ref request, ref callSettings); return _callGenerateProductMixIdeas.Async(request, callSettings); } /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [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 GenerateReachForecastResponse GenerateReachForecast(GenerateReachForecastRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GenerateReachForecastRequest(ref request, ref callSettings); return _callGenerateReachForecast.Sync(request, callSettings); } /// <summary> /// Generates a reach forecast for a given targeting / product mix. /// /// List of thrown errors: /// [AuthenticationError]() /// [AuthorizationError]() /// [FieldError]() /// [HeaderError]() /// [InternalError]() /// [QuotaError]() /// [RangeError]() /// [ReachPlanError]() /// [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<GenerateReachForecastResponse> GenerateReachForecastAsync(GenerateReachForecastRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GenerateReachForecastRequest(ref request, ref callSettings); return _callGenerateReachForecast.Async(request, callSettings); } } }
namespace Nancy.ViewEngines.Spark { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading; using Nancy.Responses.Negotiation; using global::Spark.FileSystem; /// <summary> /// Implementation of the IViewFolder interface to have Spark use views that's been discovered by Nancy's view locator. /// </summary> public class NancyViewFolder : IViewFolder { private readonly ViewEngineStartupContext viewEngineStartupContext; private List<ViewLocationResult> currentlyLocatedViews; private ReaderWriterLockSlim padlock = new ReaderWriterLockSlim(); private readonly ConcurrentDictionary<string, IViewFile> cachedFiles = new ConcurrentDictionary<string, IViewFile>(); /// <summary> /// Initializes a new instance of the <see cref="NancyViewFolder"/> class, using the provided /// <see cref="viewEngineStartupContext"/> instance. /// </summary> /// <param name="viewEngineStartupContext"></param> public NancyViewFolder(ViewEngineStartupContext viewEngineStartupContext) { this.viewEngineStartupContext = viewEngineStartupContext; // No need to lock here this.currentlyLocatedViews = new List<ViewLocationResult>(viewEngineStartupContext.ViewLocator.GetAllCurrentlyDiscoveredViews()); } /// <summary> /// Gets the source of the requested view. /// </summary> /// <param name="path">The view to get the source for</param> /// <returns>A <see cref="IViewFile"/> instance.</returns> public IViewFile GetViewSource(string path) { var searchPath = ConvertPath(path); IViewFile fileResult; if (this.cachedFiles.TryGetValue(searchPath, out fileResult)) { return fileResult; } ViewLocationResult result = null; this.padlock.EnterUpgradeableReadLock(); try { result = this.currentlyLocatedViews .FirstOrDefault(v => CompareViewPaths(GetSafeViewPath(v), searchPath)); if (result == null && StaticConfiguration.Caching.EnableRuntimeViewDiscovery) { result = this.viewEngineStartupContext.ViewLocator.LocateView(searchPath, GetFakeContext()); this.padlock.EnterWriteLock(); try { this.currentlyLocatedViews.Add(result); } finally { this.padlock.ExitWriteLock(); } } } finally { this.padlock.ExitUpgradeableReadLock(); } if (result == null) { throw new FileNotFoundException(string.Format("Template {0} not found", path), path); } fileResult = new NancyViewFile(result); this.cachedFiles.AddOrUpdate(searchPath, s => fileResult, (s, o) => fileResult); return fileResult; } /// <summary> /// Lists all view for the specified <paramref name="path"/>. /// </summary> /// <param name="path">The path to return views for.</param> /// <returns>An <see cref="IEnumerable{T}"/> that contains the matched views.</returns> public IList<string> ListViews(string path) { this.padlock.EnterReadLock(); try { return currentlyLocatedViews. Where(v => v.Location.StartsWith(path, StringComparison.OrdinalIgnoreCase)). Select(v => v.Location.Length == path.Length ? v.Name + "." + v.Extension : v.Location.Substring(path.Length) + "/" + v.Name + "." + v.Extension). ToList(); } finally { this.padlock.ExitReadLock(); } } /// <summary> /// Gets a value that indicates whether or not the view folder contains a specific view. /// </summary> /// <param name="path">The view to check for.</param> /// <returns><see langword="true"/> if the view exists in the view folder; otherwise <see langword="false"/>.</returns> public bool HasView(string path) { var searchPath = ConvertPath(path); this.padlock.EnterUpgradeableReadLock(); try { var hasCached = this.currentlyLocatedViews.Any(v => CompareViewPaths(GetSafeViewPath(v), searchPath)); if (hasCached || !StaticConfiguration.Caching.EnableRuntimeViewDiscovery) { return hasCached; } var newView = this.viewEngineStartupContext.ViewLocator.LocateView(searchPath, GetFakeContext()); if (newView == null) { return false; } this.padlock.EnterWriteLock(); try { this.currentlyLocatedViews.Add(newView); return true; } finally { this.padlock.ExitWriteLock(); } } finally { this.padlock.ExitUpgradeableReadLock(); } } private static bool CompareViewPaths(string storedViewPath, string requestedViewPath) { return String.Equals(storedViewPath, requestedViewPath, StringComparison.OrdinalIgnoreCase); } private static string ConvertPath(string path) { return path.Replace(@"\", "/"); } private static string GetSafeViewPath(ViewLocationResult result) { return string.IsNullOrEmpty(result.Location) ? string.Concat(result.Name, ".", result.Extension) : string.Concat(result.Location, "/", result.Name, ".", result.Extension); } // Horrible hack, but we have no way to get a context private static NancyContext GetFakeContext() { return new NancyContext { Request = new Request("GET", "/", "http") }; } public class NancyViewFile : IViewFile { private readonly object updateLock = new object(); private readonly ViewLocationResult viewLocationResult; private string contents; private long lastUpdated; public NancyViewFile(ViewLocationResult viewLocationResult) { this.viewLocationResult = viewLocationResult; this.UpdateContents(); } public long LastModified { get { if (StaticConfiguration.Caching.EnableRuntimeViewUpdates && this.viewLocationResult.IsStale()) { this.UpdateContents(); } return this.lastUpdated; } } public Stream OpenViewStream() { if (StaticConfiguration.Caching.EnableRuntimeViewUpdates && this.viewLocationResult.IsStale()) { this.UpdateContents(); } return new MemoryStream(Encoding.UTF8.GetBytes(this.contents)); } private void UpdateContents() { lock (this.updateLock) { using (var reader = this.viewLocationResult.Contents.Invoke()) { this.contents = reader.ReadToEnd(); } this.lastUpdated = DateTime.Now.Ticks; } } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace NetGore.Collections { /// <summary> /// Provides an interface for a class like <see cref="System.Collections.Generic.List{T}"/>, /// but allows you to override the key methods. /// </summary> /// <typeparam name="T">The type of element.</typeparam> public class VirtualList<T> : IList<T>, IList { readonly List<T> _list = new List<T>(); /// <summary> /// Gets the underlying List. /// </summary> [SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists")] protected List<T> GetUnderlyingList { get { return _list; } } /// <summary> /// Adds multiple items to the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="items">The objects to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public virtual void AddRange(IEnumerable<T> items) { foreach (var item in items) { Add(item); } } #region IList Members /// <summary> /// Gets or sets the element at the specified index. /// </summary> /// <param name="index">The zero-based index of the element to get or set.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index /// in the <see cref="T:System.Collections.IList"/>.</exception> /// <exception cref="T:System.NotSupportedException">The property is set and the /// <see cref="T:System.Collections.IList"/> is read-only.</exception> /// <returns> /// The element at the specified index. /// </returns> object IList.this[int index] { get { return this[index]; } set { this[index] = (T)value; } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.IList"/> has a fixed size. /// </summary> /// <returns> /// true if the <see cref="T:System.Collections.IList"/> has a fixed size; otherwise, false. /// </returns> bool IList.IsFixedSize { get { return ((IList)_list).IsFixedSize; } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </summary> /// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false. /// </returns> bool IList.IsReadOnly { get { return false; } } /// <summary> /// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> /// is synchronized (thread safe). /// </summary> /// <returns> /// true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe); /// otherwise, false. /// </returns> bool ICollection.IsSynchronized { get { return ((ICollection)_list).IsSynchronized; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>. /// </summary> /// <returns> /// An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>. /// </returns> object ICollection.SyncRoot { get { return ((ICollection)_list).SyncRoot; } } /// <summary> /// Adds an item to the <see cref="T:System.Collections.IList"/>. /// </summary> /// <param name="value">The <see cref="T:System.Object"/> to add to the /// <see cref="T:System.Collections.IList"/>.</param> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.IList"/> is read-only. /// -or- /// The <see cref="T:System.Collections.IList"/> has a fixed size. /// </exception> /// <returns> /// The position into which the new element was inserted. /// </returns> int IList.Add(object value) { var casted = (T)value; _list.Add(casted); if (Equals(_list[_list.Count - 1], casted)) return _list.Count; // Most likely it was added at the end else return _list.IndexOf(casted); } /// <summary> /// Determines whether the <see cref="T:System.Collections.IList"/> contains a specific value. /// </summary> /// <param name="value">The <see cref="T:System.Object"/> to locate in the /// <see cref="T:System.Collections.IList"/>.</param> /// <returns> /// true if the <see cref="T:System.Object"/> is found in the <see cref="T:System.Collections.IList"/>; /// otherwise, false. /// </returns> bool IList.Contains(object value) { return Contains((T)value); } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see cref="T:System.Array"/>, /// starting at a particular <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements /// copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have /// zero-based indexing.</param><param name="index">The zero-based index in <paramref name="array"/> at which /// copying begins.</param> /// <exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is less than zero.</exception> /// <exception cref="T:System.ArgumentException"><paramref name="array"/> is multidimensional. /// -or- /// <paramref name="index"/> is equal to or greater than the length of <paramref name="array"/>. /// -or- /// The number of elements in the source <see cref="T:System.Collections.ICollection"/> is /// greater than the available space from <paramref name="index"/> to the end of the destination /// <paramref name="array"/>. /// </exception> /// <exception cref="T:System.ArgumentException">The type of the source <see cref="T:System.Collections.ICollection"/> /// cannot be cast automatically to the type of the destination <paramref name="array"/>.</exception> void ICollection.CopyTo(Array array, int index) { ((ICollection)_list).CopyTo(array, index); } /// <summary> /// Determines the index of a specific item in the <see cref="T:System.Collections.IList"/>. /// </summary> /// <param name="value">The <see cref="T:System.Object"/> to locate in the /// <see cref="T:System.Collections.IList"/>.</param> /// <returns> /// The index of <paramref name="value"/> if found in the list; otherwise, -1. /// </returns> int IList.IndexOf(object value) { return IndexOf((T)value); } /// <summary> /// Inserts an item to the <see cref="T:System.Collections.IList"/> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="value"/> should be inserted.</param> /// <param name="value">The <see cref="T:System.Object"/> to insert into the /// <see cref="T:System.Collections.IList"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the /// <see cref="T:System.Collections.IList"/>.</exception> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.IList"/> is read-only. /// -or- /// The <see cref="T:System.Collections.IList"/> has a fixed size. /// </exception> /// <exception cref="T:System.NullReferenceException"><paramref name="value"/> is null reference in the /// <see cref="T:System.Collections.IList"/>.</exception> void IList.Insert(int index, object value) { Insert(index, (T)value); } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.IList"/>. /// </summary> /// <param name="value">The <see cref="T:System.Object"/> to remove from the /// <see cref="T:System.Collections.IList"/>.</param> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.IList"/> is read-only. /// -or- /// The <see cref="T:System.Collections.IList"/> has a fixed size. /// </exception> void IList.Remove(object value) { Remove((T)value); } #endregion #region IList<T> Members /// <summary> /// Gets or sets the element at the specified index. /// </summary> /// <returns> /// The element at the specified index. /// </returns> /// <param name="index">The zero-based index of the element to get or set. /// </param><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid index in the <see cref="T:System.Collections.Generic.IList`1"/>. /// </exception><exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IList`1"/> is read-only. /// </exception> public virtual T this[int index] { get { return _list[index]; } set { _list[index] = value; } } /// <summary> /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <returns> /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> public virtual int Count { get { return _list.Count; } } /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </summary> /// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false. /// </returns> bool ICollection<T>.IsReadOnly { get { return false; } } /// <summary> /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public virtual void Add(T item) { _list.Add(item); } /// <summary> /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public virtual void Clear() { _list.Clear(); } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; /// otherwise, false. /// </returns> public bool Contains(T item) { return _list.Contains(item); } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, /// starting at a particular <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the /// elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. /// The <see cref="T:System.Array"/> must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception> /// <exception cref="T:System.ArgumentException"><paramref name="array"/> is multidimensional. /// -or- /// <paramref name="arrayIndex"/> is equal to or greater than the length of <paramref name="array"/>. /// -or- /// The number of elements in the source /// <see cref="T:System.Collections.Generic.ICollection`1"/> /// is greater than the available space from <paramref name="arrayIndex"/> to the /// end of the destination /// <paramref name="array"/>. /// -or- /// Type <typeparamref name="T"/> cannot be cast automatically to the type of the destination /// <paramref name="array"/>. /// </exception> public virtual void CopyTo(T[] array, int arrayIndex) { _list.CopyTo(array, arrayIndex); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> public virtual IEnumerator<T> GetEnumerator() { return _list.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Determines the index of a specific item in the <see cref="T:System.Collections.Generic.IList`1"/>. /// </summary> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.IList`1"/>.</param> /// <returns> /// The index of <paramref name="item"/> if found in the list; otherwise, -1. /// </returns> public virtual int IndexOf(T item) { return _list.IndexOf(item); } /// <summary> /// Inserts an item to the <see cref="T:System.Collections.Generic.IList`1"/> at the specified index. /// </summary> /// <param name="index">The zero-based index at which <paramref name="item"/> should be inserted.</param> /// <param name="item">The object to insert into the <see cref="T:System.Collections.Generic.IList`1"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a valid /// index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception> public virtual void Insert(int index, T item) { _list.Insert(index, item); } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.ICollection`1"/>is read-only.</exception> /// <returns> /// true if <paramref name="item"/> was successfully removed from the /// <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if /// <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> public virtual bool Remove(T item) { return _list.Remove(item); } /// <summary> /// Removes the <see cref="T:System.Collections.Generic.IList`1"/> item at the specified index. /// </summary> /// <param name="index">The zero-based index of the item to remove.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="index"/> is not a /// valid index in the <see cref="T:System.Collections.Generic.IList`1"/>.</exception> /// <exception cref="T:System.NotSupportedException"> /// The <see cref="T:System.Collections.Generic.IList`1"/> is read-only.</exception> public virtual void RemoveAt(int index) { _list.RemoveAt(index); } #endregion /// <summary> /// Performs an explicit conversion from <see cref="VirtualList{T}"/> /// to <see cref="System.Collections.Generic.List{T}"/>. /// </summary> /// <param name="l">The list.</param> /// <returns>The result of the conversion.</returns> [SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists")] public static explicit operator List<T>(VirtualList<T> l) { return l._list; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; using TestLibrary; /// <summary> /// String.Compare Method (String, String) /// The comparison uses the current culture to obtain culture-specific information such as /// casing rules and the alphabetic order of individual characters. /// The comparison is performed using word sort rules. /// </summary> class StringCompare5 { private const int c_MIN_STRING_LEN = 8; private const int c_MAX_STRING_LEN = 256; private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars) private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars) private const int c_MAX_LONG_STR_LEN = 65535; private const string c_POS_TEST_PREFIX = "PosTest"; private const string c_NEG_TEST_PREFIX = "NegTest"; private int totalTestCount; private int posTestCount ; private int negTestCount; private int passedTestCount; private int failedTestCount; private enum TestType { PositiveTest = 1, NegativeTest = 2 }; private enum TestResult {NotRun = 0, PassedTest = 1, FailedTest = 2}; internal struct Parameters { public string strA, strB; public string DataString { get { string str = string.Format("\n\tFirst string: {0}, Second string: {1}", strA, strB); str += string.Format("\n\tFirst string length:{0}, second string length:{1}", strA.Length, strB.Length); return str; } } } //Default constructor to ninitial all kind of test counts public StringCompare5() { totalTestCount = posTestCount = negTestCount = 0; passedTestCount = failedTestCount = 0; } //Update (postive or negative) and total test count at the beginning of test scenario private void UpdateCounts(TestType testType) { if (TestType.PositiveTest == testType) { posTestCount++; totalTestCount++; return; } if (TestType.NegativeTest == testType) { negTestCount++; totalTestCount++; return; } } //Generate standard error number string //i.e "9", "12" is not proper. Instead they should be "009", "012" private string GenerateErrorNum(int errorNum) { string temp = errorNum.ToString(); string errorNumStr = new string('0', 3 - temp.Length) + temp; return errorNumStr; } //Update failed or passed test counts at the end of test scenario private void UpdateCounts(TestResult testResult) { if (TestResult.PassedTest == testResult) { passedTestCount++; return; } if (TestResult.FailedTest == testResult) { failedTestCount++; return; } } public static int Main() { StringCompare5 sc = new StringCompare5(); TestLibrary.TestFramework.BeginTestCase("for method: String.Compare Method (String, String)"); if (sc.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; //Postive test scenarios TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; //Negative test scenarios TestLibrary.TestFramework.LogInformation("[Negative]"); //retVal = NegTest1() && retVal; return retVal; } #region Positive test scenarioes public bool PosTest1() { Parameters paras; const string c_testDesc = "Two null comparison."; const int c_expectedValue = 0; paras.strA = null; paras.strB = null; return ExecutePosTestZero(paras, c_expectedValue, c_testDesc); } public bool PosTest2() { Parameters paras; const string c_testDesc = "Null vs String.Empty"; const bool c_expectedValue = true; paras.strA = null; paras.strB = string.Empty; return ExecutePosTestLesser(paras, c_expectedValue, c_testDesc); } public bool PosTest3() { Parameters paras; const string c_testDesc = "Long string(>256 chars) vs long string (>256 chars)"; const bool c_expectedValue = true; string strBasic1 = TestLibrary.Generator.GetString(-55, false, c_MIN_LONG_STR_LEN, c_MAX_LONG_STR_LEN - 16); string strBasic2 = TestLibrary.Generator.GetString(-55, false, 8, 8); char ch = TestLibrary.Generator.GetChar(-55); paras.strA = strBasic1 + strBasic2; paras.strB = strBasic1 + strBasic2 + strBasic2; return ExecutePosTestLesser(paras, c_expectedValue, c_testDesc); } public bool PosTest4() { Parameters paras; const string c_testDesc = "Short string (<32 chars) vs long string(>256 chars)"; const bool c_expectedValue = true; string strBasic = TestLibrary.Generator.GetString(-55, false, 20920, 20920); paras.strA = strBasic.Substring(0,this.GetInt32(1,c_MAX_SHORT_STR_LEN)); paras.strB = strBasic; return ExecutePosTestLesser(paras, c_expectedValue, c_testDesc); } #endregion #region Helper methods for positive test scenarioes //Zero value returned from test method means that two substrings equal private bool ExecutePosTestZero(Parameters paras, int expectedValue, string testDesc) { bool retVal = true; UpdateCounts(TestType.PositiveTest); string testInfo = c_POS_TEST_PREFIX + this.posTestCount.ToString() +": " + testDesc; int actualValue; TestResult testResult = TestResult.NotRun; TestLibrary.TestFramework.BeginScenario(testInfo); try { actualValue = this.CallTestMethod(paras); if (paras.strA != null && paras.strB != null) expectedValue = GlobLocHelper.OSCompare(paras.strA, paras.strB); if (expectedValue != actualValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError(GenerateErrorNum(this.totalTestCount), errorDesc); testResult = TestResult.FailedTest; retVal = false; } testResult = TestResult.PassedTest; } catch (Exception e) { TestLibrary.TestFramework.LogError(GenerateErrorNum(this.totalTestCount + 1), "Unexpected exception: " + e); testResult = TestResult.FailedTest; retVal = false; } UpdateCounts(testResult); return retVal; } // True value returned from test method means that two substrings do not equal private bool ExecutePosTestNonzero(Parameters paras, bool expectedValue, string testDesc) { bool retVal = true; UpdateCounts(TestType.PositiveTest); string testInfo = c_POS_TEST_PREFIX + this.posTestCount.ToString() + ": " + testDesc; bool actualValue; TestResult testResult = TestResult.NotRun; TestLibrary.TestFramework.BeginScenario(testInfo); try { actualValue = (0 != this.CallTestMethod(paras)); if (paras.strA != null && paras.strB != null) expectedValue = (0 != GlobLocHelper.OSCompare(paras.strA, paras.strB)); if (expectedValue != actualValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError(GenerateErrorNum(this.totalTestCount), errorDesc); testResult = TestResult.FailedTest; retVal = false; } testResult = TestResult.PassedTest; } catch (Exception e) { TestLibrary.TestFramework.LogError(GenerateErrorNum(this.totalTestCount + 1), "Unexpected exception: " + e); testResult = TestResult.FailedTest; retVal = false; } UpdateCounts(testResult); return retVal; } // True value returned from test method means that the first substring lesser than the second private bool ExecutePosTestLesser(Parameters paras, bool expectedValue, string testDesc) { bool retVal = true; UpdateCounts(TestType.PositiveTest); string testInfo = c_POS_TEST_PREFIX + this.posTestCount.ToString() + ": " + testDesc; bool actualValue; TestResult testResult = TestResult.NotRun; TestLibrary.TestFramework.BeginScenario(testInfo); try { actualValue = (0 > this.CallTestMethod(paras)); if (paras.strA != null && paras.strB != null) expectedValue = (0 > GlobLocHelper.OSCompare(paras.strA, paras.strB)); if (expectedValue != actualValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += paras.DataString; TestLibrary.TestFramework.LogError(GenerateErrorNum(this.totalTestCount), errorDesc); testResult = TestResult.FailedTest; retVal = false; } testResult = TestResult.PassedTest; } catch (Exception e) { TestLibrary.TestFramework.LogError(GenerateErrorNum(this.totalTestCount + 1), "Unexpected exception: " + e); testResult = TestResult.FailedTest; retVal = false; } UpdateCounts(testResult); return retVal; } #endregion #region Helper methods for negative test scenarioes //Test ArgumentOutOfRangeException private bool ExeNegTest_AOORE(Parameters paras, string testDesc, string errorDesc) { bool retVal = true; UpdateCounts(TestType.NegativeTest); string testInfo = c_NEG_TEST_PREFIX + this.negTestCount.ToString() + ": " + testDesc; TestResult testResult = TestResult.NotRun; TestLibrary.TestFramework.BeginScenario(testInfo); try { this.CallTestMethod(paras); TestLibrary.TestFramework.LogError(GenerateErrorNum((this.totalTestCount << 1) - 1), errorDesc); testResult = TestResult.FailedTest; retVal = false; } catch (ArgumentOutOfRangeException) { testResult = TestResult.PassedTest; } catch (Exception e) { TestLibrary.TestFramework.LogError(GenerateErrorNum(this.totalTestCount << 1), "Unexpected exception: " + e); testResult = TestResult.FailedTest; retVal = false; } UpdateCounts(testResult); return retVal; } //Test ArgumentNullException private bool ExeNegTest_ANE(Parameters paras, string testDesc, string errorDesc) { bool retVal = true; UpdateCounts(TestType.NegativeTest); string testInfo = c_NEG_TEST_PREFIX + this.negTestCount.ToString() + ": " + testDesc; TestResult testResult = TestResult.NotRun; TestLibrary.TestFramework.BeginScenario(testInfo); try { this.CallTestMethod(paras); TestLibrary.TestFramework.LogError(GenerateErrorNum((this.totalTestCount << 1) - 1), errorDesc); testResult = TestResult.FailedTest; retVal = false; } catch (ArgumentNullException) { testResult = TestResult.PassedTest; } catch (Exception e) { TestLibrary.TestFramework.LogError(GenerateErrorNum(this.totalTestCount <<1), "Unexpected exception: " + e); testResult = TestResult.FailedTest; retVal = false; } UpdateCounts(testResult); return retVal; } #endregion //Involke the test method //In this test case this method is System.String.Compare() with 7 parameters private int CallTestMethod(Parameters paras) { return string.Compare(paras.strA, paras.strB); } #region helper methods for generating test data private bool GetBoolean() { Int32 i = this.GetInt32(1,2); return (i == 1) ? true : false; } //Get a non-negative integer between minValue and maxValue private Int32 GetInt32(Int32 minValue, Int32 maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } private Int32 Min(Int32 i1, Int32 i2) { return (i1 <= i2) ? i1 : i2; } private Int32 Max(Int32 i1, Int32 i2) { return (i1 >= i2) ? i1 : i2; } #endregion }
// 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.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SymbolId { public partial class SymbolKeyTest : SymbolKeyTestBase { #region "No change to symbol" [Fact] public void C2CTypeSymbolUnchanged01() { var src1 = @"using System; public delegate void DFoo(int p1, string p2); namespace N1.N2 { public interface IFoo { } namespace N3 { public class CFoo { public struct SFoo { public enum EFoo { Zero, One } } } } } "; var src2 = @"using System; public delegate void DFoo(int p1, string p2); namespace N1.N2 { public interface IFoo { // Add member N3.CFoo GetClass(); } namespace N3 { public class CFoo { public struct SFoo { // Update member public enum EFoo { Zero, One, Two } } // Add member public void M(int n) { Console.WriteLine(n); } } } } "; var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test"); var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [Fact, WorkItem(530171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530171")] public void C2CErrorSymbolUnchanged01() { var src1 = @"public void Method() { }"; var src2 = @" public void Method() { System.Console.WriteLine(12345); } "; var comp1 = CreateCompilationWithMscorlib(src1); var comp2 = CreateCompilationWithMscorlib(src2); var symbol01 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol; var symbol02 = comp1.SourceModule.GlobalNamespace.GetMembers().FirstOrDefault() as NamedTypeSymbol; Assert.NotNull(symbol01); Assert.NotNull(symbol02); Assert.NotEqual(symbol01.Kind, SymbolKind.ErrorType); Assert.NotEqual(symbol02.Kind, SymbolKind.ErrorType); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType | SymbolCategory.DeclaredNamespace).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [Fact] [WorkItem(820263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/820263")] public void PartialDefinitionAndImplementationResolveCorrectly() { var src = @"using System; namespace NS { public partial class C1 { partial void M() { } partial void M(); } } "; var comp = CreateCompilationWithMscorlib(src, assemblyName: "Test"); var ns = comp.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var type = ns.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol; var definition = type.GetMembers("M").First() as IMethodSymbol; var implementation = definition.PartialImplementationPart; // Assert that both the definition and implementation resolve back to themselves Assert.Equal(definition, ResolveSymbol(definition, comp, SymbolKeyComparison.None)); Assert.Equal(implementation, ResolveSymbol(implementation, comp, SymbolKeyComparison.None)); } [Fact] [WorkItem(916341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916341")] public void ExplicitIndexerImplementationResolvesCorrectly() { var src = @" interface I { object this[int index] { get; } } interface I<T> { T this[int index] { get; } } class C<T> : I<T>, I { object I.this[int index] { get { throw new System.NotImplementedException(); } } T I<T>.this[int index] { get { throw new System.NotImplementedException(); } } } "; var compilation = CreateCompilationWithMscorlib(src, assemblyName: "Test"); var type = compilation.SourceModule.GlobalNamespace.GetTypeMembers("C").Single() as NamedTypeSymbol; var indexer1 = type.GetMembers().Where(m => m.MetadataName == "I.Item").Single() as IPropertySymbol; var indexer2 = type.GetMembers().Where(m => m.MetadataName == "I<T>.Item").Single() as IPropertySymbol; AssertSymbolKeysEqual(indexer1, indexer2, SymbolKeyComparison.None, expectEqual: false); Assert.Equal(indexer1, ResolveSymbol(indexer1, compilation, SymbolKeyComparison.None)); Assert.Equal(indexer2, ResolveSymbol(indexer2, compilation, SymbolKeyComparison.None)); } #endregion #region "Change to symbol" [Fact] public void C2CTypeSymbolChanged01() { var src1 = @"using System; public delegate void DFoo(int p1); namespace N1.N2 { public interface IBase { } public interface IFoo { } namespace N3 { public class CFoo { public struct SFoo { public enum EFoo { Zero, One } } } } } "; var src2 = @"using System; public delegate void DFoo(int p1, string p2); // add 1 more parameter namespace N1.N2 { public interface IBase { } public interface IFoo : IBase // add base interface { } namespace N3 { public class CFoo : IFoo // impl interface { private struct SFoo // change modifier { internal enum EFoo : long { Zero, One } // change base class, and modifier } } } } "; var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test"); var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.DeclaredType); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.DeclaredType); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [Fact] public void C2CTypeSymbolChanged02() { var src1 = @"using System; namespace NS { public class C1 { public void M() {} } } "; var src2 = @" namespace NS { internal class C1 // add new C1 { public string P { get; set; } } public class C2 // rename C1 to C2 { public void M() {} } } "; var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test"); var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test"); var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var typeSym00 = namespace1.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol; var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var typeSym01 = namespace2.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol; var typeSym02 = namespace2.GetTypeMembers("C2").Single() as NamedTypeSymbol; // new C1 resolve to old C1 ResolveAndVerifySymbol(typeSym01, typeSym00, comp1); // old C1 (new C2) NOT resolve to old C1 var symkey = SymbolKey.Create(typeSym02, CancellationToken.None); var syminfo = symkey.Resolve(comp1); Assert.Null(syminfo.Symbol); } [Fact] public void C2CMemberSymbolChanged01() { var src1 = @"using System; using System.Collections.Generic; public class Test { private byte field = 123; internal string P { get; set; } public void M(ref int n) { } event Action<string> myEvent; } "; var src2 = @"using System; public class Test { internal protected byte field = 255; // change modifier and init-value internal string P { get { return null; } } // remove 'set' public int M(ref int n) { return 0; } // change ret type event Action<string> myEvent // add add/remove { add { } remove { } } } "; var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test"); var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test"); var originalSymbols = GetSourceSymbols(comp1, SymbolCategory.NonTypeMember | SymbolCategory.Parameter) .Where(s => !s.IsAccessor()).OrderBy(s => s.Name); var newSymbols = GetSourceSymbols(comp2, SymbolCategory.NonTypeMember | SymbolCategory.Parameter) .Where(s => !s.IsAccessor()).OrderBy(s => s.Name); ResolveAndVerifySymbolList(newSymbols, originalSymbols, comp1); } [WorkItem(542700, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542700")] [Fact] public void C2CIndexerSymbolChanged01() { var src1 = @"using System; using System.Collections.Generic; public class Test { public string this[string p1] { set { } } protected long this[long p1] { set { } } } "; var src2 = @"using System; public class Test { internal string this[string p1] { set { } } // change modifier protected long this[long p1] { get { return 0; } set { } } // add 'get' } "; var comp1 = CreateCompilationWithMscorlib(src1, assemblyName: "Test"); var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Test"); var typeSym1 = comp1.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as NamedTypeSymbol; var originalSymbols = typeSym1.GetMembers(WellKnownMemberNames.Indexer); var typeSym2 = comp2.SourceModule.GlobalNamespace.GetTypeMembers("Test").Single() as NamedTypeSymbol; var newSymbols = typeSym2.GetMembers(WellKnownMemberNames.Indexer); ResolveAndVerifySymbol(newSymbols.First(), originalSymbols.First(), comp1, SymbolKeyComparison.CaseSensitive); ResolveAndVerifySymbol(newSymbols.Last(), originalSymbols.Last(), comp1, SymbolKeyComparison.CaseSensitive); } [Fact] public void C2CAssemblyChanged01() { var src = @" namespace NS { public class C1 { public void M() {} } } "; var comp1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly1"); var comp2 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly2"); var namespace1 = comp1.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var typeSym01 = namespace1.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol; var namespace2 = comp2.SourceModule.GlobalNamespace.GetMembers("NS").Single() as NamespaceSymbol; var typeSym02 = namespace2.GetTypeMembers("C1").FirstOrDefault() as NamedTypeSymbol; // new C1 resolves to old C1 if we ignore assembly and module ids ResolveAndVerifySymbol(typeSym02, typeSym01, comp1, SymbolKeyComparison.CaseSensitive | SymbolKeyComparison.IgnoreAssemblyIds); // new C1 DOES NOT resolve to old C1 if we don't ignore assembly and module ids Assert.Null(ResolveSymbol(typeSym02, comp1, SymbolKeyComparison.CaseSensitive)); } [WpfFact(Skip = "530169"), WorkItem(530169, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530169")] public void C2CAssemblyChanged02() { var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}"; // same identity var comp1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly"); var comp2 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly"); Symbol sym1 = comp1.Assembly; Symbol sym2 = comp2.Assembly; // Not ignoreAssemblyAndModules ResolveAndVerifySymbol(sym1, sym2, comp2); AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds, true); Assert.NotNull(ResolveSymbol(sym1, comp2, SymbolKeyComparison.IgnoreAssemblyIds)); // Module sym1 = comp1.Assembly.Modules[0]; sym2 = comp2.Assembly.Modules[0]; ResolveAndVerifySymbol(sym1, sym2, comp2); AssertSymbolKeysEqual(sym2, sym1, SymbolKeyComparison.IgnoreAssemblyIds, true); Assert.NotNull(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds)); } [Fact, WorkItem(530170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530170")] public void C2CAssemblyChanged03() { var src = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}"; // ------------------------------------------------------- // different name var compilation1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly1"); var compilation2 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly2"); ISymbol assembly1 = compilation1.Assembly; ISymbol assembly2 = compilation2.Assembly; // different AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.CaseSensitive, expectEqual: false); Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.CaseSensitive)); // ignore means ALL assembly/module symbols have same ID AssertSymbolKeysEqual(assembly2, assembly1, SymbolKeyComparison.IgnoreAssemblyIds, expectEqual: true); // But can NOT be resolved Assert.Null(ResolveSymbol(assembly2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds)); // Module var module1 = compilation1.Assembly.Modules[0]; var module2 = compilation2.Assembly.Modules[0]; // different AssertSymbolKeysEqual(module1, module2, SymbolKeyComparison.CaseSensitive, expectEqual: false); Assert.Null(ResolveSymbol(module1, compilation2, SymbolKeyComparison.CaseSensitive)); AssertSymbolKeysEqual(module2, module1, SymbolKeyComparison.IgnoreAssemblyIds); Assert.Null(ResolveSymbol(module2, compilation1, SymbolKeyComparison.IgnoreAssemblyIds)); } [Fact, WorkItem(546254, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546254")] public void C2CAssemblyChanged04() { var src = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] public class C {} "; var src2 = @" [assembly: System.Reflection.AssemblyVersion(""1.2.3.42"")] [assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] public class C {} "; // different versions var comp1 = CreateCompilationWithMscorlib(src, assemblyName: "Assembly"); var comp2 = CreateCompilationWithMscorlib(src2, assemblyName: "Assembly"); Symbol sym1 = comp1.Assembly; Symbol sym2 = comp2.Assembly; // comment is changed to compare Name ONLY AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.CaseSensitive, expectEqual: true); var resolved = ResolveSymbol(sym2, comp1, SymbolKeyComparison.CaseSensitive); Assert.Equal(sym1, resolved); AssertSymbolKeysEqual(sym1, sym2, SymbolKeyComparison.IgnoreAssemblyIds); Assert.Null(ResolveSymbol(sym2, comp1, SymbolKeyComparison.IgnoreAssemblyIds)); } #endregion } }
using System.Collections.ObjectModel; using System.Linq; using Tortuga.Anchor.Collections; using Tortuga.Anchor.Modeling; using Tortuga.Chain.Metadata; namespace Tortuga.Drydock.Models { public class ColumnModel<TDbType> : ModelBase where TDbType : struct { public ColumnModel(ColumnMetadata<TDbType> column) { Column = column; NormalizedTypeName = column.TypeName.ToLowerInvariant(); Constraints.CollectionChanged += (s, e) => { OnPropertyChanged(nameof(HasCheckConstraint)); OnPropertyChanged(nameof(HasDefaultConstraint)); OnPropertyChanged(nameof(HasForiegnKeyConstraint)); }; } public int? ActualMaxLength { get => Get<int?>(); set => Set(value); } public decimal? AverageLength { get { return Get<decimal?>(); } set { Set(value); } } public ConstraintCollection Constraints { get => GetNew<ConstraintCollection>(); } public ColumnMetadata<TDbType> Column { get; } /// <summary> /// Indicates that this is a text column. /// </summary> /// <value><c>true</c> if contains text; otherwise, <c>false</c>.</value> /// <remarks>This version uses ANSI SQL types.</remarks> public virtual bool ContainsText { get { switch (NormalizedTypeName) { case "character": case "char": case "character varying": case "char varying": case "varchar": case "character large object": case "char large object": case "clob": case "national character": case "national char": case "nchar": case "national character varying": case "national char varying": case "nchar varying": case "national character large object": case "nchar large object": case "nclob": return true; } return false; } } public int? DistinctCount { get => Get<int?>(); set => Set(value); } [CalculatedField("DistinctCount,SampleSize")] public double? DistinctRate { get { return SampleSize > 0 && DistinctCount.HasValue ? (double?)DistinctCount / (double)SampleSize.Value : null; } } public int? EmptyCount { get => Get<int?>(); set => Set(value); } [CalculatedField("EmptyCount,SampleSize")] public double? EmptyRate { get { return SampleSize > 0 && EmptyCount.HasValue ? (double?)EmptyCount / (double)SampleSize.Value : null; } } public FixItColumnOperationCollection<TDbType> FixItOperations => GetNew<FixItColumnOperationCollection<TDbType>>(); [CalculatedField("ConstraintsLoaded")] public bool? HasCheckConstraint { get { if (!ConstraintsLoaded) return null; return Constraints.Any(x => x.ConstraintType == ConstraintType.Check); } } [CalculatedField("ConstraintsLoaded")] public bool? HasDefaultConstraint { get { if (!ConstraintsLoaded) return null; return Constraints.Any(x => x.ConstraintType == ConstraintType.Default); } } [CalculatedField("ConstraintsLoaded")] public bool? HasForiegnKeyConstraint { get { if (!ConstraintsLoaded) return null; return Constraints.Any(x => x.ConstraintType == ConstraintType.ForiegnKey); } } public bool IsComputed { get => Column.IsComputed; } public bool IsIdentity { get => Column.IsIdentity; } public bool? IsIndexed { get => Get<bool?>(); set => Set(value); } public bool? IsNullable { get => Column.IsNullable; } [CalculatedField("ObsoleteMessage")] public bool IsObsolete { get => ObsoleteMessage != null; } public bool IsPrimaryKey { get => Column.IsPrimaryKey; } public bool IsPrimaryKeyCandidate { get => Get<bool>(); set => Set(value); } public bool? IsUnique { get => Get<bool?>(); set => Set(value); } public bool? IsUniqueIndex { get => Get<bool?>(); set => Set(value); } public int? MaxLength { get => Column.MaxLength; } public string Name { get => Column.SqlName; } [CalculatedField("DistinctCount,SampleSize")] public bool? NoDistinctValues { get { if (DistinctCount == null || SampleSize == null) return null; if (DistinctCount == 1 && SampleSize > 1) return true; return false; } } public int? NullCount { get => Get<int?>(); set => Set(value); } [CalculatedField("NullCount,SampleSize")] public double? NullRate { get { return SampleSize > 0 && NullCount.HasValue ? (double?)NullCount / (double)SampleSize.Value : null; } } [CalculatedField("NullCount,SampleSize")] public bool? AlwaysNull { get { return SampleSize > 0 && NullCount.HasValue && NullCount == SampleSize; } } public virtual string ObsoleteMessage { get => null; } public virtual string ObsoleteReplaceType { get => null; } public int? Precision { get => Column.Precision; } public int? SampleSize { get => Get<int?>(); set => Set(value); } public int? Scale { get => Column.Scale; } public int SortIndex { get => Get<int>(); set => Set(value); } public bool StatsLoaded { get => Get<bool>(); set => Set(value); } public bool ConstraintsLoaded { get => Get<bool>(); set => Set(value); } /// <summary> /// Gets a value indicating whether this column supports the distinct operator. /// </summary> /// <value><c>true</c> if supports distinct; otherwise, <c>false</c>.</value> /// <remarks>This version uses ANSI SQL types.</remarks> public virtual bool SupportsDistinct { get { switch (NormalizedTypeName) { case "character": case "char": case "character varying": case "char varying": case "varchar": case "national character": case "national char": case "nchar": case "national character varying": case "national char varying": case "nchar varying": case "numeric": case "decimal": case "dec": case "smallint": case "integer": case "int": case "bigint": case "float": case "real": case "double precision": case "boolean": case "date": case "time": case "timestamp": case "date with time zone": case "date without time zone": case "time with time zone": case "time without time zone": case "timestamp with time zone": case "timestamp without time zone": return true; } return false; } } public TextContentFeatures? TextContentFeatures { get => Get<TextContentFeatures?>(); set => Set(value); } public string TypeName { get => Column.TypeName; } public virtual bool UseMaxLength { get => Column.MaxLength.HasValue; } public virtual bool UsePrecision { get => Column.Precision.HasValue; } public virtual bool UseScale { get => Column.Scale.HasValue; } internal TableVM TableVM { get { return Get<TableVM>(); } set { Set(value); } } protected string NormalizedTypeName { get; } public string Description { get => Get<string>(); set => Set(value); } public ObservableCollectionExtended<object> TopNValues { get => GetNew<ObservableCollectionExtended<object>>(); } } }
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // 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 MassTransit.Serialization { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Context; using Events; using Pipeline; using Pipeline.Pipes; using Util; public abstract class BaseConsumeContext : BasePipeContext, ConsumeContext { readonly Lazy<IPublishEndpoint> _publishEndpoint; readonly IPublishEndpointProvider _publishEndpointProvider; readonly ReceiveContext _receiveContext; readonly ISendEndpointProvider _sendEndpointProvider; protected BaseConsumeContext(ReceiveContext receiveContext, ISendEndpointProvider sendEndpointProvider, IPublishEndpointProvider publishEndpointProvider) : base(new PayloadCacheProxy(receiveContext)) { _receiveContext = receiveContext; _sendEndpointProvider = sendEndpointProvider; _publishEndpointProvider = publishEndpointProvider; _publishEndpoint = new Lazy<IPublishEndpoint>(() => _publishEndpointProvider.CreatePublishEndpoint(_receiveContext.InputAddress, CorrelationId, ConversationId)); } public ReceiveContext ReceiveContext => _receiveContext; public Task CompleteTask => _receiveContext.CompleteTask; public abstract Guid? MessageId { get; } public abstract Guid? RequestId { get; } public abstract Guid? CorrelationId { get; } public abstract Guid? ConversationId { get; } public abstract Guid? InitiatorId { get; } public abstract DateTime? ExpirationTime { get; } public abstract Uri SourceAddress { get; } public abstract Uri DestinationAddress { get; } public abstract Uri ResponseAddress { get; } public abstract Uri FaultAddress { get; } public abstract Headers Headers { get; } public abstract HostInfo Host { get; } public abstract IEnumerable<string> SupportedMessageTypes { get; } public abstract bool HasMessageType(Type messageType); public abstract bool TryGetMessage<T>(out ConsumeContext<T> consumeContext) where T : class; public async Task RespondAsync<T>(T message) where T : class { if (message == null) throw new ArgumentNullException(nameof(message)); if (ResponseAddress != null) { ISendEndpoint endpoint = await GetSendEndpoint(ResponseAddress).ConfigureAwait(false); await endpoint.Send(message, new ResponsePipe<T>(this), CancellationToken).ConfigureAwait(false); } else await _publishEndpoint.Value.Publish(message, new ResponsePipe<T>(this), CancellationToken).ConfigureAwait(false); } public async Task RespondAsync<T>(T message, IPipe<SendContext<T>> sendPipe) where T : class { if (message == null) throw new ArgumentNullException(nameof(message)); if (sendPipe == null) throw new ArgumentNullException(nameof(sendPipe)); if (ResponseAddress != null) { ISendEndpoint endpoint = await GetSendEndpoint(ResponseAddress).ConfigureAwait(false); await endpoint.Send(message, new ResponsePipe<T>(this, sendPipe), CancellationToken).ConfigureAwait(false); } else await _publishEndpoint.Value.Publish(message, new ResponsePipe<T>(this, sendPipe), CancellationToken).ConfigureAwait(false); } public async Task RespondAsync<T>(T message, IPipe<SendContext> sendPipe) where T : class { if (message == null) throw new ArgumentNullException(nameof(message)); if (sendPipe == null) throw new ArgumentNullException(nameof(sendPipe)); if (ResponseAddress != null) { ISendEndpoint endpoint = await GetSendEndpoint(ResponseAddress).ConfigureAwait(false); await endpoint.Send(message, new ResponsePipe<T>(this, sendPipe), CancellationToken).ConfigureAwait(false); } else await _publishEndpoint.Value.Publish(message, new ResponsePipe<T>(this, sendPipe), CancellationToken).ConfigureAwait(false); } public Task RespondAsync(object message) { if (message == null) throw new ArgumentNullException(nameof(message)); Type messageType = message.GetType(); return RespondAsync(message, messageType); } public async Task RespondAsync(object message, Type messageType) { if (message == null) throw new ArgumentNullException(nameof(message)); if (messageType == null) throw new ArgumentNullException(nameof(messageType)); if (ResponseAddress != null) { ISendEndpoint endpoint = await GetSendEndpoint(ResponseAddress).ConfigureAwait(false); await SendEndpointConverterCache.Send(endpoint, message, messageType, new ResponsePipe(this), CancellationToken).ConfigureAwait(false); } else await _publishEndpoint.Value.Publish(message, new ResponsePipe(this), CancellationToken).ConfigureAwait(false); } public Task RespondAsync(object message, IPipe<SendContext> sendPipe) { if (message == null) throw new ArgumentNullException(nameof(message)); if (sendPipe == null) throw new ArgumentNullException(nameof(sendPipe)); Type messageType = message.GetType(); return RespondAsync(message, messageType, sendPipe); } public async Task RespondAsync(object message, Type messageType, IPipe<SendContext> sendPipe) { if (message == null) throw new ArgumentNullException(nameof(message)); if (messageType == null) throw new ArgumentNullException(nameof(messageType)); if (sendPipe == null) throw new ArgumentNullException(nameof(sendPipe)); if (ResponseAddress != null) { ISendEndpoint endpoint = await GetSendEndpoint(ResponseAddress).ConfigureAwait(false); await SendEndpointConverterCache.Send(endpoint, message, messageType, new ResponsePipe(this, sendPipe), CancellationToken).ConfigureAwait(false); } else await _publishEndpoint.Value.Publish(message, new ResponsePipe(this, sendPipe), CancellationToken).ConfigureAwait(false); } public Task RespondAsync<T>(object values) where T : class { if (values == null) throw new ArgumentNullException(nameof(values)); T message = TypeMetadataCache<T>.InitializeFromObject(values); return RespondAsync(message); } public Task RespondAsync<T>(object values, IPipe<SendContext<T>> sendPipe) where T : class { if (values == null) throw new ArgumentNullException(nameof(values)); T message = TypeMetadataCache<T>.InitializeFromObject(values); return RespondAsync(message, sendPipe); } public Task RespondAsync<T>(object values, IPipe<SendContext> sendPipe) where T : class { if (values == null) throw new ArgumentNullException(nameof(values)); T message = TypeMetadataCache<T>.InitializeFromObject(values); return RespondAsync(message, sendPipe); } public void Respond<T>(T message) where T : class { Task task = RespondAsync(message); _receiveContext.AddPendingTask(task); } public async Task<ISendEndpoint> GetSendEndpoint(Uri address) { ISendEndpoint sendEndpoint = await _sendEndpointProvider.GetSendEndpoint(address).ConfigureAwait(false); return new ConsumeSendEndpoint(sendEndpoint, this); } public Task NotifyConsumed<T>(ConsumeContext<T> context, TimeSpan duration, string consumerType) where T : class { Task receiveTask = _receiveContext.NotifyConsumed(context, duration, consumerType); _receiveContext.AddPendingTask(receiveTask); return TaskUtil.Completed; } public Task NotifyFaulted<T>(ConsumeContext<T> context, TimeSpan duration, string consumerType, Exception exception) where T : class { Task faultTask = GenerateFault(context, exception); _receiveContext.AddPendingTask(faultTask); Task receiveTask = _receiveContext.NotifyFaulted(context, duration, consumerType, exception); _receiveContext.AddPendingTask(receiveTask); return TaskUtil.Completed; } public Task Publish<T>(T message, CancellationToken cancellationToken) where T : class { Task task = _publishEndpoint.Value.Publish(message, cancellationToken); _receiveContext.AddPendingTask(task); return task; } public Task Publish<T>(T message, IPipe<PublishContext<T>> publishPipe, CancellationToken cancellationToken) where T : class { Task task = _publishEndpoint.Value.Publish(message, publishPipe, cancellationToken); _receiveContext.AddPendingTask(task); return task; } public Task Publish<T>(T message, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken) where T : class { Task task = _publishEndpoint.Value.Publish(message, publishPipe, cancellationToken); _receiveContext.AddPendingTask(task); return task; } public Task Publish(object message, CancellationToken cancellationToken) { Task task = _publishEndpoint.Value.Publish(message, cancellationToken); _receiveContext.AddPendingTask(task); return task; } public Task Publish(object message, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken) { Task task = _publishEndpoint.Value.Publish(message, publishPipe, cancellationToken); _receiveContext.AddPendingTask(task); return task; } public Task Publish(object message, Type messageType, CancellationToken cancellationToken) { Task task = _publishEndpoint.Value.Publish(message, messageType, cancellationToken); _receiveContext.AddPendingTask(task); return task; } public Task Publish(object message, Type messageType, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken) { Task task = _publishEndpoint.Value.Publish(message, messageType, publishPipe, cancellationToken); _receiveContext.AddPendingTask(task); return task; } public Task Publish<T>(object values, CancellationToken cancellationToken) where T : class { Task task = _publishEndpoint.Value.Publish<T>(values, cancellationToken); _receiveContext.AddPendingTask(task); return task; } public Task Publish<T>(object values, IPipe<PublishContext<T>> publishPipe, CancellationToken cancellationToken) where T : class { Task task = _publishEndpoint.Value.Publish(values, publishPipe, cancellationToken); _receiveContext.AddPendingTask(task); return task; } public Task Publish<T>(object values, IPipe<PublishContext> publishPipe, CancellationToken cancellationToken) where T : class { Task task = _publishEndpoint.Value.Publish<T>(values, publishPipe, cancellationToken); _receiveContext.AddPendingTask(task); return task; } public ConnectHandle ConnectPublishObserver(IPublishObserver observer) { return _publishEndpoint.Value.ConnectPublishObserver(observer); } public ConnectHandle ConnectSendObserver(ISendObserver observer) { return _sendEndpointProvider.ConnectSendObserver(observer); } async Task GenerateFault<T>(ConsumeContext<T> context, Exception exception) where T : class { Fault<T> fault = new FaultEvent<T>(context.Message, context.MessageId, HostMetadataCache.Host, exception); IPipe<SendContext<Fault<T>>> faultPipe = Pipe.Execute<SendContext<Fault<T>>>(x => { x.SourceAddress = ReceiveContext.InputAddress; x.CorrelationId = CorrelationId; x.RequestId = RequestId; foreach (var header in Headers.GetAll()) x.Headers.Set(header.Key, header.Value); }); if (FaultAddress != null) { ISendEndpoint endpoint = await GetSendEndpoint(FaultAddress).ConfigureAwait(false); await endpoint.Send(fault, faultPipe, CancellationToken).ConfigureAwait(false); } else if (ResponseAddress != null) { ISendEndpoint endpoint = await GetSendEndpoint(ResponseAddress).ConfigureAwait(false); await endpoint.Send(fault, faultPipe, CancellationToken).ConfigureAwait(false); } else await _publishEndpoint.Value.Publish(fault, faultPipe, CancellationToken).ConfigureAwait(false); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Demeter.FormComponent; using MongoDB.Driver; using Nest; namespace Demeter.FileComponent { public class DemeterFileStore<TFile> : IFormStore<TFile> where TFile : DemeterFile, new() { private readonly IMongoCollection<TFile> _fileCollection; private readonly ElasticClient _elasticClient; private readonly string _baseFolderPath; public DemeterFileStore( IMongoDatabase database, string formsCollection, string folderPath, ElasticClient elasticClient = null) { if (database == null) { throw new ArgumentNullException(nameof(database)); } if (formsCollection == null) { throw new ArgumentNullException(nameof(formsCollection)); } this._fileCollection = database.GetCollection<TFile>(formsCollection); this._baseFolderPath = folderPath; this._elasticClient = elasticClient; } async Task<FormResult> IFormStore<TFile>.CreateAsync(TFile file, CancellationToken cancellationToken) { if (file == null) { throw new ArgumentNullException(nameof(file)); } byte[] tempStore = file.Content; file.Content = null; await Task.WhenAll( DemeterFileUtil.WriteAsync(this._baseFolderPath, file.Id, tempStore), this._fileCollection .InsertOneAsync(file, cancellationToken: cancellationToken), Task.Run(async () => { if (this._elasticClient == null) { return ; } await this._elasticClient.IndexAsync(file, m => m.Id(file.Id)); }) ).ConfigureAwait(false); file.Content = tempStore; return FormResult.Success; } async Task<FormResult> IFormStore<TFile>.DeleteAsync(TFile file, CancellationToken cancellationToken) { if (file == null) { throw new ArgumentNullException(nameof(file)); } file.Delete(); var query = Builders<TFile>.Filter.And( Builders<TFile>.Filter.Eq(f => f.Id, file.Id), Builders<TFile>.Filter.Eq(f => f.DeleteOn, null) ); var update = Builders<TFile>.Update.Set(f => f.DeleteOn, file.DeleteOn); var result = (await Task.WhenAll( this._fileCollection.UpdateOneAsync( query, update, new UpdateOptions { IsUpsert = false }, cancellationToken ), Task.Run(async () => { await DemeterFileUtil.DeleteAsync(this._baseFolderPath, file.Id); return UpdateResult.Unacknowledged.Instance as UpdateResult; }), Task.Run(async () => { if (this._elasticClient == null) { return UpdateResult.Unacknowledged.Instance as UpdateResult; } await this._elasticClient.DeleteAsync<TFile>( DocumentPath<TFile>.Id(file.Id) ); return UpdateResult.Unacknowledged.Instance as UpdateResult; }) ).ConfigureAwait(false))[0]; return result.IsAcknowledged && result.ModifiedCount == 1 ? FormResult.Success : FormResult.Failed(new FormError { Code = "404", Description = "not find file"}); } async Task<TFile> IFormStore<TFile>.FindByIdAsync(string id, CancellationToken cancellationToken) { if (id == null) { throw new ArgumentNullException(nameof(id)); } var query = Builders<TFile>.Filter.And( Builders<TFile>.Filter.Eq(f => f.Id, id), Builders<TFile>.Filter.Eq(f => f.DeleteOn, null) ); var result = await Task.WhenAll( Task.Run(async () => { var formResult = await this._fileCollection.Find(query) .FirstOrDefaultAsync(cancellationToken); return formResult as DemeterFile; }), Task.Run(async () => { return new DemeterFile(id) { Content = await DemeterFileUtil.ReadAsync(this._baseFolderPath, id) }; }) ).ConfigureAwait(false); if (result[0] == null) { return null; } else { result[0].Content = result[1].Content; return result[0] as TFile; } } async Task<TNewFile> IFormStore<TFile>.QueryAsync<TNewFile>( string queryString, int count, Func<IQueryable<TFile>, TNewFile> queryAction, CancellationToken cancellationToken) { if (queryString == null) { throw new ArgumentNullException(nameof(queryString)); } if (this._elasticClient == null) { throw new NullReferenceException(nameof(this._elasticClient)); } var response = await this._elasticClient.SearchAsync<TFile>(s => s .From(0).Size(count).Query(q => q.QueryString(m => m.Query(queryString)) )); return queryAction(response.Hits .Select(hit => DemeterForm.QueryHitTransfer(hit)) .AsQueryable() ); } async Task<FormResult> IFormStore<TFile>.UpdateAsync(TFile file, CancellationToken cancellationToken) { if (file == null) { throw new ArgumentNullException(nameof(file)); } var query = Builders<TFile>.Filter.And( Builders<TFile>.Filter.Eq(f => f.Id, file.Id), Builders<TFile>.Filter.Eq(f => f.DeleteOn, null) ); byte[] tempStore = file.Content; file.Content = null; await Task.WhenAll( DemeterFileUtil.WriteAsync(this._baseFolderPath, file.Id, tempStore), this._fileCollection .ReplaceOneAsync( query, file, new UpdateOptions { IsUpsert = false }, cancellationToken ), Task.Run(async () => { if (this._elasticClient == null) { return (ReplaceOneResult)ReplaceOneResult.Unacknowledged.Instance; } await this._elasticClient.UpdateAsync<TFile>( DocumentPath<TFile>.Id(file.Id), update => update.Doc(file) ); return (ReplaceOneResult)ReplaceOneResult.Unacknowledged.Instance; }) ).ConfigureAwait(false); file.Content = tempStore; return FormResult.Success; } Task<TNewFile> IFormStore<TFile>.QueryAsync<TNewFile>( Func<IQueryable<TFile>, TNewFile> queryAction, CancellationToken cancellationToken) => Task.FromResult( queryAction(this._fileCollection .AsQueryable() .Where(f => f.DeleteOn == null) ) ); #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } } // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources. // ~DemeterFileStore() { // // Do not change this code. Put cleanup code in Dispose(bool disposing) above. // Dispose(false); // } // This code added to correctly implement the disposable pattern. void System.IDisposable.Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); // TODO: uncomment the following line if the finalizer is overridden above. // GC.SuppressFinalize(this); } #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.Globalization; /// <summary> /// String.System.IConvertible.ToUInt16(IFormatProvider provider) /// This method supports the .NET Framework infrastructure and is /// not intended to be used directly from your code. /// Converts the value of the current String object to a 16-bit unsigned integer. /// </summary> class IConvertibleToUInt16 { private const int c_MIN_STRING_LEN = 8; private const int c_MAX_STRING_LEN = 256; public static int Main() { IConvertibleToUInt16 iege = new IConvertibleToUInt16(); TestLibrary.TestFramework.BeginTestCase("for method: String.System.IConvertible.ToUInt16(IFormatProvider)"); if (iege.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive test scenarioes public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Random numeric string"; const string c_TEST_ID = "P001"; string strSrc; IFormatProvider provider; UInt16 i; bool expectedValue = true; bool actualValue = false; i = (UInt16)(TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1)); strSrc = i.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (i == ((IConvertible)strSrc).ToUInt16(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Positive sign"; const string c_TEST_ID = "P002"; string strSrc; IFormatProvider provider; NumberFormatInfo ni = new NumberFormatInfo(); UInt16 i; bool expectedValue = true; bool actualValue = false; i = (UInt16)(TestLibrary.Generator.GetInt32(-55) % (UInt16.MaxValue + 1)); ni.PositiveSign = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); strSrc = ni.PositiveSign + i.ToString(); provider = (IFormatProvider)ni; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (i == ((IConvertible)strSrc).ToUInt16(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: string is Int16.MaxValue"; const string c_TEST_ID = "P003"; string strSrc; IFormatProvider provider; bool expectedValue = true; bool actualValue = false; strSrc = UInt16.MaxValue.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (UInt16.MaxValue == ((IConvertible)strSrc).ToUInt16(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_DESC = "PosTest4: string is Int16.MinValue"; const string c_TEST_ID = "P004"; string strSrc; IFormatProvider provider; bool expectedValue = true; bool actualValue = false; strSrc = UInt16.MinValue.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (UInt16.MinValue == ((IConvertible)strSrc).ToUInt16(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } #endregion // end for positive test scenarioes #region Negative test scenarios public bool NegTest1() { bool retVal = true; const string c_TEST_DESC = "NegTest1: The value of String object cannot be parsed"; const string c_TEST_ID = "N001"; string strSrc; IFormatProvider provider; strSrc = "p" + TestLibrary.Generator.GetString(-55, false, 9, c_MAX_STRING_LEN); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IConvertible)strSrc).ToUInt16(provider); TestLibrary.TestFramework.LogError("009" + "TestId-" + c_TEST_ID, "FormatException is not thrown as expected" + GetDataString(strSrc, provider)); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("010" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; const string c_TEST_DESC = "NegTest2: The value of String object is a number greater than MaxValue"; const string c_TEST_ID = "N002"; string strSrc; IFormatProvider provider; int i; i = TestLibrary.Generator.GetInt16(-55) + UInt16.MaxValue + 1; strSrc = i.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IConvertible)strSrc).ToUInt16(provider); TestLibrary.TestFramework.LogError("011" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider)); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("012" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; const string c_TEST_DESC = "NegTest3: The value of String object is a number less than MinValue"; const string c_TEST_ID = "N003"; string strSrc; IFormatProvider provider; int i; i = -1 * (TestLibrary.Generator.GetInt32(-55) % UInt16.MaxValue) + UInt16.MinValue - 1; strSrc = i.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IConvertible)strSrc).ToUInt16(provider); TestLibrary.TestFramework.LogError("013" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider)); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("014" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } #endregion private string GetDataString(string strSrc, IFormatProvider provider) { string str1, str2, str; int len1; if (null == strSrc) { str1 = "null"; len1 = 0; } else { str1 = strSrc; len1 = strSrc.Length; } str2 = (null == provider) ? "null" : provider.ToString(); str = string.Format("\n[Source string value]\n \"{0}\"", str1); str += string.Format("\n[Length of source string]\n {0}", len1); str += string.Format("\n[Format provider string]\n {0}", str2); return str; } }
// // TreeStore.cs // // Author: // Lluis Sanchez <lluis@xamarin.com> // // Copyright (c) 2011 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Linq; using System.Collections.Generic; using Xwt.Backends; using System.ComponentModel; namespace Xwt { [BackendType (typeof(ITreeStoreBackend))] public class TreeStore: XwtComponent, ITreeDataSource { IDataField[] fields; class TreeStoreBackendHost: BackendHost<TreeStore,ITreeStoreBackend> { protected override IBackend OnCreateBackend () { var b = base.OnCreateBackend (); if (b == null) b = new DefaultTreeStoreBackend (); ((ITreeStoreBackend)b).Initialize (Parent.fields.Select (f => f.FieldType).ToArray ()); return b; } } protected override Xwt.Backends.BackendHost CreateBackendHost () { return new TreeStoreBackendHost (); } public TreeStore (params IDataField[] fields) { for (int n=0; n<fields.Length; n++) { if (fields[n].Index != -1) throw new InvalidOperationException ("DataField object already belongs to another data store"); ((IDataFieldInternal)fields[n]).SetIndex (n); } this.fields = fields; } ITreeStoreBackend Backend { get { return (ITreeStoreBackend)BackendHost.Backend; } } public TreeNavigator GetFirstNode () { var p = Backend.GetChild (null, 0); return new TreeNavigator (Backend, p); } public TreeNavigator GetNavigatorAt (TreePosition pos) { return new TreeNavigator (Backend, pos); } public TreeNavigator AddNode () { var pos = Backend.AddChild (null); return new TreeNavigator (Backend, pos); } public TreeNavigator AddNode (TreePosition position) { var pos = Backend.AddChild (position); return new TreeNavigator (Backend, pos); } public TreeNavigator InsertNodeAfter (TreePosition positon) { var pos = Backend.InsertAfter (positon); return new TreeNavigator (Backend, pos); } public TreeNavigator InsertNodeBefore (TreePosition positon) { var pos = Backend.InsertBefore (positon); return new TreeNavigator (Backend, pos); } public IEnumerable<TreeNavigator> FindNavigators<T> (T fieldValue, IDataField<T> field) { if (fieldValue == null) { return Enumerable.Empty<TreeNavigator> (); } TreeNavigator navigator = GetFirstNode (); if (navigator.CurrentPosition == null) { return Enumerable.Empty<TreeNavigator> (); } return FindNavigators (fieldValue, field, navigator); } static IEnumerable<TreeNavigator> FindNavigators<T> (T fieldValue, IDataField<T> field, TreeNavigator navigator) { do { if (IsNavigator (navigator, fieldValue, field)) { yield return navigator.Clone (); } foreach (TreeNavigator foundChild in FindChildNavigators (navigator, fieldValue, field)) { yield return foundChild.Clone (); } } while (navigator.MoveNext()); } static IEnumerable<TreeNavigator> FindChildNavigators<T> (TreeNavigator navigator, T fieldValue, IDataField<T> field) { if (!navigator.MoveToChild ()) { yield break; } foreach (var treeNavigator in FindNavigators (fieldValue, field, navigator)) { yield return treeNavigator; } navigator.MoveToParent (); } static bool IsNavigator<T> (TreeNavigator navigator, T fieldValue, IDataField<T> field) { T value = navigator.GetValue (field); return fieldValue.Equals (value); } public void Clear () { Backend.Clear (); } event EventHandler<TreeNodeEventArgs> ITreeDataSource.NodeInserted { add { Backend.NodeInserted += value; } remove { Backend.NodeInserted -= value; } } event EventHandler<TreeNodeChildEventArgs> ITreeDataSource.NodeDeleted { add { Backend.NodeDeleted += value; } remove { Backend.NodeDeleted -= value; } } event EventHandler<TreeNodeEventArgs> ITreeDataSource.NodeChanged { add { Backend.NodeChanged += value; } remove { Backend.NodeChanged -= value; } } event EventHandler<TreeNodeOrderEventArgs> ITreeDataSource.NodesReordered { add { Backend.NodesReordered += value; } remove { Backend.NodesReordered -= value; } } TreePosition ITreeDataSource.GetChild (TreePosition pos, int index) { return Backend.GetChild (pos, index); } TreePosition ITreeDataSource.GetParent (TreePosition pos) { return Backend.GetParent (pos); } int ITreeDataSource.GetChildrenCount (TreePosition pos) { return Backend.GetChildrenCount (pos); } object ITreeDataSource.GetValue (TreePosition pos, int column) { return Backend.GetValue (pos, column); } void ITreeDataSource.SetValue (TreePosition pos, int column, object val) { Backend.SetValue (pos, column, val); } Type[] ITreeDataSource.ColumnTypes { get { return fields.Select (f => f.FieldType).ToArray (); } } } class DefaultTreeStoreBackend: ITreeStoreBackend { struct Node { public object[] Data; public NodeList Children; public int NodeId; } class NodePosition: TreePosition { public NodeList ParentList; public int NodeIndex; public int NodeId; public int StoreVersion; public override bool Equals (object obj) { NodePosition other = (NodePosition) obj; if (other == null) return false; return ParentList == other.ParentList && NodeId == other.NodeId; } public override int GetHashCode () { return ParentList.GetHashCode () ^ NodeId; } } class NodeList: List<Node> { public NodePosition Parent; } Type[] columnTypes; NodeList rootNodes = new NodeList (); int version; int nextNodeId; public event EventHandler<TreeNodeEventArgs> NodeInserted; public event EventHandler<TreeNodeChildEventArgs> NodeDeleted; public event EventHandler<TreeNodeEventArgs> NodeChanged; #pragma warning disable CS0067 public event EventHandler<TreeNodeOrderEventArgs> NodesReordered; #pragma warning restore CS0067 public void InitializeBackend (object frontend, ApplicationContext context) { } public void Initialize (Type[] columnTypes) { this.columnTypes = columnTypes; } public void Clear () { rootNodes.Clear (); } NodePosition GetPosition (TreePosition pos) { if (pos == null) return null; NodePosition np = (NodePosition)pos; if (np.StoreVersion != version) { np.NodeIndex = -1; for (int i=0; i<np.ParentList.Count; i++) { if (np.ParentList [i].NodeId == np.NodeId) { np.NodeIndex = i; break; } } if (np.NodeIndex == -1) throw new InvalidOperationException ("Invalid node position"); np.StoreVersion = version; } return np; } public void SetValue (TreePosition pos, int column, object value) { NodePosition n = GetPosition (pos); Node node = n.ParentList [n.NodeIndex]; if (node.Data == null) { node.Data = new object [columnTypes.Length]; n.ParentList [n.NodeIndex] = node; } node.Data [column] = value; if (NodeChanged != null) NodeChanged (this, new TreeNodeEventArgs (pos)); } public object GetValue (TreePosition pos, int column) { NodePosition np = GetPosition (pos); Node n = np.ParentList[np.NodeIndex]; if (n.Data == null) return null; return n.Data [column]; } public TreePosition GetChild (TreePosition pos, int index) { if (pos == null) { if (rootNodes.Count == 0) return null; Node n = rootNodes[index]; return new NodePosition () { ParentList = rootNodes, NodeId = n.NodeId, NodeIndex = index, StoreVersion = version }; } else { NodePosition np = GetPosition (pos); Node n = np.ParentList[np.NodeIndex]; if (n.Children == null || index >= n.Children.Count) return null; return new NodePosition () { ParentList = n.Children, NodeId = n.Children[index].NodeId, NodeIndex = index, StoreVersion = version }; } } public TreePosition GetNext (TreePosition pos) { NodePosition np = GetPosition (pos); if (np.NodeIndex >= np.ParentList.Count - 1) return null; Node n = np.ParentList[np.NodeIndex + 1]; return new NodePosition () { ParentList = np.ParentList, NodeId = n.NodeId, NodeIndex = np.NodeIndex + 1, StoreVersion = version }; } public TreePosition GetPrevious (TreePosition pos) { NodePosition np = GetPosition (pos); if (np.NodeIndex <= 0) return null; Node n = np.ParentList[np.NodeIndex - 1]; return new NodePosition () { ParentList = np.ParentList, NodeId = n.NodeId, NodeIndex = np.NodeIndex - 1, StoreVersion = version }; } public int GetChildrenCount (TreePosition pos) { if (pos == null) return rootNodes.Count; NodePosition np = GetPosition (pos); Node n = np.ParentList[np.NodeIndex]; return n.Children != null ? n.Children.Count : 0; } public TreePosition InsertBefore (TreePosition pos) { NodePosition np = GetPosition (pos); Node nn = new Node (); nn.NodeId = nextNodeId++; np.ParentList.Insert (np.NodeIndex, nn); version++; // Update the NodePosition since it is now invalid np.NodeIndex++; np.StoreVersion = version; var node = new NodePosition () { ParentList = np.ParentList, NodeId = nn.NodeId, NodeIndex = np.NodeIndex - 1, StoreVersion = version }; if (NodeInserted != null) NodeInserted (this, new TreeNodeEventArgs (node)); return node; } public TreePosition InsertAfter (TreePosition pos) { NodePosition np = GetPosition (pos); Node nn = new Node (); nn.NodeId = nextNodeId++; np.ParentList.Insert (np.NodeIndex + 1, nn); version++; // Update the provided position is still valid np.StoreVersion = version; var node = new NodePosition () { ParentList = np.ParentList, NodeId = nn.NodeId, NodeIndex = np.NodeIndex + 1, StoreVersion = version }; if (NodeInserted != null) NodeInserted (this, new TreeNodeEventArgs (node)); return node; } public TreePosition AddChild (TreePosition pos) { NodePosition np = GetPosition (pos); Node nn = new Node (); nn.NodeId = nextNodeId++; NodeList list; if (pos == null) { list = rootNodes; } else { Node n = np.ParentList [np.NodeIndex]; if (n.Children == null) { n.Children = new NodeList (); n.Children.Parent = new NodePosition () { ParentList = np.ParentList, NodeId = n.NodeId, NodeIndex = np.NodeIndex, StoreVersion = version }; np.ParentList [np.NodeIndex] = n; } list = n.Children; } list.Add (nn); version++; // The provided position is unafected by this change. Keep it valid. if (np != null) np.StoreVersion = version; var node = new NodePosition () { ParentList = list, NodeId = nn.NodeId, NodeIndex = list.Count - 1, StoreVersion = version }; if (NodeInserted != null) NodeInserted (this, new TreeNodeEventArgs (node)); return node; } public void Remove (TreePosition pos) { NodePosition np = GetPosition (pos); np.ParentList.RemoveAt (np.NodeIndex); var parent = np.ParentList.Parent; var index = np.NodeIndex; version++; if (NodeDeleted != null) NodeDeleted (this, new TreeNodeChildEventArgs (parent, index)); } public TreePosition GetParent (TreePosition pos) { NodePosition np = GetPosition (pos); if (np.ParentList == rootNodes) return null; var parent = np.ParentList.Parent; return new NodePosition () { ParentList = parent.ParentList, NodeId = parent.NodeId, NodeIndex = parent.NodeIndex, StoreVersion = version }; } public Type[] ColumnTypes { get { return columnTypes; } } public void EnableEvent (object eventId) { } public void DisableEvent (object eventId) { } } }
namespace Prototype.Math { public class Matrix4x4 { public Matrix4x4() { if (m_Matrix == null) { m_Matrix = new double[16]; } SetIdentity(); } public Matrix4x4(double m0, double m1, double m2, double m3, double m4, double m5, double m6, double m7, double m8, double m9, double m10, double m11, double m12, double m13, double m14, double m15) { if (m_Matrix == null) { m_Matrix = new double[16]; } m_Matrix[0] = m0; m_Matrix[1] = m1; m_Matrix[2] = m2; m_Matrix[3] = m3; m_Matrix[4] = m4; m_Matrix[5] = m5; m_Matrix[6] = m6; m_Matrix[7] = m7; m_Matrix[8] = m8; m_Matrix[9] = m9; m_Matrix[10] = m10; m_Matrix[11] = m11; m_Matrix[12] = m12; m_Matrix[13] = m13; m_Matrix[14] = m14; m_Matrix[15] = m15; } public Matrix4x4(double[] array) { if (array != null) { if (array.Length == 16) { m_Matrix = new double[16]; for (int i = 0; i < m_Matrix.Length; i++) { m_Matrix[i] = array[i]; } } else { SetIdentity(); } } else { SetIdentity(); } } public static Matrix4x4 operator +(Matrix4x4 m1, Matrix4x4 m2) { Matrix4x4 result = new Matrix4x4(); result[0] = m1[0] + m2[0]; result[1] = m1[1] + m2[1]; result[2] = m1[2] + m2[2]; result[3] = m1[3] + m2[3]; result[4] = m1[4] + m2[4]; result[5] = m1[5] + m2[5]; result[6] = m1[6] + m2[6]; result[7] = m1[7] + m2[7]; result[8] = m1[8] + m2[8]; result[9] = m1[9] + m2[9]; result[10] = m1[10] + m2[10]; result[11] = m1[11] + m2[11]; result[12] = m1[12] + m2[12]; result[13] = m1[13] + m2[13]; result[14] = m1[14] + m2[14]; result[15] = m1[15] + m2[15]; return result; } public static Matrix4x4 operator -(Matrix4x4 m1, Matrix4x4 m2) { Matrix4x4 result = new Matrix4x4(); result[0] = m1[0] - m2[0]; result[1] = m1[1] - m2[1]; result[2] = m1[2] - m2[2]; result[3] = m1[3] - m2[3]; result[4] = m1[4] - m2[4]; result[5] = m1[5] - m2[5]; result[6] = m1[6] - m2[6]; result[7] = m1[7] - m2[7]; result[8] = m1[8] - m2[8]; result[9] = m1[9] - m2[9]; result[10] = m1[10] - m2[10]; result[11] = m1[11] - m2[11]; result[12] = m1[12] - m2[12]; result[13] = m1[13] - m2[13]; result[14] = m1[14] - m2[14]; result[15] = m1[15] - m2[15]; return result; } public static Matrix4x4 operator *(Matrix4x4 m, double d) { Matrix4x4 result = new Matrix4x4(); result[0] = m[0] * d; result[1] = m[1] * d; result[2] = m[2] * d; result[3] = m[3] * d; result[4] = m[4] * d; result[5] = m[5] * d; result[6] = m[6] * d; result[7] = m[7] * d; result[8] = m[8] * d; result[9] = m[9] * d; result[10] = m[10] * d; result[11] = m[11] * d; result[12] = m[12] * d; result[13] = m[13] * d; result[14] = m[14] * d; result[15] = m[15] * d; return result; } public static Matrix4x4 operator /(Matrix4x4 m, double d) { Matrix4x4 result = new Matrix4x4(); result[0] = m[0] / d; result[1] = m[1] / d; result[2] = m[2] / d; result[3] = m[3] / d; result[4] = m[4] / d; result[5] = m[5] / d; result[6] = m[6] / d; result[7] = m[7] / d; result[8] = m[8] / d; result[9] = m[9] / d; result[10] = m[10] / d; result[11] = m[11] / d; result[12] = m[12] / d; result[13] = m[13] / d; result[14] = m[14] / d; result[15] = m[15] / d; return result; } public static Vector3 operator *(Matrix4x4 m, Vector3 v) { Vector3 result = new Vector3(); result.X = m[0] * v.X + m[1] * v.Y + m[2] * v.Z + m[3] * 1; result.Y = m[4] * v.X + m[5] * v.Y + m[6] * v.Z + m[7] * 1; result.Z = m[8] * v.X + m[9] * v.Y + m[10] * v.Z + m[11] * 1; return result; } public static Matrix4x4 operator *(Matrix4x4 m1, Matrix4x4 m2) { Matrix4x4 result = new Matrix4x4(); result[0] = m1[0] * m2[0] + m1[1] * m2[4] + m1[2] * m2[8] + m1[3] * m2[12]; result[1] = m1[0] * m2[1] + m1[1] * m2[5] + m1[2] * m2[9] + m1[3] * m2[13]; result[2] = m1[0] * m2[2] + m1[1] * m2[6] + m1[2] * m2[10] + m1[3] * m2[14]; result[3] = m1[0] * m2[3] + m1[1] * m2[7] + m1[2] * m2[11] + m1[3] * m2[15]; result[4] = m1[4] * m2[0] + m1[5] * m2[4] + m1[6] * m2[8] + m1[7] * m2[12]; result[5] = m1[4] * m2[1] + m1[5] * m2[5] + m1[6] * m2[9] + m1[7] * m2[13]; result[6] = m1[4] * m2[2] + m1[5] * m2[6] + m1[6] * m2[10] + m1[7] * m2[14]; result[7] = m1[4] * m2[3] + m1[5] * m2[7] + m1[6] * m2[11] + m1[7] * m2[15]; result[8] = m1[8] * m2[0] + m1[9] * m2[4] + m1[10] * m2[8] + m1[11] * m2[12]; result[9] = m1[8] * m2[1] + m1[9] * m2[5] + m1[10] * m2[9] + m1[11] * m2[13]; result[10] = m1[8] * m2[2] + m1[9] * m2[6] + m1[10] * m2[10] + m1[11] * m2[14]; result[11] = m1[8] * m2[3] + m1[9] * m2[7] + m1[10] * m2[11] + m1[11] * m2[15]; result[12] = m1[12] * m2[0] + m1[13] * m2[4] + m1[14] * m2[8] + m1[15] * m2[12]; result[13] = m1[12] * m2[1] + m1[13] * m2[5] + m1[14] * m2[9] + m1[15] * m2[13]; result[14] = m1[12] * m2[2] + m1[13] * m2[6] + m1[14] * m2[10] + m1[15] * m2[14]; result[15] = m1[12] * m2[3] + m1[13] * m2[7] + m1[14] * m2[11] + m1[15] * m2[15]; return result; } public double this[int i] { get { if (i >= 0 && i < 16) return m_Matrix[i]; else return double.NaN; } set { if (i >= 0 && i < 16) m_Matrix[i] = value; } } public double this[int i, int j] { get { if (i >= 0 && i < 4 && j >= 0 && j < 4) { return m_Matrix[i * 4 + j]; } else { return double.NaN; } } set { if (i > 0 && i < 4 && j > 0 && j < 4) { m_Matrix[i * 4 + j] = value; } } } public void SetZeroMatrix() { for (int i = 0; i < m_Matrix.Length; i++) m_Matrix[i] = 0; } public void SetIdentity() { m_Matrix[0] = 1; m_Matrix[1] = 0; m_Matrix[2] = 0; m_Matrix[3] = 0; m_Matrix[4] = 0; m_Matrix[5] = 1; m_Matrix[6] = 0; m_Matrix[7] = 0; m_Matrix[8] = 0; m_Matrix[9] = 0; m_Matrix[10] = 1; m_Matrix[11] = 0; m_Matrix[12] = 0; m_Matrix[13] = 0; m_Matrix[14] = 0; m_Matrix[15] = 1; } public void SetPerspective(int width, int height, double fov, double znear, double zfar) { double ar = (double)width / (double)height; double zNear = znear; double zFar = zfar; double zRange = zNear - zFar; double tanHalfFOV = System.Math.Tan(MathHelper.ToRadian(fov / 2.0)); this[0, 0] = 1.0f / (tanHalfFOV * ar); this[0, 1] = 0.0f; this[0, 2] = 0.0f; this[0, 3] = 0.0f; this[1, 0] = 0.0f; this[1, 1] = 1.0f / tanHalfFOV; this[1, 2] = 0.0f; this[1, 3] = 0.0f; this[2, 0] = 0.0f; this[2, 1] = 0.0f; this[2, 2] = (-zNear - zFar) / zRange; this[2, 3] = 2.0f * zFar * zNear / zRange; this[3, 0] = 0.0f; this[3, 1] = 0.0f; this[3, 2] = 1.0f; this[3, 3] = 0.0f; } public void SetCamera(Vector3 position, Vector3 target, Vector3 up) { Matrix4x4 view = new Matrix4x4(); Vector3 zaxis = target - position; zaxis.Normalize(); Vector3 xaxis = Vector3.CrossProduct(up, zaxis); xaxis.Normalize(); Vector3 yaxis = Vector3.CrossProduct(zaxis, xaxis); Vector3 pos = new Vector3() { X = -Vector3.DotProduct(xaxis, position), Y = -Vector3.DotProduct(yaxis, position), Z = -Vector3.DotProduct(zaxis, position), }; view[0, 0] = xaxis.X; view[0, 1] = xaxis.Y; view[0, 2] = xaxis.Z; view[0, 3] = 0.0; view[1, 0] = yaxis.X; view[1, 1] = yaxis.Y; view[1, 2] = yaxis.Z; view[1, 3] = 0.0; view[2, 0] = zaxis.X; view[2, 1] = zaxis.Y; view[2, 2] = zaxis.Z; view[2, 3] = 0.0; view[3, 0] = pos.X; view[3, 1] = pos.Y; view[3, 2] = pos.Z; view[3, 3] = 1.0; m_Matrix = view.ToArray(); } public void Scale(Vector3 v) { m_Matrix[0] = v.X; m_Matrix[5] = v.Y; m_Matrix[10] = v.Z; } public void Translate(Vector3 v) { this[0, 3] = v.X; this[1, 3] = v.Y; this[2, 3] = v.Z; } public void Rotate(double angleX, double angleY, double angleZ) { Matrix4x4 rx = new Matrix4x4(); Matrix4x4 ry = new Matrix4x4(); Matrix4x4 rz = new Matrix4x4(); double x = MathHelper.ToRadian(angleX); double y = MathHelper.ToRadian(angleY); double z = MathHelper.ToRadian(angleZ); rx[0, 0] = 1.0f; rx[0, 1] = 0.0f; rx[0, 2] = 0.0f; rx[0, 3] = 0.0f; rx[1, 0] = 0.0f; rx[1, 1] = System.Math.Cos(x); rx[1, 2] = -System.Math.Sin(x); rx[1, 3] = 0.0f; rx[2, 0] = 0.0f; rx[2, 1] = System.Math.Sin(x); rx[2, 2] = System.Math.Cos(x); rx[2, 3] = 0.0f; rx[3, 0] = 0.0f; rx[3, 1] = 0.0f; rx[3, 2] = 0.0f; rx[3, 3] = 1.0f; ry[0, 0] = System.Math.Cos(y); ry[0, 1] = 0.0f; ry[0, 2] = -System.Math.Sin(y); ry[0, 3] = 0.0f; ry[1, 0] = 0.0f; ry[1, 1] = 1.0f; ry[1, 2] = 0.0f; ry[1, 3] = 0.0f; ry[2, 0] = System.Math.Sin(y); ry[2, 1] = 0.0f; ry[2, 2] = System.Math.Cos(y); ry[2, 3] = 0.0f; ry[3, 0] = 0.0f; ry[3, 1] = 0.0f; ry[3, 2] = 0.0f; ry[3, 3] = 1.0f; rz[0, 0] = System.Math.Cos(z); rz[0, 1] = -System.Math.Sin(z); rz[0, 2] = 0.0f; rz[0, 3] = 0.0f; rz[1, 0] = System.Math.Sin(z); rz[1, 1] = System.Math.Cos(z); rz[1, 2] = 0.0f; rz[1, 3] = 0.0f; rz[2, 0] = 0.0f; rz[2, 1] = 0.0f; rz[2, 2] = 1.0f; rz[2, 3] = 0.0f; rz[3, 0] = 0.0f; rz[3, 1] = 0.0f; rz[3, 2] = 0.0f; rz[3, 3] = 1.0f; m_Matrix = (rz * ry * rx).ToArray(); } public double[] ToArray() { return m_Matrix; } private double[] m_Matrix; } }
using System; using System.Collections; using Server.Network; using Server.Items; using Server.Targeting; namespace Server.Spells.Necromancy { public class StrangleSpell : NecromancerSpell { private static SpellInfo m_Info = new SpellInfo( "Strangle", "In Bal Nox", 209, 9031, Reagent.DaemonBlood, Reagent.NoxCrystal ); public override TimeSpan CastDelayBase { get { return TimeSpan.FromSeconds( 2.0 ); } } public override double RequiredSkill{ get{ return 65.0; } } public override int RequiredMana{ get{ return 29; } } public StrangleSpell( Mobile caster, Item scroll ) : base( caster, scroll, m_Info ) { } public override void OnCast() { Caster.Target = new InternalTarget( this ); } public void Target( Mobile m ) { if ( CheckHSequence( m ) ) { SpellHelper.Turn( Caster, m ); //SpellHelper.CheckReflect( (int)this.Circle, Caster, ref m ); //Irrelevent after AoS /* Temporarily chokes off the air suply of the target with poisonous fumes. * The target is inflicted with poison damage over time. * The amount of damage dealt each "hit" is based off of the caster's Spirit Speak skill and the Target's current Stamina. * The less Stamina the target has, the more damage is done by Strangle. * Duration of the effect is Spirit Speak skill level / 10 rounds, with a minimum number of 4 rounds. * The first round of damage is dealt after 5 seconds, and every next round after that comes 1 second sooner than the one before, until there is only 1 second between rounds. * The base damage of the effect lies between (Spirit Speak skill level / 10) - 2 and (Spirit Speak skill level / 10) + 1. * Base damage is multiplied by the following formula: (3 - (target's current Stamina / target's maximum Stamina) * 2). * Example: * For a target at full Stamina the damage multiplier is 1, * for a target at 50% Stamina the damage multiplier is 2 and * for a target at 20% Stamina the damage multiplier is 2.6 */ if ( m.Spell != null ) m.Spell.OnCasterHurt(); m.PlaySound( 0x22F ); m.FixedParticles( 0x36CB, 1, 9, 9911, 67, 5, EffectLayer.Head ); m.FixedParticles( 0x374A, 1, 17, 9502, 1108, 4, (EffectLayer)255 ); if ( !m_Table.Contains( m ) ) { Timer t = new InternalTimer( m, Caster ); t.Start(); m_Table[m] = t; } HarmfulSpell(m); } //Calculations for the buff bar double spiritlevel = Caster.Skills[SkillName.SpiritSpeak].Value / 10; if (spiritlevel < 4) spiritlevel = 4; int d_MinDamage = 4; int d_MaxDamage = ((int)spiritlevel + 1) * 3; string args = String.Format("{0}\t{1}", d_MinDamage, d_MaxDamage); int i_Count = (int)spiritlevel; int i_MaxCount = i_Count; int i_HitDelay = 5; int i_Length = i_HitDelay; while (i_Count > 1) { --i_Count; if (i_HitDelay > 1) { if (i_MaxCount < 5) { --i_HitDelay; } else { int delay = (int)(Math.Ceiling((1.0 + (5 * i_Count)) / i_MaxCount)); if (delay <= 5) i_HitDelay = delay; else i_HitDelay = 5; } } i_Length += i_HitDelay; } TimeSpan t_Duration = TimeSpan.FromSeconds(i_Length); BuffInfo.AddBuff(m, new BuffInfo(BuffIcon.Strangle, 1075794, 1075795, t_Duration, m, args.ToString())); FinishSequence(); } private static Hashtable m_Table = new Hashtable(); public static bool RemoveCurse( Mobile m ) { Timer t = (Timer)m_Table[m]; if ( t == null ) return false; t.Stop(); m.SendLocalizedMessage( 1061687 ); // You can breath normally again. m_Table.Remove( m ); return true; } private class InternalTimer : Timer { private Mobile m_Target, m_From; private double m_MinBaseDamage, m_MaxBaseDamage; private DateTime m_NextHit; private int m_HitDelay; private int m_Count, m_MaxCount; public InternalTimer( Mobile target, Mobile from ) : base( TimeSpan.FromSeconds( 0.1 ), TimeSpan.FromSeconds( 0.1 ) ) { Priority = TimerPriority.FiftyMS; m_Target = target; m_From = from; double spiritLevel = from.Skills[SkillName.SpiritSpeak].Value / 10; m_MinBaseDamage = spiritLevel - 2; m_MaxBaseDamage = spiritLevel + 1; m_HitDelay = 5; m_NextHit = DateTime.Now + TimeSpan.FromSeconds( m_HitDelay ); m_Count = (int)spiritLevel; if ( m_Count < 4 ) m_Count = 4; m_MaxCount = m_Count; } protected override void OnTick() { if ( !m_Target.Alive ) { m_Table.Remove( m_Target ); Stop(); } if ( !m_Target.Alive || DateTime.Now < m_NextHit ) return; --m_Count; if ( m_HitDelay > 1 ) { if ( m_MaxCount < 5 ) { --m_HitDelay; } else { int delay = (int)(Math.Ceiling( (1.0 + (5 * m_Count)) / m_MaxCount ) ); if ( delay <= 5 ) m_HitDelay = delay; else m_HitDelay = 5; } } if ( m_Count == 0 ) { m_Target.SendLocalizedMessage( 1061687 ); // You can breath normally again. m_Table.Remove( m_Target ); Stop(); } else { m_NextHit = DateTime.Now + TimeSpan.FromSeconds( m_HitDelay ); double damage = m_MinBaseDamage + (Utility.RandomDouble() * (m_MaxBaseDamage - m_MinBaseDamage)); damage *= (3 - (((double)m_Target.Stam / m_Target.StamMax) * 2)); if ( damage < 1 ) damage = 1; if ( !m_Target.Player ) damage *= 1.75; AOS.Damage( m_Target, m_From, (int)damage, 0, 0, 0, 100, 0 ); if (0.60 <= Utility.RandomDouble()) // OSI: randomly revealed between first and third damage tick, guessing 60% chance m_Target.RevealingAction(); } } } private class InternalTarget : Target { private StrangleSpell m_Owner; public InternalTarget( StrangleSpell owner ) : base( Core.ML ? 10 : 12, false, TargetFlags.Harmful ) { m_Owner = owner; } protected override void OnTarget( Mobile from, object o ) { if ( o is Mobile ) m_Owner.Target( (Mobile) o ); } protected override void OnTargetFinish( Mobile from ) { m_Owner.FinishSequence(); } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Microsoft.TemplateEngine.Abstractions; using Microsoft.TemplateEngine.Core.Contracts; using Microsoft.TemplateEngine.Core.Util; namespace Microsoft.TemplateEngine.Core.Expressions.Cpp { public static class CppStyleEvaluatorDefinition { private const int ReservedTokenCount = 24; private const int ReservedTokenMaxIndex = ReservedTokenCount - 1; private static readonly IOperationProvider[] NoOperationProviders = new IOperationProvider[0]; private static readonly char[] SupportedQuotes = {'"', '\''}; public static bool EvaluateFromString(IEngineEnvironmentSettings environmentSettings, string text, IVariableCollection variables) { using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(text))) using (MemoryStream res = new MemoryStream()) { EngineConfig cfg = new EngineConfig(environmentSettings, variables); IProcessorState state = new ProcessorState(ms, res, (int)ms.Length, (int)ms.Length, cfg, NoOperationProviders); int len = (int)ms.Length; int pos = 0; return Evaluate(state, ref len, ref pos, out bool faulted); } } public static bool Evaluate(IProcessorState processor, ref int bufferLength, ref int currentBufferPosition, out bool faulted) { faulted = false; TokenTrie trie = new TokenTrie(); //Logic trie.AddToken(processor.Encoding.GetBytes("&&"), 0); trie.AddToken(processor.Encoding.GetBytes("||"), 1); trie.AddToken(processor.Encoding.GetBytes("^"), 2); trie.AddToken(processor.Encoding.GetBytes("!"), 3); trie.AddToken(processor.Encoding.GetBytes(">"), 4); trie.AddToken(processor.Encoding.GetBytes(">="), 5); trie.AddToken(processor.Encoding.GetBytes("<"), 6); trie.AddToken(processor.Encoding.GetBytes("<="), 7); trie.AddToken(processor.Encoding.GetBytes("=="), 8); trie.AddToken(processor.Encoding.GetBytes("="), 9); trie.AddToken(processor.Encoding.GetBytes("!="), 10); //Bitwise trie.AddToken(processor.Encoding.GetBytes("&"), 11); trie.AddToken(processor.Encoding.GetBytes("|"), 12); trie.AddToken(processor.Encoding.GetBytes("<<"), 13); trie.AddToken(processor.Encoding.GetBytes(">>"), 14); //Braces trie.AddToken(processor.Encoding.GetBytes("("), 15); trie.AddToken(processor.Encoding.GetBytes(")"), 16); //Whitespace trie.AddToken(processor.Encoding.GetBytes(" "), 17); trie.AddToken(processor.Encoding.GetBytes("\t"), 18); //EOLs trie.AddToken(processor.Encoding.GetBytes("\r\n"), 19); trie.AddToken(processor.Encoding.GetBytes("\n"), 20); trie.AddToken(processor.Encoding.GetBytes("\r"), 21); // quotes trie.AddToken(processor.Encoding.GetBytes("\""), 22); trie.AddToken(processor.Encoding.GetBytes("'"), 23); //Tokens trie.Append(processor.EncodingConfig.Variables); //Run forward to EOL and collect args TokenFamily currentTokenFamily; List<byte> currentTokenBytes = new List<byte>(); List<TokenRef> tokens = new List<TokenRef>(); if (!trie.GetOperation(processor.CurrentBuffer, bufferLength, ref currentBufferPosition, out int token)) { currentTokenFamily = TokenFamily.Literal; currentTokenBytes.Add(processor.CurrentBuffer[currentBufferPosition++]); } else if (token > ReservedTokenMaxIndex) { currentTokenFamily = TokenFamily.Reference | (TokenFamily)token; tokens.Add(new TokenRef { Family = currentTokenFamily }); } else { currentTokenFamily = (TokenFamily)token; if (currentTokenFamily != TokenFamily.WindowsEOL && currentTokenFamily != TokenFamily.LegacyMacEOL && currentTokenFamily != TokenFamily.UnixEOL) { tokens.Add(new TokenRef { Family = currentTokenFamily }); } else { return EvaluateCondition(tokens, processor.EncodingConfig.VariableValues); } } int braceDepth = 0; if (tokens[0].Family == TokenFamily.OpenBrace) { ++braceDepth; } bool first = true; QuotedRegionKind inQuoteType = QuotedRegionKind.None; while ((first || braceDepth > 0) && bufferLength > 0) { int targetLen = Math.Min(bufferLength, trie.MaxLength); for (; currentBufferPosition < bufferLength - targetLen + 1;) { int oldBufferPos = currentBufferPosition; if (trie.GetOperation(processor.CurrentBuffer, bufferLength, ref currentBufferPosition, out token)) { if (braceDepth == 0) { switch (tokens[tokens.Count - 1].Family) { case TokenFamily.Whitespace: case TokenFamily.Tab: case TokenFamily.CloseBrace: case TokenFamily.WindowsEOL: case TokenFamily.UnixEOL: case TokenFamily.LegacyMacEOL: TokenFamily thisFamily = (TokenFamily)token; if (thisFamily == TokenFamily.WindowsEOL || thisFamily == TokenFamily.UnixEOL || thisFamily == TokenFamily.LegacyMacEOL) { currentBufferPosition = oldBufferPos; } break; default: currentBufferPosition = oldBufferPos; first = false; break; } if (!first) { break; } } // We matched an item, so whatever this is, it's not a literal. // if the current token is a literal, end it. if (currentTokenFamily == TokenFamily.Literal) { string literal = processor.Encoding.GetString(currentTokenBytes.ToArray()); tokens.Add(new TokenRef { Family = TokenFamily.Literal, Literal = literal }); currentTokenBytes.Clear(); } TokenFamily foundTokenFamily = (TokenFamily)token; if (foundTokenFamily == TokenFamily.QuotedLiteral || foundTokenFamily == TokenFamily.SingleQuotedLiteral) { QuotedRegionKind incomingQuoteKind; switch (foundTokenFamily) { case TokenFamily.QuotedLiteral: incomingQuoteKind = QuotedRegionKind.DoubleQuoteRegion; break; case TokenFamily.SingleQuotedLiteral: incomingQuoteKind = QuotedRegionKind.SingleQuoteRegion; break; default: incomingQuoteKind = QuotedRegionKind.None; break; } if (inQuoteType == QuotedRegionKind.None) { // starting quote found currentTokenBytes.AddRange(trie.Tokens[token].Value); inQuoteType = incomingQuoteKind; } else if (incomingQuoteKind == inQuoteType) { // end quote found currentTokenBytes.AddRange(trie.Tokens[token].Value); tokens.Add(new TokenRef { Family = TokenFamily.Literal, Literal = processor.Encoding.GetString(currentTokenBytes.ToArray()) }); currentTokenBytes.Clear(); inQuoteType = QuotedRegionKind.None; } else { // this is a different quote type. Treat it like a non-match, just add the token to the currentTokenBytes currentTokenBytes.AddRange(trie.Tokens[token].Value); } } else if (inQuoteType != QuotedRegionKind.None) { // we're inside a quoted literal, the token found by the trie should not be processed, just included with the literal currentTokenBytes.AddRange(trie.Tokens[token].Value); } else if (token > ReservedTokenMaxIndex) { currentTokenFamily = TokenFamily.Reference | (TokenFamily)token; tokens.Add(new TokenRef { Family = currentTokenFamily }); } else { //If we have a normal token... currentTokenFamily = (TokenFamily)token; if (currentTokenFamily != TokenFamily.WindowsEOL && currentTokenFamily != TokenFamily.LegacyMacEOL && currentTokenFamily != TokenFamily.UnixEOL) { switch (currentTokenFamily) { case TokenFamily.OpenBrace: ++braceDepth; break; case TokenFamily.CloseBrace: --braceDepth; break; } tokens.Add(new TokenRef { Family = currentTokenFamily }); } else { return EvaluateCondition(tokens, processor.EncodingConfig.VariableValues); } } } else if (inQuoteType != QuotedRegionKind.None) { // we're in a quoted literal but did not match a token at the current position. // so just add the current byte to the currentTokenBytes currentTokenBytes.Add(processor.CurrentBuffer[currentBufferPosition++]); } else if (braceDepth > 0) { currentTokenFamily = TokenFamily.Literal; currentTokenBytes.Add(processor.CurrentBuffer[currentBufferPosition++]); } else { first = false; break; } } processor.AdvanceBuffer(currentBufferPosition); currentBufferPosition = processor.CurrentBufferPosition; bufferLength = processor.CurrentBufferLength; } #if DEBUG Debug.Assert(inQuoteType == QuotedRegionKind.None, $"Malformed predicate due to unmatched quotes. InitialBuffer = {processor.Encoding.GetString(processor.CurrentBuffer)} currentTokenFamily = {currentTokenFamily} | TokenFamily.QuotedLiteral = {TokenFamily.QuotedLiteral} | TokenFamily.SingleQuotedLiteral = {TokenFamily.SingleQuotedLiteral}"); #endif return EvaluateCondition(tokens, processor.EncodingConfig.VariableValues); } private static bool IsLogicalOperator(Operator op) { return op == Operator.And || op == Operator.Or || op == Operator.Xor || op == Operator.Not; } private static void CombineExpressionOperator(ref Scope current, Stack<Scope> parents) { if (current.Operator == Operator.None) { if (current.TargetPlacement != Scope.NextPlacement.Right || !(current.Left is Scope leftScope) || !IsLogicalOperator(leftScope.Operator)) { return; } Scope tmp2 = new Scope { Value = leftScope.Right }; leftScope.Right = tmp2; parents.Push(leftScope); current = tmp2; return; } Scope tmp = new Scope(); if (!IsLogicalOperator(current.Operator)) { tmp.Value = current; } else { tmp.Value = current.Right; current.Right = tmp; parents.Push(current); } current = tmp; } private static bool EvaluateCondition(IReadOnlyList<TokenRef> tokens, IReadOnlyList<Func<object>> values) { //Skip over all leading whitespace int i = 0; for (; i < tokens.Count && (tokens[i].Family == TokenFamily.Whitespace || tokens[i].Family == TokenFamily.Tab); ++i) { } //Scan through all remaining tokens and put them in a form the standard evaluator can understand List<TokenRef> outputTokens = new List<TokenRef>(); for (; i < tokens.Count; ++i) { if (tokens[i].Family == TokenFamily.Whitespace || tokens[i].Family == TokenFamily.Tab) { //Ignore whitespace } else { if (tokens[i].Family.HasFlag(TokenFamily.Reference)) { outputTokens.Add(tokens[i]); } else if (tokens[i].Family == TokenFamily.Literal) { //Combine literals string literalValue = tokens[i].Literal; string followingWhitespace = ""; int reach = i; for (int j = i + 1; j < tokens.Count; ++j) { switch (tokens[j].Family) { case TokenFamily.Literal: literalValue += followingWhitespace + tokens[j].Literal; followingWhitespace = string.Empty; reach = j; break; case TokenFamily.Tab: followingWhitespace += '\t'; break; case TokenFamily.Whitespace: followingWhitespace += ' '; break; default: j = tokens.Count; break; } } i = reach; outputTokens.Add(new TokenRef { Family = TokenFamily.Literal, Literal = literalValue }); } else { outputTokens.Add(tokens[i]); } } } Scope root = new Scope(); Scope current = root; Stack<Scope> parents = new Stack<Scope>(); for (i = 0; i < outputTokens.Count; ++i) { switch (outputTokens[i].Family) { case TokenFamily.Not: { Scope nextScope = new Scope { TargetPlacement = Scope.NextPlacement.Right }; current.Value = nextScope; parents.Push(current); current = nextScope; current.Operator = Operator.Not; break; } case TokenFamily.Literal: current.Value = InferTypeAndConvertLiteral(outputTokens[i].Literal); while (parents.Count > 0 && current.TargetPlacement == Scope.NextPlacement.None) { current = parents.Pop(); } break; case TokenFamily.And: if (current.Operator != Operator.None) { Scope s = new Scope { Value = current }; current = s; } current.Operator = Operator.And; current.TargetPlacement = Scope.NextPlacement.Right; break; case TokenFamily.BitwiseAnd: CombineExpressionOperator(ref current, parents); current.Operator = Operator.BitwiseAnd; break; case TokenFamily.BitwiseOr: CombineExpressionOperator(ref current, parents); current.Operator = Operator.BitwiseOr; break; case TokenFamily.CloseBrace: //If the grouping is valid, the grouping has already been closed // due to argument fulfillment, do nothing. // -- OR -- //This is a grouping around a unary operator if (parents.Count > 0 && current.TargetPlacement == Scope.NextPlacement.Right) { current = parents.Pop(); } break; case TokenFamily.EqualTo: case TokenFamily.EqualToShort: CombineExpressionOperator(ref current, parents); current.Operator = Operator.EqualTo; break; case TokenFamily.GreaterThan: CombineExpressionOperator(ref current, parents); current.Operator = Operator.GreaterThan; break; case TokenFamily.GreaterThanOrEqualTo: CombineExpressionOperator(ref current, parents); current.Operator = Operator.GreaterThanOrEqualTo; break; case TokenFamily.LeftShift: CombineExpressionOperator(ref current, parents); current.Operator = Operator.LeftShift; break; case TokenFamily.LessThan: CombineExpressionOperator(ref current, parents); current.Operator = Operator.LessThan; break; case TokenFamily.LessThanOrEqualTo: CombineExpressionOperator(ref current, parents); current.Operator = Operator.LessThanOrEqualTo; break; case TokenFamily.NotEqualTo: CombineExpressionOperator(ref current, parents); current.Operator = Operator.NotEqualTo; break; case TokenFamily.OpenBrace: { Scope nextScope = new Scope(); current.Value = nextScope; parents.Push(current); current = nextScope; break; } case TokenFamily.Or: if (current.Operator != Operator.None) { Scope s = new Scope { Value = current }; current = s; } current.Operator = Operator.Or; break; case TokenFamily.RightShift: CombineExpressionOperator(ref current, parents); current.Operator = Operator.RightShift; break; case TokenFamily.Xor: if (current.Operator != Operator.None) { Scope s = new Scope { Value = current }; current = s; } current.Operator = Operator.Xor; break; default: current.Value = ResolveToken(outputTokens[i], values); while (parents.Count > 0 && current.TargetPlacement == Scope.NextPlacement.None) { current = parents.Pop(); } break; } } Debug.Assert(parents.Count == 0, "Unbalanced condition"); return (bool)Convert.ChangeType(current.Evaluate() ?? "false", typeof(bool)); } private static object InferTypeAndConvertLiteral(string literal) { //A propertly quoted string must be... // At least two characters long // Start and end with the same character // The character that the string starts with must be one of the supported quote kinds if (literal.Length < 2 || literal[0] != literal[literal.Length - 1] || !SupportedQuotes.Contains(literal[0])) { if (string.Equals(literal, "true", StringComparison.OrdinalIgnoreCase)) { return true; } if (string.Equals(literal, "false", StringComparison.OrdinalIgnoreCase)) { return false; } if (string.Equals(literal, "null", StringComparison.OrdinalIgnoreCase)) { return null; } if (literal.Contains(".") && double.TryParse(literal, out double literalDouble)) { return literalDouble; } if (long.TryParse(literal, out long literalLong)) { return literalLong; } if (literal.StartsWith("0x", StringComparison.OrdinalIgnoreCase) && long.TryParse(literal.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out literalLong)) { return literalLong; } return null; } return literal.Substring(1, literal.Length - 2); } private static object ResolveToken(TokenRef tokenRef, IReadOnlyList<Func<object>> values) { return values[(int)(tokenRef.Family & ~TokenFamily.Reference) - ReservedTokenCount](); } } }
// 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.Reflection; using System.Runtime.CompilerServices; using System.Threading; namespace System.Runtime.InteropServices { /// <summary> /// A delegate used to resolve native libraries via callback. /// </summary> /// <param name="libraryName">The native library to resolve</param> /// <param name="assembly">The assembly requesting the resolution</param> /// <param name="searchPath"> /// The DllImportSearchPathsAttribute on the PInvoke, if any. /// Otherwise, the DllImportSearchPathsAttribute on the assembly, if any. /// Otherwise null. /// </param> /// <returns>The handle for the loaded native library on success, null on failure</returns> public delegate IntPtr DllImportResolver(string libraryName, Assembly assembly, DllImportSearchPath? searchPath); /// <summary> /// APIs for managing Native Libraries /// </summary> public static partial class NativeLibrary { /// <summary> /// NativeLibrary Loader: Simple API /// This method is a wrapper around OS loader, using "default" flags. /// </summary> /// <param name="libraryPath">The name of the native library to be loaded</param> /// <returns>The handle for the loaded native library</returns> /// <exception cref="System.ArgumentNullException">If libraryPath is null</exception> /// <exception cref="System.DllNotFoundException ">If the library can't be found.</exception> /// <exception cref="System.BadImageFormatException">If the library is not valid.</exception> public static IntPtr Load(string libraryPath) { if (libraryPath == null) throw new ArgumentNullException(nameof(libraryPath)); return LoadFromPath(libraryPath, throwOnError: true); } /// <summary> /// NativeLibrary Loader: Simple API that doesn't throw /// </summary> /// <param name="libraryPath">The name of the native library to be loaded</param> /// <param name="handle">The out-parameter for the loaded native library handle</param> /// <returns>True on successful load, false otherwise</returns> /// <exception cref="System.ArgumentNullException">If libraryPath is null</exception> public static bool TryLoad(string libraryPath, out IntPtr handle) { if (libraryPath == null) throw new ArgumentNullException(nameof(libraryPath)); handle = LoadFromPath(libraryPath, throwOnError: false); return handle != IntPtr.Zero; } /// <summary> /// NativeLibrary Loader: High-level API /// Given a library name, this function searches specific paths based on the /// runtime configuration, input parameters, and attributes of the calling assembly. /// If DllImportSearchPath parameter is non-null, the flags in this enumeration are used. /// Otherwise, the flags specified by the DefaultDllImportSearchPaths attribute on the /// calling assembly (if any) are used. /// This LoadLibrary() method does not invoke the managed call-backs for native library resolution: /// * The per-assembly registered callback /// * AssemblyLoadContext.LoadUnmanagedDll() /// * AssemblyLoadContext.ResolvingUnmanagedDllEvent /// </summary> /// <param name="libraryName">The name of the native library to be loaded</param> /// <param name="assembly">The assembly loading the native library</param> /// <param name="searchPath">The search path</param> /// <returns>The handle for the loaded library</returns> /// <exception cref="System.ArgumentNullException">If libraryPath or assembly is null</exception> /// <exception cref="System.ArgumentException">If assembly is not a RuntimeAssembly</exception> /// <exception cref="System.DllNotFoundException ">If the library can't be found.</exception> /// <exception cref="System.BadImageFormatException">If the library is not valid.</exception> public static IntPtr Load(string libraryName, Assembly assembly, DllImportSearchPath? searchPath) { if (libraryName == null) throw new ArgumentNullException(nameof(libraryName)); if (assembly == null) throw new ArgumentNullException(nameof(assembly)); if (!assembly.IsRuntimeImplemented()) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); return LoadLibraryByName(libraryName, assembly, searchPath, throwOnError: true); } /// <summary> /// NativeLibrary Loader: High-level API that doesn't throw. /// </summary> /// <param name="libraryName">The name of the native library to be loaded</param> /// <param name="searchPath">The search path</param> /// <param name="assembly">The assembly loading the native library</param> /// <param name="handle">The out-parameter for the loaded native library handle</param> /// <returns>True on successful load, false otherwise</returns> /// <exception cref="System.ArgumentNullException">If libraryPath or assembly is null</exception> /// <exception cref="System.ArgumentException">If assembly is not a RuntimeAssembly</exception> public static bool TryLoad(string libraryName, Assembly assembly, DllImportSearchPath? searchPath, out IntPtr handle) { if (libraryName == null) throw new ArgumentNullException(nameof(libraryName)); if (assembly == null) throw new ArgumentNullException(nameof(assembly)); if (!assembly.IsRuntimeImplemented()) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); handle = LoadLibraryByName(libraryName, assembly, searchPath, throwOnError: false); return handle != IntPtr.Zero; } /// <summary> /// Free a loaded library /// Given a library handle, free it. /// No action if the input handle is null. /// </summary> /// <param name="handle">The native library handle to be freed</param> public static void Free(IntPtr handle) { FreeLib(handle); } /// <summary> /// Get the address of an exported Symbol /// This is a simple wrapper around OS calls, and does not perform any name mangling. /// </summary> /// <param name="handle">The native library handle</param> /// <param name="name">The name of the exported symbol</param> /// <returns>The address of the symbol</returns> /// <exception cref="System.ArgumentNullException">If handle or name is null</exception> /// <exception cref="System.EntryPointNotFoundException">If the symbol is not found</exception> public static IntPtr GetExport(IntPtr handle, string name) { if (handle == IntPtr.Zero) throw new ArgumentNullException(nameof(handle)); if (name == null) throw new ArgumentNullException(nameof(name)); return GetSymbol(handle, name, throwOnError: true); } /// <summary> /// Get the address of an exported Symbol, but do not throw /// </summary> /// <param name="handle">The native library handle</param> /// <param name="name">The name of the exported symbol</param> /// <param name="address"> The out-parameter for the symbol address, if it exists</param> /// <returns>True on success, false otherwise</returns> /// <exception cref="System.ArgumentNullException">If handle or name is null</exception> public static bool TryGetExport(IntPtr handle, string name, out IntPtr address) { if (handle == IntPtr.Zero) throw new ArgumentNullException(nameof(handle)); if (name == null) throw new ArgumentNullException(nameof(name)); address = GetSymbol(handle, name, throwOnError: false); return address != IntPtr.Zero; } /// <summary> /// Map from assembly to native-library resolver. /// Interop specific fields and properties are generally not added to Assembly class. /// Therefore, this table uses weak assembly pointers to indirectly achieve /// similar behavior. /// </summary> private static ConditionalWeakTable<Assembly, DllImportResolver>? s_nativeDllResolveMap; /// <summary> /// Set a callback for resolving native library imports from an assembly. /// This per-assembly resolver is the first attempt to resolve native library loads /// initiated by this assembly. /// /// Only one resolver can be registered per assembly. /// Trying to register a second resolver fails with InvalidOperationException. /// </summary> /// <param name="assembly">The assembly for which the resolver is registered</param> /// <param name="resolver">The resolver callback to register</param> /// <exception cref="System.ArgumentNullException">If assembly or resolver is null</exception> /// <exception cref="System.ArgumentException">If a resolver is already set for this assembly</exception> public static void SetDllImportResolver(Assembly assembly, DllImportResolver resolver) { if (assembly == null) throw new ArgumentNullException(nameof(assembly)); if (resolver == null) throw new ArgumentNullException(nameof(resolver)); if (!assembly.IsRuntimeImplemented()) throw new ArgumentException(SR.Argument_MustBeRuntimeAssembly); if (s_nativeDllResolveMap == null) { Interlocked.CompareExchange(ref s_nativeDllResolveMap, new ConditionalWeakTable<Assembly, DllImportResolver>(), null); } try { s_nativeDllResolveMap.Add(assembly, resolver); } catch (ArgumentException) { // ConditionalWealTable throws ArgumentException if the Key already exists throw new InvalidOperationException(SR.InvalidOperation_CannotRegisterSecondResolver); } } /// <summary> /// The helper function that calls the per-assembly native-library resolver /// if one is registered for this assembly. /// </summary> /// <param name="libraryName">The native library to load</param> /// <param name="assembly">The assembly trying load the native library</param> /// <param name="hasDllImportSearchPathFlags">If the pInvoke has DefaultDllImportSearchPathAttribute</param> /// <param name="dllImportSearchPathFlags">If hasdllImportSearchPathFlags is true, the flags in /// DefaultDllImportSearchPathAttribute; meaningless otherwise </param> /// <returns>The handle for the loaded library on success. Null on failure.</returns> internal static IntPtr LoadLibraryCallbackStub(string libraryName, Assembly assembly, bool hasDllImportSearchPathFlags, uint dllImportSearchPathFlags) { if (s_nativeDllResolveMap == null) { return IntPtr.Zero; } if (!s_nativeDllResolveMap.TryGetValue(assembly, out DllImportResolver? resolver)) { return IntPtr.Zero; } return resolver(libraryName, assembly, hasDllImportSearchPathFlags ? (DllImportSearchPath?)dllImportSearchPathFlags : null); } } }
// // Copyright 2014-2015 Amazon.com, // Inc. or its affiliates. All Rights Reserved. // // Licensed under the Amazon Software License (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/asl/ // // or in the "license" file accompanying this file. This file is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, express or implied. See the License // for the specific language governing permissions and // limitations under the License. // using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using Amazon.DynamoDBv2.DocumentModel; using Amazon.DynamoDBv2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal.Util; using Amazon.Util; using Amazon.Util.Internal; namespace Amazon.DynamoDBv2.DataModel { /// <summary> /// Basic property storage information /// </summary> internal class SimplePropertyStorage { // local property name public string PropertyName { get; protected set; } // DynamoDB attribute name public string AttributeName { get; set; } // MemberInfo of the property public MemberInfo Member { get; protected set; } // Type of the property public Type MemberType { get; protected set; } // Converter type, if one is present public Type ConverterType { get; set; } // Converter, if one is present public IPropertyConverter Converter { get; protected set; } public SimplePropertyStorage(MemberInfo member) : this(Utils.GetType(member)) { Member = member; PropertyName = member.Name; } public SimplePropertyStorage(Type memberType) { MemberType = memberType; } } /// <summary> /// DynamoDB property storage information /// </summary> internal class PropertyStorage : SimplePropertyStorage { // flags public bool IsHashKey { get; set; } public bool IsRangeKey { get; set; } public bool IsKey { get { return IsHashKey || IsRangeKey; } } public bool IsVersion { get; set; } public bool IsLSIRangeKey { get; set; } public bool IsGSIHashKey { get; set; } public bool IsGSIRangeKey { get; set; } public bool IsGSIKey { get { return IsGSIHashKey || IsGSIRangeKey; } } public bool IsIgnored { get; set; } // corresponding IndexNames, if applicable public List<string> IndexNames { get; set; } public void AddIndex(DynamoDBGlobalSecondaryIndexHashKeyAttribute gsiHashKey) { AddIndex(new GSI(true, gsiHashKey.AttributeName, gsiHashKey.IndexNames)); } public void AddIndex(DynamoDBGlobalSecondaryIndexRangeKeyAttribute gsiRangeKey) { AddIndex(new GSI(false, gsiRangeKey.AttributeName, gsiRangeKey.IndexNames)); } public void AddIndex(DynamoDBLocalSecondaryIndexRangeKeyAttribute lsiRangeKey) { AddIndex(new LSI(lsiRangeKey.AttributeName, lsiRangeKey.IndexNames)); } public void AddGsiIndex(bool isHashKey, string attributeName, params string[] indexNames) { AddIndex(new GSI(isHashKey, attributeName, indexNames)); } public void AddLsiIndex(string attributeName, params string[] indexNames) { AddIndex(new LSI(attributeName, indexNames)); } public void AddIndex(Index index) { Indexes.Add(index); } public List<Index> Indexes { get; private set; } public abstract class Index { public List<string> IndexNames { get; private set; } public string AttributeName { get; private set; } public Index(string attributeName, params string[] indexNames) { IndexNames = new List<string>(indexNames); AttributeName = attributeName; } } public class LSI : Index { public LSI(string attributeName, params string[] indexNames) : base(attributeName, indexNames) { } } public class GSI : Index { public bool IsHashKey { get; private set; } public GSI(bool isHashKey, string attributeName, params string[] indexNames) : base(attributeName, indexNames) { IsHashKey = isHashKey; } } /// <summary> /// Validates configurations and sets required fields /// </summary> public void Validate(DynamoDBContext context) { if (IsVersion) Utils.ValidateVersionType(MemberType); // no conversion is possible, so type must be a nullable primitive if (IsHashKey && IsRangeKey) throw new InvalidOperationException("Property " + PropertyName + " cannot be both hash and range key"); if (ConverterType != null) { if (!Utils.CanInstantiateConverter(ConverterType) || !Utils.ImplementsInterface(ConverterType, typeof(IPropertyConverter))) throw new InvalidOperationException("Converter for " + PropertyName + " must be instantiable with no parameters and must implement IPropertyConverter"); this.Converter = Utils.InstantiateConverter(ConverterType, context) as IPropertyConverter; } IPropertyConverter converter; if (context.ConverterCache.TryGetValue(MemberType, out converter) && converter != null) { this.Converter = converter; } if (IsKey || IsGSIKey) if (Converter == null && !Utils.IsPrimitive(MemberType)) throw new InvalidOperationException("Key " + PropertyName + " must be of primitive type"); foreach (var index in Indexes) IndexNames.AddRange(index.IndexNames); } public PropertyStorage(MemberInfo member) : base(member) { IndexNames = new List<string>(); Indexes = new List<Index>(); } } /// <summary> /// Storage information for a single item /// </summary> internal class ItemStorage { public Document Document { get; set; } public ItemStorageConfig Config { get; set; } public Primitive CurrentVersion { get; set; } public HashSet<object> ConvertedObjects { get; private set; } public ItemStorage(ItemStorageConfig storageConfig) { Document = new Document(); Config = storageConfig; ConvertedObjects = new HashSet<object>(); } } /// <summary> /// GSI info /// </summary> internal class GSIConfig { public GSIConfig(string indexName) { IndexName = indexName; } // index name public string IndexName { get; set; } // keys public string HashKeyPropertyName { get; set; } public string RangeKeyPropertyName { get; set; } } /// <summary> /// Storage information for a specific class /// </summary> internal class StorageConfig { // normalized PropertyStorage objects public List<PropertyStorage> Properties { get; private set; } // target type public ITypeInfo TargetTypeInfo { get; private set; } // target type members public Dictionary<string, MemberInfo> TargetTypeMembers { get; private set; } // storage mappings private Dictionary<string, PropertyStorage> PropertyToPropertyStorageMapping { get; set; } protected void AddPropertyStorage(string propertyName, PropertyStorage propertyStorage) { PropertyToPropertyStorageMapping[propertyName] = propertyStorage; } public PropertyStorage GetPropertyStorage(string propertyName) { PropertyStorage storage; if (TryGetPropertyStorage(propertyName, out storage)) return storage; throw new InvalidOperationException("Unable to find storage information for property [" + propertyName + "]"); } public bool TryGetPropertyStorage(string propertyName, out PropertyStorage storage) { return (PropertyToPropertyStorageMapping.TryGetValue(propertyName, out storage)); } public IEnumerable<PropertyStorage> AllPropertyStorage { get { return PropertyToPropertyStorageMapping.Values; } } public bool FindPropertyByPropertyName(string propertyName, out PropertyStorage propertyStorage) { return FindSingleProperty( p => string.Equals(p.PropertyName, propertyName, StringComparison.Ordinal), "Multiple properties configured for property " + propertyName, out propertyStorage); } public bool FindSinglePropertyByAttributeName(string attributeName, out PropertyStorage propertyStorage) { return FindSingleProperty( p => string.Equals(p.AttributeName, attributeName, StringComparison.Ordinal), "Multiple properties configured for attribute " + attributeName, out propertyStorage); } private bool FindSingleProperty(Func<PropertyStorage, bool> match, string errorMessage, out PropertyStorage propertyStorage) { var properties = Properties.Where(match).ToList(); if (properties.Count == 0) { propertyStorage = null; return false; } if (properties.Count == 1) { propertyStorage = properties[0]; return true; } throw new InvalidOperationException(errorMessage); } public static bool IsValidMemberInfo(MemberInfo member) { // filter out non-fields and non-properties if (!(member is FieldInfo || member is PropertyInfo)) return false; // filter out properties that aren't both read and write if (!Utils.IsReadWrite(member)) return false; return true; } private static Dictionary<string, MemberInfo> GetMembersDictionary(ITypeInfo typeInfo) { Dictionary<string, MemberInfo> dictionary = new Dictionary<string, MemberInfo>(StringComparer.Ordinal); var members = typeInfo .GetMembers() .Where(IsValidMemberInfo) .ToList(); foreach (var member in members) { InternalSDKUtils.AddToDictionary(dictionary, member.Name, member); } return dictionary; } // constructor public StorageConfig(ITypeInfo targetTypeInfo) { var type = targetTypeInfo.Type; if (!Utils.CanInstantiate(type)) throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Type {0} is unsupported, it cannot be instantiated", targetTypeInfo.FullName)); TargetTypeInfo = targetTypeInfo; Properties = new List<PropertyStorage>(); PropertyToPropertyStorageMapping = new Dictionary<string, PropertyStorage>(StringComparer.Ordinal); TargetTypeMembers = GetMembersDictionary(targetTypeInfo); if (TargetTypeMembers.Count == 0) throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Type {0} is unsupported, it has no supported members", targetTypeInfo.FullName)); } } /// <summary> /// Storage information for a specific class that is associated with a table /// </summary> internal class ItemStorageConfig : StorageConfig { // table public string TableName { get; set; } public bool LowerCamelCaseProperties { get; set; } // keys public List<string> HashKeyPropertyNames { get; private set; } public List<string> RangeKeyPropertyNames { get; private set; } // properties to get public List<string> AttributesToGet { get; private set; } // version public string VersionPropertyName { get; private set; } public bool HasVersion { get { return !string.IsNullOrEmpty(VersionPropertyName); } } // attribute-to-index mapping public Dictionary<string, List<string>> AttributeToIndexesNameMapping { get; set; } // indexName to LSI range key properties mapping public Dictionary<string, List<string>> IndexNameToLSIRangePropertiesMapping { get; set; } // indexName to GSIConfig mapping public Dictionary<string, GSIConfig> IndexNameToGSIMapping { get; set; } //public void RemovePropertyStorage(string propertyName) //{ // PropertyStorage storage; // if (!TryGetPropertyStorage(propertyName, out storage)) // return; // string attributeName = storage.AttributeName; // // Remove all references // if (storage.IsHashKey) // HashKeyPropertyNames.Remove(propertyName); // if (storage.IsRangeKey) // RangeKeyPropertyNames.Remove(propertyName); // if (storage.IsVersion) // VersionPropertyName = null; // if (storage.IsGSIHashKey) // IndexNameToGSIMapping // AttributesToGet.Remove(attributeName); // PropertyToPropertyStorageMapping.Remove(propertyName); //} public GSIConfig GetGSIConfig(string indexName) { GSIConfig gsiConfig; if (!this.IndexNameToGSIMapping.TryGetValue(indexName, out gsiConfig)) gsiConfig = null; return gsiConfig; } public string GetCorrectHashKeyProperty(DynamoDBFlatConfig currentConfig, string hashKeyProperty) { if (currentConfig.IsIndexOperation) { string indexName = currentConfig.IndexName; GSIConfig gsiConfig = this.GetGSIConfig(indexName); // Use GSI hash key if GSI is found AND GSI hash-key is set if (gsiConfig != null && !string.IsNullOrEmpty(gsiConfig.HashKeyPropertyName)) hashKeyProperty = gsiConfig.HashKeyPropertyName; } return hashKeyProperty; } public string GetRangeKeyByIndex(string indexName) { string rangeKeyPropertyName = null; // test LSI first List<string> rangeProperties; if (IndexNameToLSIRangePropertiesMapping.TryGetValue(indexName, out rangeProperties) && rangeProperties != null && rangeProperties.Count == 1) { rangeKeyPropertyName = rangeProperties[0]; } GSIConfig gsiConfig = GetGSIConfig(indexName); if (gsiConfig != null) { rangeKeyPropertyName = gsiConfig.RangeKeyPropertyName; } if (string.IsNullOrEmpty(rangeKeyPropertyName)) throw new InvalidOperationException("Unable to determine range key from index name"); return rangeKeyPropertyName; } public PropertyStorage VersionPropertyStorage { get { if (!HasVersion) throw new InvalidOperationException("No version field defined for this type"); return GetPropertyStorage(VersionPropertyName); } } public void Denormalize(DynamoDBContext context) { // analyze all PropertyStorage configs and denormalize data into other properties // all data must exist in PropertyStorage objects prior to denormalization foreach (var property in Properties) { // only add non-ignored properties if (property.IsIgnored) continue; property.Validate(context); AddPropertyStorage(property); string propertyName = property.PropertyName; foreach (var index in property.Indexes) { var gsi = index as PropertyStorage.GSI; if (gsi != null) AddGSIConfigs(gsi.IndexNames, propertyName, gsi.IsHashKey); var lsi = index as PropertyStorage.LSI; if (lsi != null) AddLSIConfigs(lsi.IndexNames, propertyName); } } //if (this.HashKeyPropertyNames.Count == 0) // throw new InvalidOperationException("No hash key configured for type " + TargetTypeInfo.FullName); if (this.Properties.Count == 0) throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Type {0} is unsupported, it has no supported members", TargetTypeInfo.FullName)); } private void AddPropertyStorage(PropertyStorage value) { string propertyName = value.PropertyName; string attributeName = value.AttributeName; //PropertyToPropertyStorageMapping[propertyName] = value; AddPropertyStorage(propertyName, value); if (!AttributesToGet.Contains(attributeName)) AttributesToGet.Add(attributeName); if (value.IsLSIRangeKey || value.IsGSIKey) { List<string> indexes; if (!AttributeToIndexesNameMapping.TryGetValue(attributeName, out indexes)) { indexes = new List<string>(); AttributeToIndexesNameMapping[attributeName] = indexes; } foreach (var index in value.IndexNames) { if (!indexes.Contains(index)) indexes.Add(index); } } if (value.IsHashKey) HashKeyPropertyNames.Add(propertyName); if (value.IsRangeKey) RangeKeyPropertyNames.Add(propertyName); if (value.IsVersion) { if (!string.IsNullOrEmpty(VersionPropertyName)) throw new InvalidOperationException("Multiple version properties defined: " + VersionPropertyName + " and " + propertyName); VersionPropertyName = propertyName; } } private void AddLSIConfigs(List<string> lsiIndexNames, string propertyName) { foreach (var index in lsiIndexNames) { List<string> properties; if (!this.IndexNameToLSIRangePropertiesMapping.TryGetValue(index, out properties)) { properties = new List<string>(); this.IndexNameToLSIRangePropertiesMapping[index] = properties; } if (!properties.Contains(propertyName, StringComparer.Ordinal)) properties.Add(propertyName); } } private void AddGSIConfigs(List<string> gsiIndexNames, string propertyName, bool isHashKey) { foreach (var index in gsiIndexNames) { GSIConfig gsiConfig = this.GetGSIConfig(index); if (gsiConfig == null) { gsiConfig = new GSIConfig(index); this.IndexNameToGSIMapping[index] = gsiConfig; } if (isHashKey) gsiConfig.HashKeyPropertyName = propertyName; else gsiConfig.RangeKeyPropertyName = propertyName; } } // constructor public ItemStorageConfig(ITypeInfo targetTypeInfo) : base(targetTypeInfo) { AttributeToIndexesNameMapping = new Dictionary<string, List<string>>(StringComparer.Ordinal); IndexNameToLSIRangePropertiesMapping = new Dictionary<string, List<string>>(StringComparer.Ordinal); IndexNameToGSIMapping = new Dictionary<string, GSIConfig>(StringComparer.Ordinal); AttributesToGet = new List<string>(); HashKeyPropertyNames = new List<string>(); RangeKeyPropertyNames = new List<string>(); } } /// <summary> /// Cache of ItemStorageConfig objects /// </summary> internal class ItemStorageConfigCache { // Cache of ItemStorageConfig objects per table and the // base, table-less ItemStorageConfig private class ConfigTableCache { public Dictionary<string, ItemStorageConfig> Cache { get; private set; } public ItemStorageConfig BaseTypeConfig { get; private set; } public ConfigTableCache(ItemStorageConfig baseTypeConfig) { BaseTypeConfig = baseTypeConfig; BaseTableName = BaseTypeConfig.TableName; Cache = new Dictionary<string, ItemStorageConfig>(StringComparer.Ordinal); } public string BaseTableName { get; private set; } } private Dictionary<Type, ConfigTableCache> Cache; private DynamoDBContext Context; public ItemStorageConfigCache(DynamoDBContext context) { Cache = new Dictionary<Type, ConfigTableCache>(); Context = context; } public ItemStorageConfig GetConfig<T>(DynamoDBFlatConfig flatConfig, bool conversionOnly = false) { Type type = typeof(T); return GetConfig(type, flatConfig, conversionOnly); } public ItemStorageConfig GetConfig(Type type, DynamoDBFlatConfig flatConfig, bool conversionOnly = false) { lock (Cache) { ConfigTableCache tableCache; if (!Cache.TryGetValue(type, out tableCache)) { var baseStorageConfig = CreateStorageConfig(type, actualTableName: null, flatConfig: flatConfig); tableCache = new ConfigTableCache(baseStorageConfig); Cache[type] = tableCache; } // If this type is only used for conversion, do not attempt to populate the config from the table if (conversionOnly) return tableCache.BaseTypeConfig; string actualTableName = DynamoDBContext.GetTableName(tableCache.BaseTableName, flatConfig); ItemStorageConfig config; if (!tableCache.Cache.TryGetValue(actualTableName, out config)) { config = CreateStorageConfig(type, actualTableName, flatConfig); tableCache.Cache[actualTableName] = config; } return config; } } private static string GetAccurateCase(ItemStorageConfig config, string value) { return (config.LowerCamelCaseProperties ? Utils.ToLowerCamelCase(value) : value); } private ItemStorageConfig CreateStorageConfig(Type baseType, string actualTableName, DynamoDBFlatConfig flatConfig) { if (baseType == null) throw new ArgumentNullException("baseType"); ITypeInfo typeInfo = TypeFactory.GetTypeInfo(baseType); ItemStorageConfig config = new ItemStorageConfig(typeInfo); PopulateConfigFromType(config, typeInfo); PopulateConfigFromMappings(config, AWSConfigsDynamoDB.Context.TypeMappings); // populate config from table definition only if actual table name is known if (!string.IsNullOrEmpty(actualTableName)) { Table table; if (Context.TryGetTable(actualTableName, flatConfig, out table)) { PopulateConfigFromTable(config, table); } } config.Denormalize(Context); return config; } private static void PopulateConfigFromType(ItemStorageConfig config, ITypeInfo typeInfo) { DynamoDBTableAttribute tableAttribute = Utils.GetTableAttribute(typeInfo); if (tableAttribute == null) { config.TableName = typeInfo.Name; } else { if (string.IsNullOrEmpty(tableAttribute.TableName)) throw new InvalidOperationException("DynamoDBTableAttribute.Table is empty or null"); config.TableName = tableAttribute.TableName; config.LowerCamelCaseProperties = tableAttribute.LowerCamelCaseProperties; } string tableAlias; if (AWSConfigsDynamoDB.Context.TableAliases.TryGetValue(config.TableName, out tableAlias)) config.TableName = tableAlias; foreach (var member in typeInfo.GetMembers()) { if (!StorageConfig.IsValidMemberInfo(member)) continue; // prepare basic info PropertyStorage propertyStorage = new PropertyStorage(member); propertyStorage.AttributeName = GetAccurateCase(config, member.Name); // run through all DDB attributes List<DynamoDBAttribute> allAttributes = Utils.GetAttributes(member); foreach (var attribute in allAttributes) { // filter out ignored properties if (attribute is DynamoDBIgnoreAttribute) propertyStorage.IsIgnored = true; if (attribute is DynamoDBVersionAttribute) propertyStorage.IsVersion = true; DynamoDBPropertyAttribute propertyAttribute = attribute as DynamoDBPropertyAttribute; if (propertyAttribute != null) { if (!string.IsNullOrEmpty(propertyAttribute.AttributeName)) propertyStorage.AttributeName = GetAccurateCase(config, propertyAttribute.AttributeName); if (propertyAttribute.Converter != null) propertyStorage.ConverterType = propertyAttribute.Converter; if (propertyAttribute is DynamoDBHashKeyAttribute) { var gsiHashAttribute = propertyAttribute as DynamoDBGlobalSecondaryIndexHashKeyAttribute; if (gsiHashAttribute != null) { propertyStorage.IsGSIHashKey = true; propertyStorage.AddIndex(gsiHashAttribute); } else propertyStorage.IsHashKey = true; } if (propertyAttribute is DynamoDBRangeKeyAttribute) { var gsiRangeAttribute = propertyAttribute as DynamoDBGlobalSecondaryIndexRangeKeyAttribute; if (gsiRangeAttribute != null) { propertyStorage.IsGSIRangeKey = true; propertyStorage.AddIndex(gsiRangeAttribute); } else propertyStorage.IsRangeKey = true; } DynamoDBLocalSecondaryIndexRangeKeyAttribute lsiRangeKeyAttribute = propertyAttribute as DynamoDBLocalSecondaryIndexRangeKeyAttribute; if (lsiRangeKeyAttribute != null) { propertyStorage.IsLSIRangeKey = true; propertyStorage.AddIndex(lsiRangeKeyAttribute); } } } config.Properties.Add(propertyStorage); } } private static void PopulateConfigFromTable(ItemStorageConfig config, Table table) { PropertyStorage property; // keys foreach(var key in table.Keys) { var attributeName = key.Key; var keyDescription = key.Value; property = GetProperty(config, attributeName, false); // validate against table if (property.IsKey) ValidateProperty(property.IsHashKey == keyDescription.IsHash, property.PropertyName, "Property key definition must match table key definition"); // populate property if (keyDescription.IsHash) property.IsHashKey = true; else property.IsRangeKey = true; } foreach (var kvp in table.GlobalSecondaryIndexes) { string indexName = kvp.Key; var gsi = kvp.Value; foreach (var element in gsi.KeySchema) { string attributeName = element.AttributeName; bool isHashKey = element.KeyType == KeyType.HASH; property = GetProperty(config, attributeName, true); if (property != null) { property.AddGsiIndex(isHashKey, attributeName, indexName); } } } foreach (var kvp in table.LocalSecondaryIndexes) { string indexName = kvp.Key; var lsi = kvp.Value; foreach (var element in lsi.KeySchema) { string attributeName = element.AttributeName; bool isHashKey = element.KeyType == KeyType.HASH; // only add for range keys if (!isHashKey) { property = GetProperty(config, attributeName, true); if (property != null) { property.AddLsiIndex(attributeName, indexName); } } } } } private static void PopulateConfigFromMappings(ItemStorageConfig config, Dictionary<Type, TypeMapping> typeMappings) { var baseType = config.TargetTypeInfo.Type; TypeMapping typeMapping; if (typeMappings.TryGetValue(baseType, out typeMapping)) { config.TableName = typeMapping.TargetTable; foreach (var kvp in typeMapping.PropertyConfigs) { PropertyConfig propertyConfig = kvp.Value; string propertyName = propertyConfig.Name; PropertyStorage propertyStorage; if (!config.FindPropertyByPropertyName(propertyName, out propertyStorage)) throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "No matching property {0} on type {1}", propertyName, baseType.FullName)); if (!string.IsNullOrEmpty(propertyConfig.Attribute)) propertyStorage.AttributeName = propertyConfig.Attribute; if (propertyConfig.Converter != null) propertyStorage.ConverterType = propertyConfig.Converter; propertyStorage.IsIgnored = propertyConfig.Ignore; propertyStorage.IsVersion = propertyConfig.Version; } } } // Finds an existing PropertyStorage for a property by its attributeName, // or creates a new PropertyStorage and adds it to the config. // If a property is non-optional and is not present on the type, throws an exception. // If a property is optional and not present on the type, returns null. private static PropertyStorage GetProperty(ItemStorageConfig config, string attributeName, bool optional) { PropertyStorage property = null; bool exists = config.FindSinglePropertyByAttributeName(attributeName, out property); if (!exists) { // property storage doesn't exist yet, create and populate MemberInfo member; // for optional properties/attributes, a null MemberInfo is OK Validate(config.TargetTypeMembers.TryGetValue(attributeName, out member) || optional, "Unable to locate property for key attribute {0}", attributeName); if (member != null) { property = new PropertyStorage(member); property.AttributeName = attributeName; config.Properties.Add(property); } } return property; } private static void Validate(bool value, string messageFormat, params object[] args) { if (!value) { StringBuilder sb = new StringBuilder(); sb.AppendFormat(CultureInfo.InvariantCulture, messageFormat, args); throw new InvalidOperationException(sb.ToString()); } } private static void ValidateProperty(bool value, string propertyName, string messageFormat, params object[] args) { if (!value) { StringBuilder sb = new StringBuilder(); sb.AppendFormat(CultureInfo.InvariantCulture, "Error with property [{0}]: ", propertyName); sb.AppendFormat(CultureInfo.InvariantCulture, messageFormat, args); throw new InvalidOperationException(sb.ToString()); } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Windows.Markup.Localizer.BamlLocalizationDictionary.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Windows.Markup.Localizer { sealed public partial class BamlLocalizationDictionary : System.Collections.IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { #region Methods and constructors public void Add(BamlLocalizableResourceKey key, BamlLocalizableResource value) { } public BamlLocalizationDictionary() { } public void Clear() { } public bool Contains(BamlLocalizableResourceKey key) { return default(bool); } public void CopyTo(System.Collections.DictionaryEntry[] array, int arrayIndex) { Contract.Requires(array != null); Contract.Ensures((Contract.OldValue(arrayIndex) - array.Length) < 0); Contract.Ensures((this.Count - array.Length) <= 0); Contract.Ensures(0 <= this.Count); } public BamlLocalizationDictionaryEnumerator GetEnumerator() { Contract.Ensures(Contract.Result<System.Windows.Markup.Localizer.BamlLocalizationDictionaryEnumerator>() != null); return default(BamlLocalizationDictionaryEnumerator); } public void Remove(BamlLocalizableResourceKey key) { } void System.Collections.ICollection.CopyTo(Array array, int index) { } void System.Collections.IDictionary.Add(Object key, Object value) { } bool System.Collections.IDictionary.Contains(Object key) { return default(bool); } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); } void System.Collections.IDictionary.Remove(Object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); } #endregion #region Properties and indexers public int Count { get { Contract.Ensures(0 <= Contract.Result<int>()); return default(int); } } public bool IsFixedSize { get { return default(bool); } } public bool IsReadOnly { get { return default(bool); } } public BamlLocalizableResource this [BamlLocalizableResourceKey key] { get { return default(BamlLocalizableResource); } set { } } public System.Collections.ICollection Keys { get { return default(System.Collections.ICollection); } } public BamlLocalizableResourceKey RootElementKey { get { return default(BamlLocalizableResourceKey); } } int System.Collections.ICollection.Count { get { return default(int); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } Object System.Collections.ICollection.SyncRoot { get { return default(Object); } } Object System.Collections.IDictionary.this [Object key] { get { return default(Object); } set { } } public System.Collections.ICollection Values { get { return default(System.Collections.ICollection); } } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Microsoft.OData.Client; namespace Microsoft.OData.ProxyExtensions { public abstract class ReadOnlyQueryableSetBase { private DataServiceQuery _inner; private DataServiceContextWrapper _context; // Will return null if not an interface protected static Type CreateConcreteType(Type tsourceType) { var tsourceTypeInfo = tsourceType.GetTypeInfo(); if (tsourceTypeInfo.IsGenericType) { var arguments = tsourceTypeInfo.GenericTypeArguments; bool modified = false; for (int i = 0; i < arguments.Length; i++) { var converted = CreateConcreteType(arguments[i]); if (converted != null) { arguments[i] = converted; modified = true; } } if (!modified) { return null; } // Properties declared as IPagedCollection on the interface are declared as IList on the concrete type if (tsourceTypeInfo.GetGenericTypeDefinition() == typeof(IPagedCollection<>)) { return typeof(IList<>).MakeGenericType(arguments); } return tsourceTypeInfo.GetGenericTypeDefinition().MakeGenericType(arguments); } const string fetcher = "Fetcher"; if (tsourceTypeInfo.CustomAttributes.Any(i => i.AttributeType == typeof(LowerCasePropertyAttribute))) { string typeName = tsourceTypeInfo.Namespace + "." + tsourceTypeInfo.Name.Substring(1); if (typeName.EndsWith(fetcher)) { typeName = typeName.Substring(typeName.Length - fetcher.Length); } return tsourceTypeInfo.Assembly.GetType(typeName); } return null; } public DataServiceContextWrapper Context { get { return _context; } } public DataServiceQuery Query { get { return _inner; } } protected void Initialize(DataServiceQuery inner, DataServiceContextWrapper context) { _inner = inner; _context = context; } } public abstract class ReadOnlyQueryableSetBase<TSource> : ReadOnlyQueryableSetBase, IReadOnlyQueryableSetBase<TSource>, IConcreteTypeAccessor { private readonly Lazy<Type> _concreteType = new Lazy<Type>(() => CreateConcreteType(typeof(TSource)), true); protected ReadOnlyQueryableSetBase( DataServiceQuery inner, DataServiceContextWrapper context) { Initialize(inner, context); } #region IConcreteTypeAccessor implementation Type IConcreteTypeAccessor.ConcreteType { get { return _concreteType.Value ?? typeof(TSource); } } Type IConcreteTypeAccessor.ElementType { get { return typeof(TSource); } } #endregion protected Task<IPagedCollection<TSource>> ExecuteAsyncInternal() { if (_concreteType.Value != null) { var contextTypeInfo = typeof(DataServiceContextWrapper).GetTypeInfo(); var executeAsyncMethodInfo = (from i in contextTypeInfo.GetDeclaredMethods("ExecuteAsync") let parameters = i.GetParameters() where parameters.Length == 1 && parameters[0].ParameterType.GetGenericTypeDefinition() == typeof(DataServiceQuery<>) select i).First(); return (Task<IPagedCollection<TSource>>)executeAsyncMethodInfo.MakeGenericMethod(_concreteType.Value, typeof(TSource)).Invoke(Context, new object[] { Query }); } return Context.ExecuteAsync<TSource, TSource>((DataServiceQuery<TSource>)Query); } protected Task<TSource> ExecuteSingleAsyncInternal() { if (_concreteType.Value != null) { var contextTypeInfo = typeof(DataServiceContextWrapper).GetTypeInfo(); var executeAsyncMethodInfo = (from i in contextTypeInfo.GetDeclaredMethods("ExecuteSingleAsync") let parameters = i.GetParameters() where parameters.Length == 1 && parameters[0].ParameterType.GetGenericTypeDefinition() == typeof(DataServiceQuery<>) select i).First(); return (Task<TSource>)executeAsyncMethodInfo.MakeGenericMethod(_concreteType.Value, typeof(TSource)).Invoke(Context, new object[] { Query }); } return Context.ExecuteSingleAsync<TSource, TSource>((DataServiceQuery<TSource>)Query); } #region LINQ private class PascalCaseExpressionVisitor : ExpressionVisitor { private readonly Dictionary<ParameterExpression, ParameterExpression> _parameterDictionary = new Dictionary<ParameterExpression, ParameterExpression>(); protected override Expression VisitExtension(Expression node) { return node; } protected override Expression VisitLambda<T>(Expression<T> node) { var originalDelegateType = typeof(T); if (originalDelegateType.GetGenericTypeDefinition() == typeof(Func<,>)) { var newParameterArray = originalDelegateType.GetTypeInfo().GenericTypeArguments; bool hasInterfaces = false; var ct = CreateConcreteType(newParameterArray[0]); if (ct != null) { hasInterfaces = true; newParameterArray[0] = ct; } ct = CreateConcreteType(newParameterArray[1]); if (ct != null) { hasInterfaces = true; newParameterArray[1] = ct; } if (!hasInterfaces) { return base.VisitLambda(node); } var newdDelegateType = typeof(Func<,>).MakeGenericType(newParameterArray); var invocationParameters = node.Parameters.ToArray(); for (int i = 0; i < invocationParameters.Length; i++) { var concreteType = CreateConcreteType(invocationParameters[i].Type); if (concreteType != null) { if (!_parameterDictionary.ContainsKey(invocationParameters[i])) { _parameterDictionary[invocationParameters[i]] = Expression.Parameter( concreteType, invocationParameters[i].Name); } invocationParameters[i] = _parameterDictionary[invocationParameters[i]]; } } var body = Visit(node.Body); var newLambda = Expression.Lambda( newdDelegateType, body, node.TailCall, invocationParameters); return newLambda; } return base.VisitLambda(node); } protected override Expression VisitParameter(ParameterExpression node) { var concreteType = CreateConcreteType(node.Type); if (concreteType == null) { return base.VisitParameter(node); } if (!_parameterDictionary.ContainsKey(node)) { _parameterDictionary[node] = Expression.Parameter( concreteType, node.Name); } return base.VisitParameter(_parameterDictionary[node]); } protected override Expression VisitMember(MemberExpression node) { if (node.Member is PropertyInfo) { var interfaceType = CreateConcreteType(node.Type) != null; var toLower = node.Member.CustomAttributes.Any(i => i.AttributeType == typeof(LowerCasePropertyAttribute)); if (interfaceType || toLower) { var newExpression = Visit(node.Expression); return base.VisitMember(Expression.Property( newExpression, newExpression.Type.GetRuntimeProperty(toLower ? char.ToLower(node.Member.Name[0]) + node.Member.Name.Substring(1) : node.Member.Name) )); } } /* Example - ""me"" is a field: var me = await client.Me.ExecuteAsync(); var filesQuery = await client.Users.Where(i => i.UserPrincipalName != me.UserPrincipalName).ExecuteAsync(); */ else { var fieldInfo = node.Member as FieldInfo; if (fieldInfo != null) // for local variables { var fieldTypeInfo = fieldInfo.FieldType.GetTypeInfo(); if (fieldTypeInfo.CustomAttributes.Any(i => i.AttributeType == typeof(LowerCasePropertyAttribute))) { var expression = Expression.TypeAs(node, CreateConcreteType(fieldTypeInfo.AsType())); return expression; } } } return base.VisitMember(node); } } private readonly ExpressionVisitor _pascalCaseExpressionVisitor = new PascalCaseExpressionVisitor(); public IReadOnlyQueryableSet<TResult> Select<TResult>(Expression<Func<TSource, TResult>> selector) { var newSelector = _pascalCaseExpressionVisitor.Visit(selector); DataServiceQuery query = CallLinqMethod(newSelector); return new ReadOnlyQueryableSet<TResult>( query, Context); } public IReadOnlyQueryableSet<TSource> Where(Expression<Func<TSource, bool>> predicate) { // Fix for DevDiv 941323: if (predicate.Body.NodeType == ExpressionType.Coalesce) { var binary = (BinaryExpression)predicate.Body; var constantRight = binary.Right as ConstantExpression; // If we are coalescing bool to false, it is a no-op if (constantRight != null && constantRight.Value is bool && !(bool)constantRight.Value && binary.Left.Type == typeof(bool?) && binary.Left is BinaryExpression) { var oldLeft = (BinaryExpression)binary.Left; var newLeft = Expression.MakeBinary( oldLeft.NodeType, oldLeft.Left, oldLeft.Right); predicate = (Expression<Func<TSource, bool>>)Expression.Lambda( predicate.Type, newLeft, predicate.TailCall, predicate.Parameters); } } var newSelector = _pascalCaseExpressionVisitor.Visit(predicate); DataServiceQuery query = CallLinqMethod(newSelector, true); return new ReadOnlyQueryableSet<TSource>( query, Context); } public IReadOnlyQueryableSet<TResult> OfType<TResult>() { DataServiceQuery query = ApplyLinq(new[] { typeof(TResult) }, new object[] { Query }) ?? (DataServiceQuery)((IQueryable<TSource>)Query).OfType<TResult>(); return new ReadOnlyQueryableSet<TResult>( query, Context); } public IReadOnlyQueryableSet<TSource> Skip(int count) { DataServiceQuery query = ApplyLinq(new[] { typeof(TSource) }, new object[] { Query, count }) ?? (DataServiceQuery)((IQueryable<TSource>)Query).Skip(count); return new ReadOnlyQueryableSet<TSource>( query, Context); } public IReadOnlyQueryableSet<TSource> Take(int count) { DataServiceQuery query = ApplyLinq(new[] { typeof(TSource) }, new object[] { Query, count }) ?? (DataServiceQuery)((IQueryable<TSource>)Query).Take(count); return new ReadOnlyQueryableSet<TSource>( query, Context); } public IReadOnlyQueryableSet<TSource> OrderBy<TKey>(Expression<Func<TSource, TKey>> keySelector) { var newSelector = _pascalCaseExpressionVisitor.Visit(keySelector); DataServiceQuery query = CallLinqMethod(newSelector); return new ReadOnlyQueryableSet<TSource>( query, Context); } public IReadOnlyQueryableSet<TSource> OrderByDescending<TKey>(Expression<Func<TSource, TKey>> keySelector) { var newSelector = _pascalCaseExpressionVisitor.Visit(keySelector); DataServiceQuery query = CallLinqMethod(newSelector); return new ReadOnlyQueryableSet<TSource>( query, Context); } public IReadOnlyQueryableSet<TSource> Expand<TTarget>(Expression<Func<TSource, TTarget>> navigationPropertyAccessor) { var newSelector = _pascalCaseExpressionVisitor.Visit(navigationPropertyAccessor); var concreteType = _concreteType.Value ?? typeof(TSource); var concreteDsq = typeof(DataServiceQuery<>).MakeGenericType(concreteType); DataServiceQuery query = CallOnConcreteType(concreteDsq, Query, new[] { typeof(TTarget) }, new object[] { newSelector }); return new ReadOnlyQueryableSet<TSource>( query, Context); } public IReadOnlyQueryableSet<TSource> Expand(string expansion) { var concreteType = _concreteType.Value ?? typeof(TSource); var concreteDsq = typeof(DataServiceQuery<>).MakeGenericType(concreteType); DataServiceQuery query = CallOnConcreteType(concreteDsq, Query, new object[] { expansion }); return new ReadOnlyQueryableSet<TSource>( query, Context); } private DataServiceQuery ApplyLinq(Type[] typeParams, object[] callParams, [CallerMemberName] string methodName = null) { return CallOnConcreteType(typeof (Queryable), null, typeParams, callParams, methodName); } private DataServiceQuery CallOnConcreteType(Type targetType, object instance, Type[] typeParams, object[] callParams, [CallerMemberName] string methodName = null) { for (int i = 0; i < typeParams.Length; i++) { if (typeParams[i] == typeof(TSource)) { typeParams[i] = _concreteType.Value; } else { var concreteType = CreateConcreteType(typeParams[i]); if (concreteType != null) { typeParams[i] = concreteType; } } } var typeInfo = targetType.GetTypeInfo(); var methodInfo = (from i in typeInfo.GetDeclaredMethods(methodName) let parameters = i.GetParameters() where i.GetGenericArguments().Length == typeParams.Length let constructedMethod = i.MakeGenericMethod(typeParams) where AllParametersAreAssignable(constructedMethod.GetParameters(), callParams) select constructedMethod).First(); return (DataServiceQuery)methodInfo.Invoke(instance, callParams); } private DataServiceQuery CallOnConcreteType(Type targetType, object instance, object[] callParams, [CallerMemberName] string methodName = null) { var typeInfo = targetType.GetTypeInfo(); var methodInfo = (from i in typeInfo.GetDeclaredMethods(methodName) where AllParametersAreAssignable(i.GetParameters(), callParams) select i).First(); return (DataServiceQuery)methodInfo.Invoke(instance, callParams); } private bool AllParametersAreAssignable(IEnumerable<ParameterInfo> parameterInfo, object[] callParams) { return !parameterInfo.Where((t, i) => callParams[i] != null && !t.ParameterType.GetTypeInfo().IsAssignableFrom(callParams[i].GetType().GetTypeInfo())).Any(); } private DataServiceQuery CallLinqMethod(Expression predicate, bool singleGenericParameter = false, [CallerMemberName] string methodName = null) { var typeParams = singleGenericParameter ? new[] { predicate.Type.GenericTypeArguments[0] } : predicate.Type.GenericTypeArguments; var callParams = new object[] { Query, predicate }; var typeInfo = typeof(Queryable).GetTypeInfo(); var methodInfo = (from i in typeInfo.GetDeclaredMethods(methodName) let parameters = i.GetParameters() where i.GetGenericArguments().Length == typeParams.Length let constructedMethod = i.MakeGenericMethod(typeParams) where AllParametersAreAssignable(constructedMethod.GetParameters(), callParams) select constructedMethod).First(); return (DataServiceQuery)methodInfo.Invoke(null, callParams); } #endregion } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using PushSharp.Web.Areas.HelpPage.Models; namespace PushSharp.Web.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.ResourceManager.V3.Snippets { using Google.Api.Gax; using Google.LongRunning; using Google.Protobuf.WellKnownTypes; using System; using System.Linq; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedTagBindingsClientSnippets { /// <summary>Snippet for ListTagBindings</summary> public void ListTagBindingsRequestObject() { // Snippet: ListTagBindings(ListTagBindingsRequest, CallSettings) // Create client TagBindingsClient tagBindingsClient = TagBindingsClient.Create(); // Initialize request argument(s) ListTagBindingsRequest request = new ListTagBindingsRequest { ParentAsResourceName = new UnparsedResourceName("a/wildcard/resource"), }; // Make the request PagedEnumerable<ListTagBindingsResponse, TagBinding> response = tagBindingsClient.ListTagBindings(request); // Iterate over all response items, lazily performing RPCs as required foreach (TagBinding item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListTagBindingsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TagBinding item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TagBinding> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TagBinding item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTagBindingsAsync</summary> public async Task ListTagBindingsRequestObjectAsync() { // Snippet: ListTagBindingsAsync(ListTagBindingsRequest, CallSettings) // Create client TagBindingsClient tagBindingsClient = await TagBindingsClient.CreateAsync(); // Initialize request argument(s) ListTagBindingsRequest request = new ListTagBindingsRequest { ParentAsResourceName = new UnparsedResourceName("a/wildcard/resource"), }; // Make the request PagedAsyncEnumerable<ListTagBindingsResponse, TagBinding> response = tagBindingsClient.ListTagBindingsAsync(request); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((TagBinding item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListTagBindingsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TagBinding item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TagBinding> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TagBinding item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTagBindings</summary> public void ListTagBindings() { // Snippet: ListTagBindings(string, string, int?, CallSettings) // Create client TagBindingsClient tagBindingsClient = TagBindingsClient.Create(); // Initialize request argument(s) string parent = "a/wildcard/resource"; // Make the request PagedEnumerable<ListTagBindingsResponse, TagBinding> response = tagBindingsClient.ListTagBindings(parent); // Iterate over all response items, lazily performing RPCs as required foreach (TagBinding item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListTagBindingsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TagBinding item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TagBinding> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TagBinding item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTagBindingsAsync</summary> public async Task ListTagBindingsAsync() { // Snippet: ListTagBindingsAsync(string, string, int?, CallSettings) // Create client TagBindingsClient tagBindingsClient = await TagBindingsClient.CreateAsync(); // Initialize request argument(s) string parent = "a/wildcard/resource"; // Make the request PagedAsyncEnumerable<ListTagBindingsResponse, TagBinding> response = tagBindingsClient.ListTagBindingsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((TagBinding item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListTagBindingsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TagBinding item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TagBinding> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TagBinding item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTagBindings</summary> public void ListTagBindingsResourceNames() { // Snippet: ListTagBindings(IResourceName, string, int?, CallSettings) // Create client TagBindingsClient tagBindingsClient = TagBindingsClient.Create(); // Initialize request argument(s) IResourceName parent = new UnparsedResourceName("a/wildcard/resource"); // Make the request PagedEnumerable<ListTagBindingsResponse, TagBinding> response = tagBindingsClient.ListTagBindings(parent); // Iterate over all response items, lazily performing RPCs as required foreach (TagBinding item in response) { // Do something with each item Console.WriteLine(item); } // Or iterate over pages (of server-defined size), performing one RPC per page foreach (ListTagBindingsResponse page in response.AsRawResponses()) { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TagBinding item in page) { // Do something with each item Console.WriteLine(item); } } // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TagBinding> singlePage = response.ReadPage(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TagBinding item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for ListTagBindingsAsync</summary> public async Task ListTagBindingsResourceNamesAsync() { // Snippet: ListTagBindingsAsync(IResourceName, string, int?, CallSettings) // Create client TagBindingsClient tagBindingsClient = await TagBindingsClient.CreateAsync(); // Initialize request argument(s) IResourceName parent = new UnparsedResourceName("a/wildcard/resource"); // Make the request PagedAsyncEnumerable<ListTagBindingsResponse, TagBinding> response = tagBindingsClient.ListTagBindingsAsync(parent); // Iterate over all response items, lazily performing RPCs as required await response.ForEachAsync((TagBinding item) => { // Do something with each item Console.WriteLine(item); }); // Or iterate over pages (of server-defined size), performing one RPC per page await response.AsRawResponses().ForEachAsync((ListTagBindingsResponse page) => { // Do something with each page of items Console.WriteLine("A page of results:"); foreach (TagBinding item in page) { // Do something with each item Console.WriteLine(item); } }); // Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required int pageSize = 10; Page<TagBinding> singlePage = await response.ReadPageAsync(pageSize); // Do something with the page of items Console.WriteLine($"A page of {pageSize} results (unless it's the final page):"); foreach (TagBinding item in singlePage) { // Do something with each item Console.WriteLine(item); } // Store the pageToken, for when the next page is required. string nextPageToken = singlePage.NextPageToken; // End snippet } /// <summary>Snippet for CreateTagBinding</summary> public void CreateTagBindingRequestObject() { // Snippet: CreateTagBinding(CreateTagBindingRequest, CallSettings) // Create client TagBindingsClient tagBindingsClient = TagBindingsClient.Create(); // Initialize request argument(s) CreateTagBindingRequest request = new CreateTagBindingRequest { TagBinding = new TagBinding(), ValidateOnly = false, }; // Make the request Operation<TagBinding, CreateTagBindingMetadata> response = tagBindingsClient.CreateTagBinding(request); // Poll until the returned long-running operation is complete Operation<TagBinding, CreateTagBindingMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result TagBinding result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<TagBinding, CreateTagBindingMetadata> retrievedResponse = tagBindingsClient.PollOnceCreateTagBinding(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result TagBinding retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateTagBindingAsync</summary> public async Task CreateTagBindingRequestObjectAsync() { // Snippet: CreateTagBindingAsync(CreateTagBindingRequest, CallSettings) // Additional: CreateTagBindingAsync(CreateTagBindingRequest, CancellationToken) // Create client TagBindingsClient tagBindingsClient = await TagBindingsClient.CreateAsync(); // Initialize request argument(s) CreateTagBindingRequest request = new CreateTagBindingRequest { TagBinding = new TagBinding(), ValidateOnly = false, }; // Make the request Operation<TagBinding, CreateTagBindingMetadata> response = await tagBindingsClient.CreateTagBindingAsync(request); // Poll until the returned long-running operation is complete Operation<TagBinding, CreateTagBindingMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result TagBinding result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<TagBinding, CreateTagBindingMetadata> retrievedResponse = await tagBindingsClient.PollOnceCreateTagBindingAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result TagBinding retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateTagBinding</summary> public void CreateTagBinding() { // Snippet: CreateTagBinding(TagBinding, CallSettings) // Create client TagBindingsClient tagBindingsClient = TagBindingsClient.Create(); // Initialize request argument(s) TagBinding tagBinding = new TagBinding(); // Make the request Operation<TagBinding, CreateTagBindingMetadata> response = tagBindingsClient.CreateTagBinding(tagBinding); // Poll until the returned long-running operation is complete Operation<TagBinding, CreateTagBindingMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result TagBinding result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<TagBinding, CreateTagBindingMetadata> retrievedResponse = tagBindingsClient.PollOnceCreateTagBinding(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result TagBinding retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for CreateTagBindingAsync</summary> public async Task CreateTagBindingAsync() { // Snippet: CreateTagBindingAsync(TagBinding, CallSettings) // Additional: CreateTagBindingAsync(TagBinding, CancellationToken) // Create client TagBindingsClient tagBindingsClient = await TagBindingsClient.CreateAsync(); // Initialize request argument(s) TagBinding tagBinding = new TagBinding(); // Make the request Operation<TagBinding, CreateTagBindingMetadata> response = await tagBindingsClient.CreateTagBindingAsync(tagBinding); // Poll until the returned long-running operation is complete Operation<TagBinding, CreateTagBindingMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result TagBinding result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<TagBinding, CreateTagBindingMetadata> retrievedResponse = await tagBindingsClient.PollOnceCreateTagBindingAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result TagBinding retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteTagBinding</summary> public void DeleteTagBindingRequestObject() { // Snippet: DeleteTagBinding(DeleteTagBindingRequest, CallSettings) // Create client TagBindingsClient tagBindingsClient = TagBindingsClient.Create(); // Initialize request argument(s) DeleteTagBindingRequest request = new DeleteTagBindingRequest { TagBindingName = TagBindingName.FromTagBinding("[TAG_BINDING]"), }; // Make the request Operation<Empty, DeleteTagBindingMetadata> response = tagBindingsClient.DeleteTagBinding(request); // Poll until the returned long-running operation is complete Operation<Empty, DeleteTagBindingMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteTagBindingMetadata> retrievedResponse = tagBindingsClient.PollOnceDeleteTagBinding(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteTagBindingAsync</summary> public async Task DeleteTagBindingRequestObjectAsync() { // Snippet: DeleteTagBindingAsync(DeleteTagBindingRequest, CallSettings) // Additional: DeleteTagBindingAsync(DeleteTagBindingRequest, CancellationToken) // Create client TagBindingsClient tagBindingsClient = await TagBindingsClient.CreateAsync(); // Initialize request argument(s) DeleteTagBindingRequest request = new DeleteTagBindingRequest { TagBindingName = TagBindingName.FromTagBinding("[TAG_BINDING]"), }; // Make the request Operation<Empty, DeleteTagBindingMetadata> response = await tagBindingsClient.DeleteTagBindingAsync(request); // Poll until the returned long-running operation is complete Operation<Empty, DeleteTagBindingMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteTagBindingMetadata> retrievedResponse = await tagBindingsClient.PollOnceDeleteTagBindingAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteTagBinding</summary> public void DeleteTagBinding() { // Snippet: DeleteTagBinding(string, CallSettings) // Create client TagBindingsClient tagBindingsClient = TagBindingsClient.Create(); // Initialize request argument(s) string name = "tagBindings/[TAG_BINDING]"; // Make the request Operation<Empty, DeleteTagBindingMetadata> response = tagBindingsClient.DeleteTagBinding(name); // Poll until the returned long-running operation is complete Operation<Empty, DeleteTagBindingMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteTagBindingMetadata> retrievedResponse = tagBindingsClient.PollOnceDeleteTagBinding(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteTagBindingAsync</summary> public async Task DeleteTagBindingAsync() { // Snippet: DeleteTagBindingAsync(string, CallSettings) // Additional: DeleteTagBindingAsync(string, CancellationToken) // Create client TagBindingsClient tagBindingsClient = await TagBindingsClient.CreateAsync(); // Initialize request argument(s) string name = "tagBindings/[TAG_BINDING]"; // Make the request Operation<Empty, DeleteTagBindingMetadata> response = await tagBindingsClient.DeleteTagBindingAsync(name); // Poll until the returned long-running operation is complete Operation<Empty, DeleteTagBindingMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteTagBindingMetadata> retrievedResponse = await tagBindingsClient.PollOnceDeleteTagBindingAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteTagBinding</summary> public void DeleteTagBindingResourceNames() { // Snippet: DeleteTagBinding(TagBindingName, CallSettings) // Create client TagBindingsClient tagBindingsClient = TagBindingsClient.Create(); // Initialize request argument(s) TagBindingName name = TagBindingName.FromTagBinding("[TAG_BINDING]"); // Make the request Operation<Empty, DeleteTagBindingMetadata> response = tagBindingsClient.DeleteTagBinding(name); // Poll until the returned long-running operation is complete Operation<Empty, DeleteTagBindingMetadata> completedResponse = response.PollUntilCompleted(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteTagBindingMetadata> retrievedResponse = tagBindingsClient.PollOnceDeleteTagBinding(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } /// <summary>Snippet for DeleteTagBindingAsync</summary> public async Task DeleteTagBindingResourceNamesAsync() { // Snippet: DeleteTagBindingAsync(TagBindingName, CallSettings) // Additional: DeleteTagBindingAsync(TagBindingName, CancellationToken) // Create client TagBindingsClient tagBindingsClient = await TagBindingsClient.CreateAsync(); // Initialize request argument(s) TagBindingName name = TagBindingName.FromTagBinding("[TAG_BINDING]"); // Make the request Operation<Empty, DeleteTagBindingMetadata> response = await tagBindingsClient.DeleteTagBindingAsync(name); // Poll until the returned long-running operation is complete Operation<Empty, DeleteTagBindingMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Empty result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Empty, DeleteTagBindingMetadata> retrievedResponse = await tagBindingsClient.PollOnceDeleteTagBindingAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Empty retrievedResult = retrievedResponse.Result; } // End snippet } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Runtime.InteropServices; using System.Text; namespace QText { internal static class Helper { #region Encode/decode file name private static readonly char[] InvalidTitleChars = new char[] { '\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B', '\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018', '\u0019', '\u001A', '\u001B', '\u001C', '\u001D', '\u001E', '\u001F', '\u0022', '\u002a', '\u002f', '\u003a', '\u003c', '\u003e', '\u003f', '\u005c', '\u007c' }; // " * / : < > ? \ | public static string EncodeFileTitle(string title) { return EncodeTitle(title, isFolder: false); } public static string EncodeFolderTitle(string title) { return EncodeTitle(title, isFolder: true); } private static string EncodeTitle(string title, bool isFolder) { var sb = new StringBuilder(); foreach (var ch in title) { if (Array.IndexOf(InvalidTitleChars, ch) >= 0) { sb.Append("~"); sb.Append(((byte)ch).ToString("x2")); sb.Append("~"); } else { sb.Append(ch); } } var lastChar = (sb.Length > 0) ? sb[sb.Length - 1] : default(char?); if (isFolder && ((lastChar == '.') || (lastChar == ' '))) { //special handling for folders ending in dot sb.Remove(sb.Length - 1, 1); sb.Append("~"); sb.Append(((byte)lastChar.Value).ToString("x2")); sb.Append("~"); } var firstChar = (sb.Length > 0) ? sb[0] : default(char?); if (firstChar == ' ') { sb.Remove(0, 1); sb.Insert(0, "~" + ((byte)firstChar.Value).ToString("x2") + "~"); } return sb.ToString(); } public static string DecodeFileTitle(string name) { return DecodeTitle(name); } public static string DecodeFolderTitle(string name) { return DecodeTitle(name); } private static string DecodeTitle(string name) { var sb = new StringBuilder(); StringBuilder sbDecode = null; var inEncoded = false; foreach (var ch in name) { if (inEncoded) { if (ch == '~') { //end decode if (sbDecode.Length == 2) { //could be if (int.TryParse(sbDecode.ToString(), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var value)) { var charValue = Convert.ToChar(value); if ((Array.IndexOf(InvalidTitleChars, charValue) >= 0) || (charValue == '.') || (charValue == ' ')) { sb.Append(charValue); inEncoded = false; } else { //not a char to be decoded sb.Append("~"); sb.Append(sbDecode); sbDecode.Length = 0; } } else { //cannot decode sb.Append("~"); sb.Append(sbDecode); sbDecode.Length = 0; } } else { sb.Append("~"); sb.Append(sbDecode); sbDecode.Length = 0; } } else { sbDecode.Append(ch); if (sbDecode.Length > 2) { sb.Append("~"); sb.Append(sbDecode); inEncoded = false; } } } else { if (ch == '~') { //start decode if (sbDecode == null) { sbDecode = new StringBuilder(); } else { sbDecode.Length = 0; } inEncoded = true; } else { sb.Append(ch); } } } if (inEncoded) { sb.Append("~"); sb.Append(sbDecode); } return sb.ToString(); } public static void CreatePath(string path) { if ((!Directory.Exists(path))) { var currPath = path; var allPaths = new List<string>(); while (!(Directory.Exists(currPath))) { allPaths.Add(currPath); currPath = System.IO.Path.GetDirectoryName(currPath); if (string.IsNullOrEmpty(currPath)) { throw new IOException("Path \"" + path + "\" can not be created."); } } try { for (var i = allPaths.Count - 1; i >= 0; i += -1) { System.IO.Directory.CreateDirectory(allPaths[i]); } } catch (Exception) { throw new System.IO.IOException("Path \"" + path + "\" can not be created."); } } } #endregion public static void MovePath(string currentPath, string newPath) { if (!currentPath.StartsWith(@"\\", StringComparison.Ordinal)) { currentPath = @"\\?\" + currentPath; } if (!newPath.StartsWith(@"\\", StringComparison.Ordinal)) { newPath = @"\\?\" + newPath; } if (NativeMethods.MoveFileExW(currentPath, newPath, NativeMethods.MOVEFILE_COPY_ALLOWED | NativeMethods.MOVEFILE_WRITE_THROUGH) == false) { var ex = new Win32Exception(); throw new IOException(ex.Message, ex); } } internal static class NativeMethods { public const uint MOVEFILE_COPY_ALLOWED = 0x02; public const uint MOVEFILE_WRITE_THROUGH = 0x08; [DllImportAttribute("kernel32.dll", EntryPoint = "MoveFileExW", SetLastError = true)] [return: MarshalAsAttribute(UnmanagedType.Bool)] public static extern bool MoveFileExW([InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string lpExistingFileName, [InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string lpNewFileName, uint dwFlags); } public static string GetFileNameWithoutExtension(string path) { var name = Path.GetFileName(path); foreach (var extension in GetExtensions()) { if (name.EndsWith(extension, StringComparison.OrdinalIgnoreCase)) { return name.Substring(0, name.Length - extension.Length); } } throw new InvalidOperationException("Unexpected data type for file \"" + path + "\""); } #region Extensions internal static IEnumerable<string> GetExtensions() { yield return Extensions.Plain; yield return Extensions.Rich; yield return Extensions.PlainEncrypted; yield return Extensions.RichEncrypted; } internal static class Extensions { public static readonly string Plain = ".txt"; public static readonly string Rich = ".rtf"; public static readonly string PlainEncrypted = ".txt.aes256cbc"; public static readonly string RichEncrypted = ".rtf.aes256cbc"; } #endregion internal class FileSystemToggler : IDisposable { public FileSystemToggler(FileSystemWatcher watcher) { Watcher = watcher; WasEnabled = watcher.EnableRaisingEvents; Watcher.EnableRaisingEvents = false; } private readonly FileSystemWatcher Watcher; private readonly bool WasEnabled; void IDisposable.Dispose() { Watcher.EnableRaisingEvents = WasEnabled; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using TestSupport; namespace TestSupport.Collections { public class IEnumerable_Test { private IEnumerable _collection; protected ModifyUnderlyingCollection _modifyCollection; protected Object[] _items; protected System.Collections.Generic.IEqualityComparer<Object> _comparer; protected VerificationLevel _verificationLevel; protected bool _isGenericCompatibility; protected bool _isResetNotSupported; protected CollectionOrder _collectionOrder; private IEnumerable_Test() { } /// <summary> /// Initializes a new instance of the IEnumerable_Test. /// </summary> /// <param name="collection">The collection to run the tests on.</param> /// <param name="items">The items currently in the collection.</param> public IEnumerable_Test(IEnumerable collection, Object[] items) : this(collection, items, null) { } /// <summary> /// Initializes a new instance of the IEnumerable_Test. /// </summary> /// <param name="collection">The collection to run the tests on.</param> /// <param name="items">The items currently in the collection.</param> /// <param name="modifyCollection">Modifies the collection to invalidate the enumerator.</param> public IEnumerable_Test(IEnumerable collection, Object[] items, ModifyUnderlyingCollection modifyCollection) { _collection = collection; _modifyCollection = modifyCollection; _isGenericCompatibility = false; _isResetNotSupported = false; _verificationLevel = VerificationLevel.Extensive; _collectionOrder = CollectionOrder.Sequential; if (items == null) _items = new Object[0]; else _items = items; _comparer = System.Collections.Generic.EqualityComparer<Object>.Default; } /// <summary> /// Runs all of the IEnumerable tests. /// </summary> /// <returns>true if all of the tests passed else false</returns> public bool RunAllTests() { bool retValue = true; retValue &= MoveNext_Tests(); retValue &= Current_Tests(); retValue &= Reset_Tests(); retValue &= ModifiedCollection_Test(); return retValue; } /// <summary> /// The collection to run the tests on. /// </summary> /// <value>The collection to run the tests on.</value> public IEnumerable Collection { get { return _collection; } set { if (null == value) { throw new ArgumentNullException("value"); } _collection = value; } } /// <summary> /// The items in the Collection /// </summary> /// <value>The items in the Collection</value> public Object[] Items { get { return _items; } set { if (null == value) { throw new ArgumentNullException("value"); } _items = value; } } /// <summary> /// Modifies the collection. If null the test that verify that enumerating a /// collection that has been modified since the enumerator has been created /// will not be run. /// </summary> /// <value>Modifies the collection.</value> public ModifyUnderlyingCollection ModifyCollection { get { return _modifyCollection; } set { _modifyCollection = value; } } /// <summary> /// The IComparer used to compare the items. If null Comparer<Object>.Default will be used. /// </summary> /// <value>The IComparer used to compare the items.</value> public System.Collections.Generic.IEqualityComparer<Object> Comparer { get { return _comparer; } set { if (null == value) _comparer = System.Collections.Generic.EqualityComparer<Object>.Default; else _comparer = value; } } /// <summary> /// If true specifies that IEnumerator.Current has undefined behavior when /// the enumerator is positioned before the first item or after the last item. /// </summary> public bool IsGenericCompatibility { get { return _isGenericCompatibility; } set { _isGenericCompatibility = value; } } /// <summary> /// If true specifes that IEnumerator.Reset is not supported on the /// IEnumerator returned from Collection and will throw NotSupportedException. /// </summary> public bool IsResetNotSupported { get { return _isResetNotSupported; } set { _isResetNotSupported = value; } } /// <summary> /// The Verification level to use. If VerificationLevel is Extensive the collection /// will be verified after argument checking (invalid) tests. /// </summary> /// <value>The Verification level to use.</value> public VerificationLevel VerificationLevel { get { return _verificationLevel; } set { _verificationLevel = value; } } /// <summary> /// This specifies where Add places an item at the beginning of the collection, /// the end of the collection, or unspecified. Items is expected to be in the /// same order as the enumerator unless AddOrder.Unspecified is used. /// </summary> /// <value>This specifies where Add places an item.</value> public CollectionOrder CollectionOrder { get { return _collectionOrder; } set { _collectionOrder = value; } } /// <summary> /// Runs all of the tests on MoveNext(). /// </summary> /// <returns>true if all of the test passed else false.</returns> public bool MoveNext_Tests() { bool retValue = true; int iterations = 0; IEnumerator enumerator = _collection.GetEnumerator(); String testDescription = "No description of test available"; int j; bool scenarioResult; for (int i = 0; i < 3 && retValue; i++) { try { //[] Call MoveNext() until the end of the collection has been reached testDescription = "14328edfae Call MoveNext() until the end of the collection has been reached"; while (enumerator.MoveNext()) { iterations++; } retValue &= Test.Eval(_items.Length, iterations, "Err_64897adhs Items iterated through"); //[] Call MoveNext() several times after the end of the collection has been reached testDescription = "78083adshp Call MoveNext() several times after the end of the collection has been reached"; for (j = 0, scenarioResult = true; j < 3 && scenarioResult; j++) { try { Object tempCurrent = enumerator.Current; retValue &= scenarioResult = Test.Eval(_isGenericCompatibility, "Expected Current to throw InvalidOperationException after the end of the collection " + "has been reached and nothing was thrown Iterations({0})\n", i); } catch (InvalidOperationException) { } catch (Exception e) { retValue &= scenarioResult = Test.Eval(_isGenericCompatibility, "Expected Current to throw InvalidOperationException after the end of the collection " + "has been reache and the following exception was thrown Iterations({0}): \n{1}\n", i, e); } retValue &= scenarioResult = Test.Eval(!enumerator.MoveNext(), "Expected MoveNext() to return false on the {0} after the end of the collection has been reached\n", j + 1); } iterations = 0; if (!_isResetNotSupported) enumerator.Reset(); else enumerator = _collection.GetEnumerator(); } catch (Exception e) { retValue &= Test.Eval(false, "The following test: \n{0} threw the following exception: \n {1}\n", testDescription, e); break; } } return retValue; } /// <summary> /// Runs all of the tests on Current. /// </summary> /// <returns>true if all of the test passed else false.</returns> public bool Current_Tests() { bool retValue = true; IEnumerator enumerator = _collection.GetEnumerator(); String testDescription = "No description of test available"; for (int i = 0; i < 3 && retValue; i++) { try { //[] Call MoveNext() until the end of the collection has been reached testDescription = "Call MoveNext() until the end of the collection has been reached"; retValue &= Test.Eval(VerifyEnumerator(enumerator, _items), "Err_" + testDescription + " FAILED\n"); //[] Enumerate only part of the collection testDescription = "Enumerate only part of the collection "; if (_isResetNotSupported) enumerator = _collection.GetEnumerator(); else enumerator.Reset(); retValue &= Test.Eval(VerifyEnumerator(enumerator, _items, 0, _items.Length / 2, ExpectedEnumeratorRange.Start, true), "Err_" + testDescription + " FAILED\n"); //[] After Enumerating only part of the collection call Reset() and enumerate through the entire collection testDescription = "After Enumerating only part of the collection call Reset() and enumerate through the entire collection"; if (_isResetNotSupported) enumerator = _collection.GetEnumerator(); else enumerator.Reset(); retValue &= Test.Eval(VerifyEnumerator(enumerator, _items), "Err_" + testDescription + " FAILED\n"); //[] Reset the enumerator for the next iteration if (_isResetNotSupported) enumerator = _collection.GetEnumerator(); else enumerator.Reset(); } catch (Exception e) { retValue &= Test.Eval(false, "The following test: \n{0} threw the following exception: \n {1}\n", testDescription, e); break; } } return retValue; } /// <summary> /// Runs all of the tests on Reset(). /// </summary> /// <returns>true if all of the test passed else false.</returns> public bool Reset_Tests() { bool retValue = true; IEnumerator enumerator = _collection.GetEnumerator(); String testDescription = "No description of test available"; for (int i = 0; i < 3 && retValue; i++) { try { if (!_isResetNotSupported) { //[] Call Reset() several times on a new Enumerator then enumerate the collection testDescription = "Call Reset() several times on a new Enumerator"; retValue &= VerifyEnumerator(enumerator, _items); enumerator.Reset(); //[] Enumerate part of the collection then call Reset() several times testDescription = "Enumerate part of the collection then call Reset() several times"; retValue &= Test.Eval(VerifyEnumerator(enumerator, _items, 0, _items.Length / 2, ExpectedEnumeratorRange.Start, true), "Err_" + testDescription + " FAILED\n"); enumerator.Reset(); enumerator.Reset(); enumerator.Reset(); //[] After Enumerating only part of the collection and Reset() was called several times and enumerate through the entire collection testDescription = "After Enumerating only part of the collection and Reset() was called several times and enumerate through the entire collection"; retValue &= Test.Eval(VerifyEnumerator(enumerator, _items), "Err_" + testDescription + " FAILED\n"); enumerator.Reset(); //[] Enumerate the entire collection then call Reset() several times testDescription = "Enumerate the entire collection then call Reset() several times"; retValue &= Test.Eval(VerifyEnumerator(enumerator, _items), "Err_" + testDescription + " FAILED\n"); enumerator.Reset(); enumerator.Reset(); enumerator.Reset(); //[] After Enumerating the entire collection and Reset() was called several times and enumerate through the entire collection testDescription = "After Enumerating the entire collection and Reset() was called several times and enumerate through the entire collection"; retValue &= Test.Eval(VerifyEnumerator(enumerator, _items), "Err_" + testDescription + " FAILED\n"); enumerator.Reset(); } else { //[] Call Reset() several times on a new Enumerator then enumerate the collection testDescription = "Call Reset() several times on a new Enumerator"; int j = 0; bool scenarioResult; for (j = 0, scenarioResult = true; j < 3 && scenarioResult; ++j) { retValue &= scenarioResult = Test.Eval(Test.VerifyException<InvalidOperationException>(new ExceptionGenerator(enumerator.Reset)), "Verify Reset() Iteration:{0} FAILED", j); } retValue &= Test.Eval(VerifyEnumerator(enumerator, _items), "Err_" + testDescription + " FAILED\n Expected Reset to throw InvalidOperationException\n"); //[] Enumerate only part of the collection testDescription = "Enumerate only part of the collection "; enumerator = _collection.GetEnumerator(); retValue &= Test.Eval(VerifyEnumerator(enumerator, _items, 0, _items.Length / 2, ExpectedEnumeratorRange.Start | ExpectedEnumeratorRange.End, true), "Err_" + testDescription + " FAILED\n"); //[] After Enumerating only part of the collection call Reset() and enumerate through the entire collection testDescription = "After Enumerating only part of the collection call Reset() and enumerate through the entire collection"; for (j = 0; j < 3; ++j) { retValue &= Test.Eval(Test.VerifyException<InvalidOperationException>(new ExceptionGenerator(enumerator.Reset)), "Verify Reset() Iteration:{0} FAILED", j); } retValue &= Test.Eval(VerifyEnumerator(enumerator, _items, _items.Length / 2, _items.Length - (_items.Length / 2), ExpectedEnumeratorRange.Start | ExpectedEnumeratorRange.End, true), "Err_" + testDescription + " Reset is Supported FAILED\n"); //[] Enumerate the entire collection then call Reset() several times testDescription = "Enumerate the entire collection then call Reset() several times"; enumerator = _collection.GetEnumerator(); retValue &= Test.Eval(VerifyEnumerator(enumerator, _items), "Err_" + testDescription + " FAILED\n"); for (j = 0; j < 3; ++j) { retValue &= Test.Eval(Test.VerifyException<InvalidOperationException>(new ExceptionGenerator(enumerator.Reset)), "Verify Reset() Iteration:{0} FAILED", j); } //[] After Enumerating the entire collection and Reset() was called several times and enumerate through the entire collection testDescription = "After Enumerating the entire collection and Reset() was called several times and enumerate through the entire collection"; retValue &= Test.Eval(VerifyEnumerator(enumerator, _items, 0, 0, ExpectedEnumeratorRange.End, true), "Err_" + testDescription + " FAILED\n"); enumerator = _collection.GetEnumerator(); } } catch (Exception e) { retValue &= Test.Eval(false, "The following test: \n{0} threw the following exception: \n {1}", testDescription, e); break; } } return retValue; } /// <summary> /// Runs tests when the collection has been modified after /// the enumerator was created. /// </summary> /// <returns>true if all of the test passed else false.</returns> public bool ModifiedCollection_Test() { bool retValue = true; IEnumerator enumerator; String testDescription = "No description of test available"; Object currentItem; try { if (null == _modifyCollection) { //We have no way to modify the collection so we will just have to return true; return true; } //[] Verify Modifying collecton with new Enumerator testDescription = "Verify Modifying collecton with new Enumerator"; enumerator = _collection.GetEnumerator(); _items = _modifyCollection(_collection, _items); retValue &= Test.Eval(VerifyModifiedEnumerator(enumerator), "Err_" + testDescription + " FAILED\n"); //[] Verify enumerating to the first item //We can only do this test if there is more then 1 item in it //If the collection only has one item in it we will enumerate //to the first item in the test "Verify enumerating the entire collection" if (1 < _items.Length) { testDescription = "Verify enumerating to the first item"; enumerator = _collection.GetEnumerator(); retValue &= Test.Eval(VerifyEnumerator(enumerator, _items, 0, 1, 1 < _items.Length ? ExpectedEnumeratorRange.Start : ExpectedEnumeratorRange.Start | ExpectedEnumeratorRange.End, true), "Err_" + testDescription + " FAILED\n"); //[] Verify Modifying collection on an enumerator that has enumerated to the first item in the collection testDescription = "Verify Modifying collection on an enumerator that has enumerated to the first item in the collection"; currentItem = enumerator.Current; _items = _modifyCollection(_collection, _items); retValue &= Test.Eval(VerifyModifiedEnumerator(enumerator, currentItem), "Err_" + testDescription + " FAILED\n"); } //[] Verify enumerating part of the collection //We can only do this test if there is more then 1 item in it //If the collection only has one item in it we will enumerate //to the first item in the test "Verify enumerating the entire collection" if (1 < _items.Length) { testDescription = "Verify enumerating part of the collection"; enumerator = _collection.GetEnumerator(); retValue &= Test.Eval(VerifyEnumerator(enumerator, _items, 0, _items.Length / 2, ExpectedEnumeratorRange.Start, true), "Err_" + testDescription + " FAILED\n"); //[] Verify Modifying collection on an enumerator that has enumerated part of the collection testDescription = " Verify Modifying collection on an enumerator that has enumerated part of the collection"; currentItem = enumerator.Current; _items = _modifyCollection(_collection, _items); retValue &= Test.Eval(VerifyModifiedEnumerator(enumerator, currentItem), "Err_" + testDescription + " FAILED\n"); } //[] Verify enumerating the entire collection if (0 != _items.Length) { testDescription = "Verify enumerating the entire collection"; enumerator = _collection.GetEnumerator(); retValue &= Test.Eval(VerifyEnumerator(enumerator, _items, 0, _items.Length, ExpectedEnumeratorRange.Start), "Err_" + testDescription + " FAILED\n"); //[] Verify Modifying collection on an enumerator that has enumerated the entire collection testDescription = "Verify Modifying collection on an enumerator that has enumerated the entire collection"; currentItem = enumerator.Current; _items = _modifyCollection(_collection, _items); retValue &= Test.Eval(VerifyModifiedEnumerator(enumerator, currentItem), "Err_" + testDescription + " FAILED\n"); } //[] Verify enumerating past the end of the collection if (0 != _items.Length) { testDescription = "Verify enumerating past the end of the collection"; enumerator = _collection.GetEnumerator(); retValue &= Test.Eval(VerifyEnumerator(enumerator, _items), "Err_" + testDescription + " FAILED\n"); //[] Verify Modifying collection on an enumerator that has enumerated past the end of the collection testDescription = "Verify Modifying collection on an enumerator that has enumerated past the end of the collection"; currentItem = null; _items = _modifyCollection(_collection, _items); retValue &= Test.Eval(VerifyModifiedEnumerator(enumerator, currentItem, true), "Err_" + testDescription + " FAILED\n"); } } catch (Exception e) { retValue &= Test.Eval(false, "The following test: \n{0} threw the following exception: \n {1}", testDescription, e); } return retValue; } private bool VerifyModifiedEnumerator(IEnumerator enumerator) { return VerifyModifiedEnumerator(enumerator, null, true); } private bool VerifyModifiedEnumerator(IEnumerator enumerator, Object expectedCurrent) { return VerifyModifiedEnumerator(enumerator, expectedCurrent, false); } private bool VerifyModifiedEnumerator(IEnumerator enumerator, Object expectedCurrent, bool expectCurrentThrow) { bool retValue = true; int i; bool scenarioResult; //[] Verify Current try { Object currentItem = enumerator.Current; if (expectCurrentThrow) { retValue &= Test.Eval(_isGenericCompatibility, "Current should have thrown an exception on a modified collection"); } else { //[] Verify Current always returns the same value every time it is called for (i = 0, scenarioResult = true; i < 3 && scenarioResult; i++) { retValue &= scenarioResult = Test.Eval(_comparer.Equals(expectedCurrent, currentItem), "Current is returning inconsistent results Current returned={0} expected={1} Iteration({2})", currentItem, expectCurrentThrow, i); currentItem = enumerator.Current; } } } catch (InvalidOperationException) { retValue &= Test.Eval(expectCurrentThrow, "Did not expect Current to throw InvalidOperationException"); } catch (Exception e) { retValue &= Test.Eval(!_isGenericCompatibility || !expectCurrentThrow, "Current should have thrown an InvalidOperationException on a modified collection but the following was thrown:\n{0}", e); } //[] Verify MoveNext() try { enumerator.MoveNext(); retValue &= Test.Eval(false, "MoveNext() should have thrown an exception on a modified collection"); } catch (InvalidOperationException) { } catch (Exception e) { retValue &= Test.Eval(false, "MoveNext() should have thrown an InvalidOperationException on a modified collection but the following was thrown:\n{0}", e); } //[] Verify Reset() try { enumerator.Reset(); retValue &= Test.Eval(false, "Reset() should have thrown an exception on a modified collection"); } catch (InvalidOperationException) { } catch (Exception e) { retValue &= Test.Eval(false, "Reset() should have thrown an InvalidOperationException on a modified collection but the following was thrown:\n{0}", e); } return retValue; } protected bool VerifyCollection(IEnumerable collection, Object[] expectedItems) { return VerifyCollection(collection, expectedItems, 0, expectedItems.Length); } protected bool VerifyCollection(IEnumerable collection, Object[] expectedItems, int startIndex, int count) { return VerifyEnumerator(collection.GetEnumerator(), expectedItems, startIndex, count, ExpectedEnumeratorRange.Start | ExpectedEnumeratorRange.End); } private bool VerifyEnumerator(IEnumerator enumerator, Object[] expectedItems) { return VerifyEnumerator(enumerator, expectedItems, 0, expectedItems.Length, ExpectedEnumeratorRange.Start | ExpectedEnumeratorRange.End); } private bool VerifyEnumerator(IEnumerator enumerator, Object[] expectedItems, int startIndex, int count) { return VerifyEnumerator(enumerator, expectedItems, startIndex, count, ExpectedEnumeratorRange.Start | ExpectedEnumeratorRange.End); } private bool VerifyEnumerator( IEnumerator enumerator, Object[] expectedItems, int startIndex, int count, ExpectedEnumeratorRange expectedEnumeratorRange) { return VerifyEnumerator(enumerator, expectedItems, startIndex, count, expectedEnumeratorRange, false); } private bool VerifyEnumerator( IEnumerator enumerator, Object[] expectedItems, int startIndex, int count, ExpectedEnumeratorRange expectedEnumeratorRange, bool looseMatchingUnspecifiedOrder) { bool retValue = true; int iterations = 0; int i; bool scenarioResult; //[] Verify Current throws every time it is called before a call to MoveNext() has been made if ((expectedEnumeratorRange & ExpectedEnumeratorRange.Start) != 0) { for (i = 0, scenarioResult = true; i < 3 && scenarioResult; i++) { try { Object tempCurrent = enumerator.Current; retValue &= scenarioResult = Test.Eval(_isGenericCompatibility, "Expected Current to throw InvalidOperationException before MoveNext() " + "has been called and nothing was thrown Iterations({0})", i); } catch (InvalidOperationException) { } catch (Exception e) { retValue &= scenarioResult = Test.Eval(_isGenericCompatibility, "Expected Current to throw InvalidOperationException before MoveNext() " + "has been called and the following exception was thrown Iterations({0}): \n{1}", i, e); } } } scenarioResult = true; if (_collectionOrder == CollectionOrder.Unspecified) { System.Collections.Generic.List<Boolean> itemsVisited; bool itemFound; if (looseMatchingUnspecifiedOrder) { itemsVisited = new System.Collections.Generic.List<Boolean>(expectedItems.Length); } else { itemsVisited = new System.Collections.Generic.List<Boolean>(count); } for (i = 0; i < itemsVisited.Count; i++) itemsVisited[i] = false; while ((iterations < count) && enumerator.MoveNext()) { Object currentItem = enumerator.Current; Object tempItem; //[] Verify we have not gotten more items then we expected retValue &= Test.Eval(iterations < count, "More items have been returned fromt the enumerator({0} items) then are " + "in the expectedElements({1} items)", iterations, count); //[] Verify Current returned the correct value itemFound = false; for (i = 0; i < itemsVisited.Count; ++i) { if (!itemsVisited[i] && _comparer.Equals(currentItem, expectedItems[startIndex + i])) { itemsVisited[i] = true; itemFound = true; break; } } retValue &= Test.Eval(itemFound, "Current returned unexpected value={0}", currentItem); //[] Verify Current always returns the same value every time it is called for (i = 0; i < 3; i++) { tempItem = enumerator.Current; retValue &= Test.Eval(_comparer.Equals(currentItem, tempItem), "Current is returning inconsistent results Current returned={0} expected={1}", tempItem, currentItem); } iterations++; } if (looseMatchingUnspecifiedOrder) { int visitedItemsCount = 0; for (i = 0; i < itemsVisited.Count; ++i) { if (itemsVisited[i]) { ++visitedItemsCount; } } Test.Eval(count, visitedItemsCount, "Number of items enumerator returned"); } else { for (i = 0; i < count; ++i) { retValue &= Test.Eval(itemsVisited[i], "Expected Current to return {0}", expectedItems[startIndex + i]); } } } else { while ((iterations < count) && enumerator.MoveNext()) { Object currentItem = enumerator.Current; Object tempItem; //[] Verify we have not gotten more items then we expected retValue &= Test.Eval(iterations < count, "More items have been returned fromt the enumerator({0} items) then are " + "in the expectedElements({1} items)", iterations, count); //[] Verify Current returned the correct value retValue &= Test.Eval(_comparer.Equals(currentItem, expectedItems[startIndex + iterations]), "Current returned unexpected value={0} expected={1}", currentItem, expectedItems[startIndex + iterations]); //[] Verify Current always returns the same value every time it is called for (i = 0; i < 3; i++) { tempItem = enumerator.Current; retValue &= Test.Eval(_comparer.Equals(currentItem, tempItem), "Current is returning inconsistent results Current returned={0} expected={1}", tempItem, currentItem); } iterations++; } } retValue &= Test.Eval(count, iterations, "Items iterated through"); if ((expectedEnumeratorRange & ExpectedEnumeratorRange.End) != 0) { //[] Verify MoveNext returns false every time it is called after the end of the collection has been reached for (i = 0, scenarioResult = true; i < 3 && scenarioResult; i++) { retValue &= scenarioResult &= Test.Eval(!enumerator.MoveNext(), "Expected MoveNext to return false iteration {0}", i); } //[] Verify Current throws every time it is called after the end of the collection has been reached for (i = 0, scenarioResult = true; i < 3 && scenarioResult; i++) { try { Object tempCurrent = enumerator.Current; retValue &= scenarioResult = Test.Eval(_isGenericCompatibility, "Expected Current to throw InvalidOperationException after the end of the collection " + "has been reached and nothing was thrown Iterations({0})", i); } catch (InvalidOperationException) { } catch (Exception e) { retValue &= scenarioResult = Test.Eval(_isGenericCompatibility, "Expected Current to throw InvalidOperationException after the end of the collection " + "has been reache and the following exception was thrown Iterations({0}): \n{1}", i, e); } } } return retValue; } } }
// ------------------------------------------------------------------------------ // Copyright (c) 2014 Microsoft Corporation // // 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.Threading; using System.Threading.Tasks; using Windows.Storage; using Windows.Storage.Pickers; using Windows.Storage.Streams; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media.Imaging; using Windows.UI.Xaml.Navigation; using Microsoft.Live; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace StreamUploadDownload { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { private static readonly string[] scopes = new string[]{"wl.signin", "wl.basic", "wl.skydrive_update"}; private LiveAuthClient authClient; private LiveConnectClient liveClient; private CancellationTokenSource cts; public MainPage() { this.InitializeComponent(); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { this.InitializePage(); CheckPendingBackgroundOperations(); } private async void InitializePage() { try { this.authClient = new LiveAuthClient(); LiveLoginResult loginResult = await this.authClient.InitializeAsync(scopes); if (loginResult.Status == LiveConnectSessionStatus.Connected) { if (this.authClient.CanLogout) { this.btnLogin.Content = "Sign Out"; } else { this.btnLogin.Visibility = Visibility.Collapsed; } this.liveClient = new LiveConnectClient(loginResult.Session); } } catch (LiveAuthException) { // TODO: Display the exception } } private async void btnLogin_Click(object sender, RoutedEventArgs e) { try { if (this.btnLogin.Content.ToString() == "Sign In") { LiveLoginResult loginResult = await this.authClient.LoginAsync(scopes); if (loginResult.Status == LiveConnectSessionStatus.Connected) { if (this.authClient.CanLogout) { this.btnLogin.Content = "Sign Out"; } else { this.btnLogin.Visibility = Visibility.Collapsed; } this.liveClient = new LiveConnectClient(loginResult.Session); } } else { this.authClient.Logout(); this.btnLogin.Content = "Sign In"; } } catch (LiveAuthException) { // TODO: Display the exception } } private void btnUploadFile_Click(object sender, RoutedEventArgs e) { this.UploadFile(); } private void btnDownload_Click(object sender, RoutedEventArgs e) { this.DownloadFile(); } private async void UploadFile() { if (this.liveClient == null) { this.ShowMessage("Please sign in first."); return; } try { string folderPath = this.tbUrl.Text; var picker = new FileOpenPicker { ViewMode = PickerViewMode.Thumbnail, SuggestedStartLocation = PickerLocationId.PicturesLibrary }; picker.FileTypeFilter.Add("*"); StorageFile file = await picker.PickSingleFileAsync(); if (file != null) { using (IInputStream inStream = await file.OpenReadAsync().AsTask()) { this.progressBar.Value = 0; this.ShowProgress(); var progressHandler = new Progress<LiveOperationProgress>( (progress) => { this.progressBar.Value = progress.ProgressPercentage; }); this.cts = new CancellationTokenSource(); LiveUploadOperation operation = await this.liveClient.CreateBackgroundUploadAsync( folderPath, file.Name, inStream, OverwriteOption.Rename); LiveOperationResult result = await operation.StartAsync(this.cts.Token, progressHandler); if (result != null) { this.progressBar.Value = 0; dynamic fileData = result.Result; string downloadUrl = fileData.id + "/picture"; this.tbUrl.Text = downloadUrl; this.ShowMessage("Upload completed."); } else { this.ShowMessage("Upload failed."); } } } } catch (TaskCanceledException) { this.ShowMessage("User has cancelled the operation."); } catch (Exception exp) { this.ShowMessage(exp.ToString()); } } private async void DownloadFile() { if (this.liveClient == null) { this.ShowMessage("Please sign in first."); return; } try { string filePath = this.tbUrl.Text; if (string.IsNullOrEmpty(filePath)) { this.ShowMessage("Please specify a file id or a url."); } else { this.progressBar.Value = 0; this.ShowProgress(); var progressHandler = new Progress<LiveOperationProgress>( (progress) => { this.progressBar.Value = progress.ProgressPercentage; }); this.cts = new CancellationTokenSource(); LiveDownloadOperation op = await this.liveClient.CreateBackgroundDownloadAsync(filePath); LiveDownloadOperationResult downloadResult = await op.StartAsync(this.cts.Token, progressHandler); if (downloadResult.Stream != null) { using (IRandomAccessStream ras = await downloadResult.GetRandomAccessStreamAsync()) { var imgSource = new BitmapImage(); imgSource.SetSource(ras); this.imgPreview.Source = imgSource; this.ShowImage(); } } else { this.ShowMessage("Download failed."); } } } catch (TaskCanceledException) { this.ShowMessage("User has cancelled the operation."); } catch (Exception exp) { this.ShowMessage(exp.ToString()); } } private void btnCancel_Click(object sender, RoutedEventArgs e) { if (this.cts != null) { this.cts.Cancel(); } } private void ShowProgress() { this.imgPreview.Visibility = Visibility.Collapsed; this.tbMessage.Visibility = Visibility.Collapsed; this.progressBar.Value = 0; this.progressBar.Visibility = Visibility.Visible; this.btnCancel.IsEnabled = true; } private void ShowMessage(string message) { this.imgPreview.Visibility = Visibility.Collapsed; this.tbMessage.Text = message; this.tbMessage.Visibility = Visibility.Visible; this.progressBar.Visibility = Visibility.Collapsed; this.btnCancel.IsEnabled = false; } private void ShowImage() { this.tbMessage.Visibility = Visibility.Collapsed; this.imgPreview.Visibility = Visibility.Visible; this.progressBar.Visibility = Visibility.Collapsed; this.btnCancel.IsEnabled = false; } private async void CheckPendingBackgroundOperations() { var downloadOperations = await Microsoft.Live.LiveConnectClient.GetCurrentBackgroundDownloadsAsync(); foreach (var operation in downloadOperations) { try { var result = await operation.AttachAsync(); // Process download completed results. } catch (Exception ex) { // Handle download error } } var uploadOperations = await Microsoft.Live.LiveConnectClient.GetCurrentBackgroundUploadsAsync(); foreach (var operation in uploadOperations) { try { var result = await operation.AttachAsync(); // Process upload completed results. } catch (Exception ex) { // Handle upload error } } } } }
// 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. // // Copyright (c) 2006 Novell, Inc. (http://www.novell.com) // // using System; using System.Collections.Generic; using System.Linq; using static Avalonia.X11.XLib; // ReSharper disable FieldCanBeMadeReadOnly.Global // ReSharper disable IdentifierTypo // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedMember.Global // ReSharper disable CommentTypo // ReSharper disable ArrangeThisQualifier // ReSharper disable NotAccessedField.Global // ReSharper disable InconsistentNaming // ReSharper disable StringLiteralTypo #pragma warning disable 649 namespace Avalonia.X11 { internal class X11Atoms { private readonly IntPtr _display; // Our atoms public readonly IntPtr AnyPropertyType = (IntPtr)0; public readonly IntPtr XA_PRIMARY = (IntPtr)1; public readonly IntPtr XA_SECONDARY = (IntPtr)2; public readonly IntPtr XA_ARC = (IntPtr)3; public readonly IntPtr XA_ATOM = (IntPtr)4; public readonly IntPtr XA_BITMAP = (IntPtr)5; public readonly IntPtr XA_CARDINAL = (IntPtr)6; public readonly IntPtr XA_COLORMAP = (IntPtr)7; public readonly IntPtr XA_CURSOR = (IntPtr)8; public readonly IntPtr XA_CUT_BUFFER0 = (IntPtr)9; public readonly IntPtr XA_CUT_BUFFER1 = (IntPtr)10; public readonly IntPtr XA_CUT_BUFFER2 = (IntPtr)11; public readonly IntPtr XA_CUT_BUFFER3 = (IntPtr)12; public readonly IntPtr XA_CUT_BUFFER4 = (IntPtr)13; public readonly IntPtr XA_CUT_BUFFER5 = (IntPtr)14; public readonly IntPtr XA_CUT_BUFFER6 = (IntPtr)15; public readonly IntPtr XA_CUT_BUFFER7 = (IntPtr)16; public readonly IntPtr XA_DRAWABLE = (IntPtr)17; public readonly IntPtr XA_FONT = (IntPtr)18; public readonly IntPtr XA_INTEGER = (IntPtr)19; public readonly IntPtr XA_PIXMAP = (IntPtr)20; public readonly IntPtr XA_POINT = (IntPtr)21; public readonly IntPtr XA_RECTANGLE = (IntPtr)22; public readonly IntPtr XA_RESOURCE_MANAGER = (IntPtr)23; public readonly IntPtr XA_RGB_COLOR_MAP = (IntPtr)24; public readonly IntPtr XA_RGB_BEST_MAP = (IntPtr)25; public readonly IntPtr XA_RGB_BLUE_MAP = (IntPtr)26; public readonly IntPtr XA_RGB_DEFAULT_MAP = (IntPtr)27; public readonly IntPtr XA_RGB_GRAY_MAP = (IntPtr)28; public readonly IntPtr XA_RGB_GREEN_MAP = (IntPtr)29; public readonly IntPtr XA_RGB_RED_MAP = (IntPtr)30; public readonly IntPtr XA_STRING = (IntPtr)31; public readonly IntPtr XA_VISUALID = (IntPtr)32; public readonly IntPtr XA_WINDOW = (IntPtr)33; public readonly IntPtr XA_WM_COMMAND = (IntPtr)34; public readonly IntPtr XA_WM_HINTS = (IntPtr)35; public readonly IntPtr XA_WM_CLIENT_MACHINE = (IntPtr)36; public readonly IntPtr XA_WM_ICON_NAME = (IntPtr)37; public readonly IntPtr XA_WM_ICON_SIZE = (IntPtr)38; public readonly IntPtr XA_WM_NAME = (IntPtr)39; public readonly IntPtr XA_WM_NORMAL_HINTS = (IntPtr)40; public readonly IntPtr XA_WM_SIZE_HINTS = (IntPtr)41; public readonly IntPtr XA_WM_ZOOM_HINTS = (IntPtr)42; public readonly IntPtr XA_MIN_SPACE = (IntPtr)43; public readonly IntPtr XA_NORM_SPACE = (IntPtr)44; public readonly IntPtr XA_MAX_SPACE = (IntPtr)45; public readonly IntPtr XA_END_SPACE = (IntPtr)46; public readonly IntPtr XA_SUPERSCRIPT_X = (IntPtr)47; public readonly IntPtr XA_SUPERSCRIPT_Y = (IntPtr)48; public readonly IntPtr XA_SUBSCRIPT_X = (IntPtr)49; public readonly IntPtr XA_SUBSCRIPT_Y = (IntPtr)50; public readonly IntPtr XA_UNDERLINE_POSITION = (IntPtr)51; public readonly IntPtr XA_UNDERLINE_THICKNESS = (IntPtr)52; public readonly IntPtr XA_STRIKEOUT_ASCENT = (IntPtr)53; public readonly IntPtr XA_STRIKEOUT_DESCENT = (IntPtr)54; public readonly IntPtr XA_ITALIC_ANGLE = (IntPtr)55; public readonly IntPtr XA_X_HEIGHT = (IntPtr)56; public readonly IntPtr XA_QUAD_WIDTH = (IntPtr)57; public readonly IntPtr XA_WEIGHT = (IntPtr)58; public readonly IntPtr XA_POINT_SIZE = (IntPtr)59; public readonly IntPtr XA_RESOLUTION = (IntPtr)60; public readonly IntPtr XA_COPYRIGHT = (IntPtr)61; public readonly IntPtr XA_NOTICE = (IntPtr)62; public readonly IntPtr XA_FONT_NAME = (IntPtr)63; public readonly IntPtr XA_FAMILY_NAME = (IntPtr)64; public readonly IntPtr XA_FULL_NAME = (IntPtr)65; public readonly IntPtr XA_CAP_HEIGHT = (IntPtr)66; public readonly IntPtr XA_WM_CLASS = (IntPtr)67; public readonly IntPtr XA_WM_TRANSIENT_FOR = (IntPtr)68; public readonly IntPtr WM_PROTOCOLS; public readonly IntPtr WM_DELETE_WINDOW; public readonly IntPtr WM_TAKE_FOCUS; public readonly IntPtr _NET_SUPPORTED; public readonly IntPtr _NET_CLIENT_LIST; public readonly IntPtr _NET_NUMBER_OF_DESKTOPS; public readonly IntPtr _NET_DESKTOP_GEOMETRY; public readonly IntPtr _NET_DESKTOP_VIEWPORT; public readonly IntPtr _NET_CURRENT_DESKTOP; public readonly IntPtr _NET_DESKTOP_NAMES; public readonly IntPtr _NET_ACTIVE_WINDOW; public readonly IntPtr _NET_WORKAREA; public readonly IntPtr _NET_SUPPORTING_WM_CHECK; public readonly IntPtr _NET_VIRTUAL_ROOTS; public readonly IntPtr _NET_DESKTOP_LAYOUT; public readonly IntPtr _NET_SHOWING_DESKTOP; public readonly IntPtr _NET_CLOSE_WINDOW; public readonly IntPtr _NET_MOVERESIZE_WINDOW; public readonly IntPtr _NET_WM_MOVERESIZE; public readonly IntPtr _NET_RESTACK_WINDOW; public readonly IntPtr _NET_REQUEST_FRAME_EXTENTS; public readonly IntPtr _NET_WM_NAME; public readonly IntPtr _NET_WM_VISIBLE_NAME; public readonly IntPtr _NET_WM_ICON_NAME; public readonly IntPtr _NET_WM_VISIBLE_ICON_NAME; public readonly IntPtr _NET_WM_DESKTOP; public readonly IntPtr _NET_WM_WINDOW_TYPE; public readonly IntPtr _NET_WM_STATE; public readonly IntPtr _NET_WM_ALLOWED_ACTIONS; public readonly IntPtr _NET_WM_STRUT; public readonly IntPtr _NET_WM_STRUT_PARTIAL; public readonly IntPtr _NET_WM_ICON_GEOMETRY; public readonly IntPtr _NET_WM_ICON; public readonly IntPtr _NET_WM_PID; public readonly IntPtr _NET_WM_HANDLED_ICONS; public readonly IntPtr _NET_WM_USER_TIME; public readonly IntPtr _NET_FRAME_EXTENTS; public readonly IntPtr _NET_WM_PING; public readonly IntPtr _NET_WM_SYNC_REQUEST; public readonly IntPtr _NET_SYSTEM_TRAY_S; public readonly IntPtr _NET_SYSTEM_TRAY_ORIENTATION; public readonly IntPtr _NET_SYSTEM_TRAY_OPCODE; public readonly IntPtr _NET_WM_STATE_MAXIMIZED_HORZ; public readonly IntPtr _NET_WM_STATE_MAXIMIZED_VERT; public readonly IntPtr _NET_WM_STATE_FULLSCREEN; public readonly IntPtr _XEMBED; public readonly IntPtr _XEMBED_INFO; public readonly IntPtr _MOTIF_WM_HINTS; public readonly IntPtr _NET_WM_STATE_SKIP_TASKBAR; public readonly IntPtr _NET_WM_STATE_ABOVE; public readonly IntPtr _NET_WM_STATE_MODAL; public readonly IntPtr _NET_WM_STATE_HIDDEN; public readonly IntPtr _NET_WM_CONTEXT_HELP; public readonly IntPtr _NET_WM_WINDOW_OPACITY; public readonly IntPtr _NET_WM_WINDOW_TYPE_DESKTOP; public readonly IntPtr _NET_WM_WINDOW_TYPE_DOCK; public readonly IntPtr _NET_WM_WINDOW_TYPE_TOOLBAR; public readonly IntPtr _NET_WM_WINDOW_TYPE_MENU; public readonly IntPtr _NET_WM_WINDOW_TYPE_UTILITY; public readonly IntPtr _NET_WM_WINDOW_TYPE_SPLASH; public readonly IntPtr _NET_WM_WINDOW_TYPE_DIALOG; public readonly IntPtr _NET_WM_WINDOW_TYPE_NORMAL; public readonly IntPtr CLIPBOARD; public readonly IntPtr CLIPBOARD_MANAGER; public readonly IntPtr SAVE_TARGETS; public readonly IntPtr MULTIPLE; public readonly IntPtr PRIMARY; public readonly IntPtr OEMTEXT; public readonly IntPtr UNICODETEXT; public readonly IntPtr TARGETS; public readonly IntPtr UTF8_STRING; public readonly IntPtr UTF16_STRING; public readonly IntPtr ATOM_PAIR; public readonly IntPtr MANAGER; public readonly IntPtr _KDE_NET_WM_BLUR_BEHIND_REGION; public readonly IntPtr INCR; private readonly Dictionary<string, IntPtr> _namesToAtoms = new Dictionary<string, IntPtr>(); private readonly Dictionary<IntPtr, string> _atomsToNames = new Dictionary<IntPtr, string>(); public X11Atoms(IntPtr display) { _display = display; // make sure this array stays in sync with the statements below var fields = typeof(X11Atoms).GetFields() .Where(f => f.FieldType == typeof(IntPtr) && (IntPtr)f.GetValue(this) == IntPtr.Zero).ToArray(); var atomNames = fields.Select(f => f.Name).ToArray(); IntPtr[] atoms = new IntPtr [atomNames.Length]; ; XInternAtoms(display, atomNames, atomNames.Length, true, atoms); for (var c = 0; c < fields.Length; c++) { _namesToAtoms[fields[c].Name] = atoms[c]; _atomsToNames[atoms[c]] = fields[c].Name; fields[c].SetValue(this, atoms[c]); } } public IntPtr GetAtom(string name) { if (_namesToAtoms.TryGetValue(name, out var rv)) return rv; var atom = XInternAtom(_display, name, false); _namesToAtoms[name] = atom; _atomsToNames[atom] = name; return atom; } public string GetAtomName(IntPtr atom) { if (_atomsToNames.TryGetValue(atom, out var rv)) return rv; var name = XLib.GetAtomName(_display, atom); if (name == null) return null; _atomsToNames[atom] = name; _namesToAtoms[name] = atom; return name; } } }
//------------------------------------------------------------------------------ // <copyright file="XmlSchemaException.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> //------------------------------------------------------------------------------ namespace System.Xml.Schema { using System; using System.IO; using System.Text; using System.Resources; using System.Runtime.Serialization; using System.Globalization; using System.Diagnostics; using System.Security.Permissions; /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException"]/*' /> [Serializable] public class XmlSchemaException : SystemException { string res; string[] args; string sourceUri; int lineNumber; int linePosition; [NonSerialized] XmlSchemaObject sourceSchemaObject; // message != null for V1 exceptions deserialized in Whidbey // message == null for V2 or higher exceptions; the exception message is stored on the base class (Exception._message) string message; /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException5"]/*' /> protected XmlSchemaException(SerializationInfo info, StreamingContext context) : base(info, context) { res = (string) info.GetValue("res" , typeof(string)); args = (string[]) info.GetValue("args", typeof(string[])); sourceUri = (string) info.GetValue("sourceUri", typeof(string)); lineNumber = (int) info.GetValue("lineNumber", typeof(int)); linePosition = (int) info.GetValue("linePosition", typeof(int)); // deserialize optional members string version = null; foreach ( SerializationEntry e in info ) { if ( e.Name == "version" ) { version = (string)e.Value; } } if ( version == null ) { // deserializing V1 exception message = CreateMessage( res, args ); } else { // deserializing V2 or higher exception -> exception message is serialized by the base class (Exception._message) message = null; } } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.GetObjectData"]/*' /> [SecurityPermissionAttribute(SecurityAction.LinkDemand,SerializationFormatter=true)] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue("res", res); info.AddValue("args", args); info.AddValue("sourceUri", sourceUri); info.AddValue("lineNumber", lineNumber); info.AddValue("linePosition", linePosition); info.AddValue("version", "2.0"); } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException1"]/*' /> public XmlSchemaException() : this(null) { } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException2"]/*' /> public XmlSchemaException(String message) : this (message, ((Exception)null), 0, 0) { #if DEBUG Debug.Assert(message == null || !message.StartsWith("Sch_", StringComparison.Ordinal), "Do not pass a resource here!"); #endif } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException0"]/*' /> public XmlSchemaException(String message, Exception innerException) : this (message, innerException, 0, 0) { } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.XmlSchemaException3"]/*' /> public XmlSchemaException(String message, Exception innerException, int lineNumber, int linePosition) : this((message == null ? Res.Sch_DefaultException : Res.Xml_UserException), new string[] { message }, innerException, null, lineNumber, linePosition, null ) { } internal XmlSchemaException(string res, string[] args) : this(res, args, null, null, 0, 0, null) {} internal XmlSchemaException(string res, string arg) : this(res, new string[] { arg }, null, null, 0, 0, null) {} internal XmlSchemaException(string res, string arg, string sourceUri, int lineNumber, int linePosition) : this(res, new string[] { arg }, null, sourceUri, lineNumber, linePosition, null) {} internal XmlSchemaException(string res, string sourceUri, int lineNumber, int linePosition) : this(res, (string[])null, null, sourceUri, lineNumber, linePosition, null) {} internal XmlSchemaException(string res, string[] args, string sourceUri, int lineNumber, int linePosition) : this(res, args, null, sourceUri, lineNumber, linePosition, null) {} internal XmlSchemaException(string res, XmlSchemaObject source) : this(res, (string[])null, source) {} internal XmlSchemaException(string res, string arg, XmlSchemaObject source) : this(res, new string[] { arg }, source) {} internal XmlSchemaException(string res, string[] args, XmlSchemaObject source) : this(res, args, null, source.SourceUri, source.LineNumber, source.LinePosition, source) {} internal XmlSchemaException(string res, string[] args, Exception innerException, string sourceUri, int lineNumber, int linePosition, XmlSchemaObject source) : base (CreateMessage(res, args), innerException) { HResult = HResults.XmlSchema; this.res = res; this.args = args; this.sourceUri = sourceUri; this.lineNumber = lineNumber; this.linePosition = linePosition; this.sourceSchemaObject = source; } internal static string CreateMessage(string res, string[] args) { try { return Res.GetString(res, args); } catch ( MissingManifestResourceException ) { return "UNKNOWN("+res+")"; } } internal string GetRes { get { return res; } } internal string[] Args { get { return args; } } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.SourceUri"]/*' /> public string SourceUri { get { return this.sourceUri; } } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.LineNumber"]/*' /> public int LineNumber { get { return this.lineNumber; } } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.LinePosition"]/*' /> public int LinePosition { get { return this.linePosition; } } /// <include file='doc\XmlSchemaException.uex' path='docs/doc[@for="XmlSchemaException.SourceObject"]/*' /> public XmlSchemaObject SourceSchemaObject { get { return this.sourceSchemaObject; } } /*internal static XmlSchemaException Create(string res) { //Since internal overload with res string will clash with public constructor that takes in a message return new XmlSchemaException(res, (string[])null, null, null, 0, 0, null); }*/ internal void SetSource(string sourceUri, int lineNumber, int linePosition) { this.sourceUri = sourceUri; this.lineNumber = lineNumber; this.linePosition = linePosition; } internal void SetSchemaObject(XmlSchemaObject source) { this.sourceSchemaObject = source; } internal void SetSource(XmlSchemaObject source) { this.sourceSchemaObject = source; this.sourceUri = source.SourceUri; this.lineNumber = source.LineNumber; this.linePosition = source.LinePosition; } internal void SetResourceId(string resourceId) { this.res = resourceId; } public override string Message { get { return (message == null) ? base.Message : message; } } }; } // namespace System.Xml.Schema
namespace Nancy.ModelBinding { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text.RegularExpressions; using Nancy.Extensions; /// <summary> /// Default binder - used as a fallback when a specific modelbinder /// is not available. /// </summary> public class DefaultBinder : IBinder { private readonly IEnumerable<ITypeConverter> typeConverters; private readonly IEnumerable<IBodyDeserializer> bodyDeserializers; private readonly IFieldNameConverter fieldNameConverter; private readonly BindingDefaults defaults; private readonly static MethodInfo ToListMethodInfo = typeof(Enumerable).GetMethod("ToList", BindingFlags.Public | BindingFlags.Static); private readonly static MethodInfo ToArrayMethodInfo = typeof(Enumerable).GetMethod("ToArray", BindingFlags.Public | BindingFlags.Static); private static readonly Regex BracketRegex = new Regex(@"\[(\d+)\]\z", RegexOptions.Compiled); private static readonly Regex UnderscoreRegex = new Regex(@"_(\d+)\z", RegexOptions.Compiled); public DefaultBinder(IEnumerable<ITypeConverter> typeConverters, IEnumerable<IBodyDeserializer> bodyDeserializers, IFieldNameConverter fieldNameConverter, BindingDefaults defaults) { if (typeConverters == null) { throw new ArgumentNullException("typeConverters"); } if (bodyDeserializers == null) { throw new ArgumentNullException("bodyDeserializers"); } if (fieldNameConverter == null) { throw new ArgumentNullException("fieldNameConverter"); } if (defaults == null) { throw new ArgumentNullException("defaults"); } this.typeConverters = typeConverters; this.bodyDeserializers = bodyDeserializers; this.fieldNameConverter = fieldNameConverter; this.defaults = defaults; } /// <summary> /// Bind to the given model type /// </summary> /// <param name="context">Current context</param> /// <param name="modelType">Model type to bind to</param> /// <param name="instance">Optional existing instance</param> /// <param name="configuration">The <see cref="BindingConfig"/> that should be applied during binding.</param> /// <param name="blackList">Blacklisted binding property names</param> /// <returns>Bound model</returns> public object Bind(NancyContext context, Type modelType, object instance, BindingConfig configuration, params string[] blackList) { Type genericType = null; if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable()) { //make sure it has a generic type if (modelType.IsGenericType()) { genericType = modelType.GetGenericArguments().FirstOrDefault(); } else { var ienumerable = modelType.GetInterfaces().Where(i => i.IsGenericType()).FirstOrDefault( i => i.GetGenericTypeDefinition() == typeof(IEnumerable<>)); genericType = ienumerable == null ? null : ienumerable.GetGenericArguments().FirstOrDefault(); } if (genericType == null) { throw new ArgumentException("When modelType is an enumerable it must specify the type.", "modelType"); } } var bindingContext = this.CreateBindingContext(context, modelType, instance, configuration, blackList, genericType); try { var bodyDeserializedModel = this.DeserializeRequestBody(bindingContext); if (bodyDeserializedModel != null) { UpdateModelWithDeserializedModel(bodyDeserializedModel, bindingContext); } } catch (Exception exception) { if (!bindingContext.Configuration.IgnoreErrors) { throw new ModelBindingException(modelType, innerException: exception); } } var bindingExceptions = new List<PropertyBindingException>(); if (!bindingContext.Configuration.BodyOnly) { if (bindingContext.DestinationType.IsCollection() || bindingContext.DestinationType.IsArray() ||bindingContext.DestinationType.IsEnumerable()) { var loopCount = this.GetBindingListInstanceCount(context); var model = (IList)bindingContext.Model; for (var i = 0; i < loopCount; i++) { object genericinstance; if (model.Count > i) { genericinstance = model[i]; } else { genericinstance = Activator.CreateInstance(bindingContext.GenericType); model.Add(genericinstance); } foreach (var modelProperty in bindingContext.ValidModelBindingMembers) { var existingCollectionValue = modelProperty.GetValue(genericinstance); var collectionStringValue = GetValue(modelProperty.Name, bindingContext, i); if (this.BindingValueIsValid(collectionStringValue, existingCollectionValue, modelProperty, bindingContext)) { try { BindValue(modelProperty, collectionStringValue, bindingContext, genericinstance); } catch (PropertyBindingException ex) { bindingExceptions.Add(ex); } } } } } else { foreach (var modelProperty in bindingContext.ValidModelBindingMembers) { var existingValue = modelProperty.GetValue(bindingContext.Model); var stringValue = GetValue(modelProperty.Name, bindingContext); if (this.BindingValueIsValid(stringValue, existingValue, modelProperty, bindingContext)) { try { BindValue(modelProperty, stringValue, bindingContext); } catch (PropertyBindingException ex) { bindingExceptions.Add(ex); } } } } if (bindingExceptions.Any() && !bindingContext.Configuration.IgnoreErrors) { throw new ModelBindingException(modelType, bindingExceptions); } } if (modelType.IsArray()) { var generictoArrayMethod = ToArrayMethodInfo.MakeGenericMethod(new[] { genericType }); return generictoArrayMethod.Invoke(null, new[] { bindingContext.Model }); } return bindingContext.Model; } private bool BindingValueIsValid(string bindingValue, object existingValue, BindingMemberInfo modelProperty, BindingContext bindingContext) { return (!String.IsNullOrEmpty(bindingValue) && (IsDefaultValue(existingValue, modelProperty.PropertyType) || bindingContext.Configuration.Overwrite)); } /// <summary> /// Gets the number of distinct indexes from context: /// /// i.e: /// IntProperty_5 /// StringProperty_5 /// IntProperty_7 /// StringProperty_8 /// You'll end up with a list of 3 matches: 5,7,8 /// /// </summary> /// <param name="context">Current Context </param> /// <returns>An int containing the number of elements</returns> private int GetBindingListInstanceCount(NancyContext context) { var dictionary = context.Request.Form as IDictionary<string, object>; if (dictionary == null) { return 0; } return dictionary.Keys.Select(IsMatch).Where(x => x != -1).Distinct().ToArray().Length; } private static int IsMatch(string item) { var bracketMatch = BracketRegex.Match(item); if (bracketMatch.Success) { return int.Parse(bracketMatch.Groups[1].Value); } var underscoreMatch = UnderscoreRegex.Match(item); if (underscoreMatch.Success) { return int.Parse(underscoreMatch.Groups[1].Value); } return -1; } private static void UpdateModelWithDeserializedModel(object bodyDeserializedModel, BindingContext bindingContext) { var bodyDeserializedModelType = bodyDeserializedModel.GetType(); if (bodyDeserializedModelType.IsValueType) { bindingContext.Model = bodyDeserializedModel; return; } if (bodyDeserializedModelType.IsCollection() || bodyDeserializedModelType.IsEnumerable() || bodyDeserializedModelType.IsArray()) { var count = 0; foreach (var o in (IEnumerable)bodyDeserializedModel) { var model = (IList)bindingContext.Model; if (o.GetType().IsValueType || o is string) { HandleValueTypeCollectionElement(model, count, o); } else { HandleReferenceTypeCollectionElement(bindingContext, model, count, o); } count++; } } else { foreach (var modelProperty in bindingContext.ValidModelBindingMembers) { var existingValue = modelProperty.GetValue(bindingContext.Model); if (IsDefaultValue(existingValue, modelProperty.PropertyType) || bindingContext.Configuration.Overwrite) { CopyValue(modelProperty, bodyDeserializedModel, bindingContext.Model); } } } } private static void HandleValueTypeCollectionElement(IList model, int count, object o) { // If the instance specified in the binder contains the n-th element use that if (model.Count > count) { return; } model.Add(o); } private static void HandleReferenceTypeCollectionElement(BindingContext bindingContext, IList model, int count, object o) { // If the instance specified in the binder contains the n-th element use that otherwise make a new one. object genericTypeInstance; if (model.Count > count) { genericTypeInstance = model[count]; } else { genericTypeInstance = Activator.CreateInstance(bindingContext.GenericType); model.Add(genericTypeInstance); } foreach (var modelProperty in bindingContext.ValidModelBindingMembers) { var existingValue = modelProperty.GetValue(genericTypeInstance); if (IsDefaultValue(existingValue, modelProperty.PropertyType) || bindingContext.Configuration.Overwrite) { CopyValue(modelProperty, o, genericTypeInstance); } } } private static void CopyValue(BindingMemberInfo modelProperty, object source, object destination) { var newValue = modelProperty.GetValue(source); modelProperty.SetValue(destination, newValue); } private static bool IsDefaultValue(object existingValue, Type propertyType) { return propertyType.IsValueType ? Equals(existingValue, Activator.CreateInstance(propertyType)) : existingValue == null; } private BindingContext CreateBindingContext(NancyContext context, Type modelType, object instance, BindingConfig configuration, IEnumerable<string> blackList, Type genericType) { return new BindingContext { Configuration = configuration, Context = context, DestinationType = modelType, Model = CreateModel(modelType, genericType, instance), ValidModelBindingMembers = GetBindingMembers(modelType, genericType, blackList).ToList(), RequestData = this.GetDataFields(context), GenericType = genericType, TypeConverters = this.typeConverters.Concat(this.defaults.DefaultTypeConverters), }; } private IDictionary<string, string> GetDataFields(NancyContext context) { var dictionaries = new IDictionary<string, string>[] { ConvertDynamicDictionary(context.Request.Form), ConvertDynamicDictionary(context.Request.Query), ConvertDynamicDictionary(context.Parameters) }; return dictionaries.Merge(); } private IDictionary<string, string> ConvertDynamicDictionary(DynamicDictionary dictionary) { if (dictionary == null) { return null; } return dictionary.GetDynamicMemberNames().ToDictionary( memberName => this.fieldNameConverter.Convert(memberName), memberName => (string)dictionary[memberName]); } private static void BindValue(BindingMemberInfo modelProperty, string stringValue, BindingContext context) { BindValue(modelProperty, stringValue, context, context.Model); } private static void BindValue(BindingMemberInfo modelProperty, string stringValue, BindingContext context, object targetInstance) { var destinationType = modelProperty.PropertyType; var typeConverter = context.TypeConverters.FirstOrDefault(c => c.CanConvertTo(destinationType, context)); if (typeConverter != null) { try { SetBindingMemberValue(modelProperty, targetInstance, typeConverter.Convert(stringValue, destinationType, context)); } catch (Exception e) { throw new PropertyBindingException(modelProperty.Name, stringValue, e); } } else if (destinationType == typeof(string)) { SetBindingMemberValue(modelProperty, targetInstance, stringValue); } } private static void SetBindingMemberValue(BindingMemberInfo modelProperty, object model, object value) { // TODO - catch reflection exceptions? modelProperty.SetValue(model, value); } private static IEnumerable<BindingMemberInfo> GetBindingMembers(Type modelType, Type genericType, IEnumerable<string> blackList) { var blackListHash = new HashSet<string>(blackList, StringComparer.Ordinal); return BindingMemberInfo.Collect(genericType ?? modelType) .Where(member => !blackListHash.Contains(member.Name)); } private static object CreateModel(Type modelType, Type genericType, object instance) { if (modelType.IsArray() || modelType.IsCollection() || modelType.IsEnumerable()) { //make sure instance has a Add method. Otherwise call `.ToList` if (instance != null && modelType.IsInstanceOfType(instance)) { var addMethod = modelType.GetMethod("Add", BindingFlags.Public | BindingFlags.Instance); if (addMethod != null) { return instance; } var genericMethod = ToListMethodInfo.MakeGenericMethod(genericType); return genericMethod.Invoke(null, new[] { instance }); } //else just make a list var listType = typeof(List<>).MakeGenericType(genericType); return Activator.CreateInstance(listType); } if (instance == null) { return Activator.CreateInstance(modelType, true); } return !modelType.IsInstanceOfType(instance) ? Activator.CreateInstance(modelType, true) : instance; } private static string GetValue(string propertyName, BindingContext context, int index = -1) { if (index != -1) { var indexindexes = context.RequestData.Keys.Select(IsMatch) .Where(i => i != -1) .OrderBy(i => i) .Distinct() .Select((k, i) => new KeyValuePair<int, int>(i, k)) .ToDictionary(k => k.Key, v => v.Value); if (indexindexes.ContainsKey(index)) { var propertyValue = context.RequestData.Where(c => { var indexId = IsMatch(c.Key); return c.Key.StartsWith(propertyName, StringComparison.OrdinalIgnoreCase) && indexId != -1 && indexId == indexindexes[index]; }) .Select(k => k.Value) .FirstOrDefault(); return propertyValue ?? string.Empty; } return string.Empty; } return context.RequestData.ContainsKey(propertyName) ? context.RequestData[propertyName] : string.Empty; } private object DeserializeRequestBody(BindingContext context) { if (context.Context == null || context.Context.Request == null) { return null; } var contentType = GetRequestContentType(context.Context); if (string.IsNullOrEmpty(contentType)) { return null; } var bodyDeserializer = this.bodyDeserializers.FirstOrDefault(b => b.CanDeserialize(contentType, context)) ?? this.defaults.DefaultBodyDeserializers.FirstOrDefault(b => b.CanDeserialize(contentType, context)); return bodyDeserializer != null ? bodyDeserializer.Deserialize(contentType, context.Context.Request.Body, context) : null; } private static string GetRequestContentType(NancyContext context) { if (context == null || context.Request == null) { return String.Empty; } var contentType = context.Request.Headers.ContentType; return (string.IsNullOrEmpty(contentType)) ? string.Empty : contentType; } } }
// // Copyright (c)1998-2011 Pearson Education, Inc. or its affiliate(s). // All rights reserved. // using System; using System.Collections; using System.Reflection; using System.Text; using OpenADK.Library.Tools.Mapping; namespace OpenADK.Library { /// <summary> The default IValueBuilder implementation evaluates an expression to produce /// a string value. /// </summary> /// <remarks> /// <para> /// The IValueBuilder interface is used by the SifDtd, SifDataObject, and Mappings /// classes when evaluating XPath-like query strings. It enables developers to /// customize the way the Adk evaluates value expressions in these query strings /// to produce a value for a SIF element or attribute. The DefaultIValueBuilder /// implementation supports <c>$(variable)</c> token replacement as well as /// <c>@com.class.method</c> style calls to static .Net methods. /// </para> /// <para> /// Token Replacement /// </para> /// <para> /// When a <c>$(variable)</c> token is found in an expression, it is /// replaced with a value from the Map passed to <c>evaluate</c>. For /// example, if the Map constains the entry "color=blue", calling the <c>evaluate</c> /// method with the expression "The color is $(color)" would produce the /// string "The color is blue". /// </para> /// <para> /// .Net Method Calls /// </para> /// <para> /// When a <c>@method( arg1, arg2, ... )</c> call is found in an expression, /// the static .Net method is called and its return value inserted into the value /// string. Token replacement is performed before calling the method. /// If <c>method</c> is not fully-qualified, it is assumed to be a method /// declared by this DefaultIValueBuilder class. The default class can be changed /// by calling the <c>setDefaultClass</c> method. When writing your own /// static method, the first parameter must be of type IValueBuilder; zero or /// more String parameters may follow. The function must return a String: /// <c>String method( IValueBuilder vb, String p1, String p2, ... )</c>. /// </para> /// </remarks> /// <example> /// In the following example, the toUpperCase static method is called to convert /// the $(color) variable to uppercase. This expression would yield the result /// "The color is BLUE": /// <code>The color is @OpenADK.Library.DefaultValueBuilder.ToUpperCase( $(color) )</code> /// </example> public class DefaultValueBuilder : IValueBuilder { /// <summary> Returns the variables Map</summary> /// <returns> The Map passed to the constructor /// </returns> public virtual IFieldAdaptor Data { get { return fVars; } } /// <summary> Specifies the default class for .Net method calls that do not reference /// a fully-qualified class name. <c>OpenADK.Library.DefaultValueBuilder</c> /// is used as the default unless this method is called to change it. /// </summary> /// <value>The name of a class (e.g. "OpenADK.Library.DefaultValueBuilder"). /// <para>This should be the <seealso cref="System.Type.AssemblyQualifiedName">AssemblyQualifiedName</seealso> of the class.</para> /// </value> public static string DefaultClass { set { sDefClass = value; } } private static string sDefClass = typeof ( DefaultValueBuilder ).AssemblyQualifiedName; /// <summary> /// The aliases currently in effect /// </summary> protected internal static IDictionary sAliases; /// <summary> /// The dictionary of variables /// </summary> private IFieldAdaptor fVars; private SifFormatter fFormatter; /// <summary> Constructor</summary> public DefaultValueBuilder( IFieldAdaptor data ) : this( data, Adk.TextFormatter ) {} /// <summary> /// Creates an instance of DefaultValueBuilder that builds values based /// on the SIFDataMap, using the specified <c>SIFFormatter</c> instance /// </summary> /// <param name="data"></param> /// <param name="formatter"></param> public DefaultValueBuilder(IFieldAdaptor data, SifFormatter formatter) { fVars = data; fFormatter = formatter; } /// <summary> Evaluate an expression that the implementation of this interface /// understands to return a String value. /// </summary> /// <param name="expression">The expression to evaluate</param> /// <returns> The value built from the expression</returns> public virtual string Evaluate( string expression ) { return EvaluateCode( ReplaceTokens( expression, fVars ) ); } /// <summary> Calls all .Net methods referenced in the source string to replace the /// method reference with the string representation of the method's return /// value /// </summary> public virtual string EvaluateCode( string src ) { if ( src == null ) { return null; } StringBuilder b = new StringBuilder(); int len = src.Length; int at = 0; int mark = 0; int x = 0; do { at = src.IndexOf( "@", at ); if ( at == - 1 ) { b.Append( src.Substring( mark ) ); at = len; } if ( at < len ) { ParseResults mm = ParseResults.parse( src, at ); if ( mm != null ) { b.Append( src.Substring( mark, (at - mark) ) ); mark = mm.Position; string method = mm.MethodName; MyStringTokenizer myStringTokenizer = mm.Parameters; int methodParamCount = 0; Type targetClass = null; try { x = mm.MethodName.LastIndexOf( (Char) '.' ); if ( x != - 1 ) { // Use the fully-qualified Java method String typeName = method.Substring(0, (x - 0)); targetClass = Type.GetType( typeName ); method = method.Substring( x + 1 ); } else { // Was an alias registered? string aliasClass = (string) sAliases[method]; if ( aliasClass != null ) { targetClass = Type.GetType( aliasClass ); } } if ( targetClass == null ) { targetClass = Type.GetType( sDefClass ); } } catch ( TypeLoadException cnfe ) { throw new SystemException( "Class not found: " + method, cnfe ); } MethodInfo targetMethod = null; MethodInfo [] methods = targetClass.GetMethods( BindingFlags.Static | BindingFlags.Public ); for ( int m = 0; m < methods.Length; m++ ) { if ( methods[m].Name.Equals( method ) ) { targetMethod = methods[m]; methodParamCount = methods[m].GetParameters().Length; break; } } if ( targetMethod == null ) { throw new SystemException( "Method not found: " + method ); } x = 1; Object [] args = new Object[methodParamCount]; args[0] = this; // Assign parameters while ( x < myStringTokenizer.TokenCount + 1 && x < methodParamCount ) { args[x] = myStringTokenizer.GetToken( x - 1 ); x++; } // Fill in any remaining parameters with a blank string value while ( x < methodParamCount ) { args[x++] = ""; } at = mark; try { Object result = targetMethod.Invoke( null, (Object []) args ); if ( result != null ) { b.Append( result.ToString() ); } } catch ( Exception ex ) { throw new SystemException ( "Failed to call method '" + method + "': " + ex.ToString(), ex ); } continue; } b.Append( src.Substring( mark, (len - mark) ) ); at = len; } } while ( at < len ); return b.ToString(); } /// <summary> Replaces all <c>$(variable)</c> tokens in the source string with /// the corresponding entry in the supplied Map /// </summary> /// <param name="src">The source string /// </param> /// <param name="data">The field adaptor to use /// </param> public static string ReplaceTokens( string src, IFieldAdaptor data ) { if ( src == null ) { return null; } StringBuilder b = new StringBuilder(); int len = src.Length; int at = 0; int mark = 0; do { at = src.IndexOf( "$(", at ); if ( at == - 1 ) { at = len; } b.Append( src.Substring( mark, (at - mark) ) ); if ( at < len ) { int i = src.IndexOf( ")", at + 2 ); if ( i != - 1 ) { mark = i + 1; string key = src.Substring( at + 2, i - (at + 2) ); at = mark; object val = data.GetValue(key); if ( val != null ) { b.Append( val ); } } else { b.Append( src.Substring( mark, (len - mark) ) ); at = len; } } } while ( at < len ); return b.ToString(); } //////////////////////////////////////////////////////////////////////////////// /// <summary> "@pad( Source, PadChar, Width )" /// /// Pads the Source string with the specified PadChar character so that the /// source string is at least Width characters in length. If the Source /// string is already equal to or greater than Width, no action is taken. /// </summary> public static string Pad( IValueBuilder vb, string source, string padding, string width ) { try { string _source = source.Trim(); int _width = Int32.Parse( width.ToString().Trim() ); if ( _source.Length >= _width ) { return _source; } string _padding = padding.ToString().Trim(); StringBuilder b = new StringBuilder(); for ( int i = _source.Length; i < _width; i++ ) { b.Append( _padding ); } b.Append( _source ); return b.ToString(); } catch { return source.Trim(); } } /// <summary> "@toUpperCase( Source )" /// /// Converts the source string to uppercase /// </summary> public static string ToUpperCase( IValueBuilder vb, string source ) { try { return source.Trim().ToUpper(); } catch { return source; } } /// <summary> "@toLowerCase( Source )" /// /// Converts the source string to lowercase /// </summary> public static string ToLowerCase( IValueBuilder vb, string source ) { try { return source.Trim().ToLower(); } catch { return source; } } /// <summary> "@toMixedCase( Source )" /// /// Converts the source string to mixed case /// </summary> public static string toMixedCase( IValueBuilder vb, string source ) { try { StringBuilder b = new StringBuilder(); string _source = source.Trim(); for ( int i = 0; i < _source.Length; i++ ) { if ( i == 0 || _source[i - 1] == ' ' ) { b.Append( Char.ToUpper( _source[i] ) ); } else { b.Append( Char.ToLower( _source[i] ) ); } } return b.ToString(); } catch { return source; } } /// <summary> Registers an alias to a static .Net method.</summary> /// <param name="alias">The alias name (e.g. "doSomething") /// </param> /// <param name="method">The fully-qualified .Net method name (e.g. "mycompany.MyValueBuilder.doSomething") /// </param> public static void AddAlias( string alias, string method ) { int i = method.LastIndexOf( "." ); if ( i != - 1 ) { sAliases[alias] = method.Substring( 0, i ); } else { sAliases[alias] = method; } } /// <summary>A StringTokenizer replacement. We need a replacement for two /// reasons: first, the default does not consider empty tokens to be /// tokens. For example, ",,,blue" is considered to have one token, not 4. /// Second, we need to ignore commas in literal strings so that a parameter /// to a method can itself be comprised of delimiters. If a double-quote is /// found, all commas until the next double-quote are considered literal. /// The commas are not included in the resulting tokens. /// </summary> public class MyStringTokenizer { private string [] fTokens; /// <summary> /// Creates an instance of MyStringTokenizer /// </summary> /// <param name="src"></param> /// <param name="delimiter"></param> public MyStringTokenizer( string src, char delimiter ) { // Parse the source string into an array of tokens ArrayList v = new ArrayList( 10 ); if ( src != null ) { int i = 0; bool inQuote = false; StringBuilder token = new StringBuilder(); while ( i < src.Length ) { if ( src[i] == '"' ) { inQuote = !inQuote; } else if ( src[i] == delimiter ) { if ( inQuote ) { token.Append( delimiter ); } else { v.Add( token.ToString() ); token.Length = 0; } } else { token.Append( src[i] ); } i++; } v.Add( token.ToString() ); } fTokens = new string[v.Count]; v.CopyTo( fTokens ); } /// <summary> /// Returns the number of tokens /// </summary> public virtual int TokenCount { get { return fTokens.Length; } } /// <summary> /// Returns the token at the specified index /// </summary> /// <param name="i"></param> /// <returns></returns> public virtual string GetToken( int i ) { return fTokens[i]; } } /// <summary> A helper class to parse "@method( parameterlist )" into .Net method name /// and parameter list, and to return the position in the source string where /// the caller should continue processing. /// </summary> public class ParseResults { /// <summary> /// Position in source string immediately after closing parenthesis /// </summary> public int Position; /// <summary> /// The name of the .Net method /// </summary> public string MethodName; /// <summary> /// The parameters to send to the .Net method /// </summary> public MyStringTokenizer Parameters; /// <summary> Given a source string and an index into that string where a .Net /// method begins (i.e. the location of the @ character), parse the name /// of the .Net method and the list of parameters. Return a new ParseResults /// instance of both components were found, otherwise return null. /// /// For example, if this string were passed: '@random() @strip("(801) 323-1131")', /// and the <i>position</i> parameter were 11, this function would return /// a new ParseResults with Position set to 32, MethodName set to 'strip', /// and Parameters having a single parameter of "(801) 323-1131". /// </summary> public static ParseResults parse( string src, int position ) { ParseResults results = new ParseResults(); int i = position + 1; bool inQuote = false; StringBuilder buf = new StringBuilder(); while ( i < src.Length ) { if ( src[i] == '"' ) { inQuote = !inQuote; } else if ( src[i] == '(' ) { if ( !inQuote ) { results.MethodName = src.Substring( position + 1, i - position - 1 ); buf.Length = 0; } else { buf.Append( '(' ); } } else if ( src[i] == ')' ) { if ( !inQuote ) { results.Parameters = new MyStringTokenizer( buf.ToString(), ',' ); results.Position = i + 1; return results; } else { buf.Append( ')' ); } } else { buf.Append( src[i] ); } i++; } return null; } } static DefaultValueBuilder() { sAliases = new Hashtable(); } } } // Synchronized with DefaultValueBuilder.java
namespace Nancy { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Nancy.Diagnostics; using Bootstrapper; using Nancy.TinyIoc; /// <summary> /// TinyIoC bootstrapper - registers default route resolver and registers itself as /// INancyModuleCatalog for resolving modules but behaviour can be overridden if required. /// </summary> public class DefaultNancyBootstrapper : NancyBootstrapperWithRequestContainerBase<TinyIoCContainer> { /// <summary> /// Default assemblies that are ignored for autoregister /// </summary> public static IEnumerable<Func<Assembly, bool>> DefaultAutoRegisterIgnoredAssemblies = new Func<Assembly, bool>[] { asm => asm.FullName.StartsWith("Microsoft.", StringComparison.InvariantCulture), asm => asm.FullName.StartsWith("System.", StringComparison.InvariantCulture), asm => asm.FullName.StartsWith("System,", StringComparison.InvariantCulture), asm => asm.FullName.StartsWith("CR_ExtUnitTest", StringComparison.InvariantCulture), asm => asm.FullName.StartsWith("mscorlib,", StringComparison.InvariantCulture), asm => asm.FullName.StartsWith("CR_VSTest", StringComparison.InvariantCulture), asm => asm.FullName.StartsWith("DevExpress.CodeRush", StringComparison.InvariantCulture), asm => asm.FullName.StartsWith("IronPython", StringComparison.InvariantCulture), asm => asm.FullName.StartsWith("IronRuby", StringComparison.InvariantCulture), asm => asm.FullName.StartsWith("xunit", StringComparison.InvariantCulture), asm => asm.FullName.StartsWith("Nancy.Testing", StringComparison.InvariantCulture), asm => asm.FullName.StartsWith("MonoDevelop.NUnit", StringComparison.InvariantCulture), asm => asm.FullName.StartsWith("SMDiagnostics", StringComparison.InvariantCulture), asm => asm.FullName.StartsWith("CppCodeProvider", StringComparison.InvariantCulture), asm => asm.FullName.StartsWith("WebDev.WebHost40", StringComparison.InvariantCulture), }; /// <summary> /// Gets the assemblies to ignore when autoregistering the application container /// Return true from the delegate to ignore that particular assembly, returning true /// does not mean the assembly *will* be included, a false from another delegate will /// take precedence. /// </summary> protected virtual IEnumerable<Func<Assembly, bool>> AutoRegisterIgnoredAssemblies { get { return DefaultAutoRegisterIgnoredAssemblies; } } /// <summary> /// Configures the container using AutoRegister followed by registration /// of default INancyModuleCatalog and IRouteResolver. /// </summary> /// <param name="container">Container instance</param> protected override void ConfigureApplicationContainer(TinyIoCContainer container) { AutoRegister(container, this.AutoRegisterIgnoredAssemblies); } /// <summary> /// Resolve INancyEngine /// </summary> /// <returns>INancyEngine implementation</returns> protected override sealed INancyEngine GetEngineInternal() { return this.ApplicationContainer.Resolve<INancyEngine>(); } /// <summary> /// Create a default, unconfigured, container /// </summary> /// <returns>Container instance</returns> protected override TinyIoCContainer GetApplicationContainer() { return new TinyIoCContainer(); } /// <summary> /// Register the bootstrapper's implemented types into the container. /// This is necessary so a user can pass in a populated container but not have /// to take the responsibility of registering things like INancyModuleCatalog manually. /// </summary> /// <param name="applicationContainer">Application container to register into</param> protected override sealed void RegisterBootstrapperTypes(TinyIoCContainer applicationContainer) { applicationContainer.Register<INancyModuleCatalog>(this); } /// <summary> /// Register the default implementations of internally used types into the container as singletons /// </summary> /// <param name="container">Container to register into</param> /// <param name="typeRegistrations">Type registrations to register</param> protected override sealed void RegisterTypes(TinyIoCContainer container, IEnumerable<TypeRegistration> typeRegistrations) { foreach (var typeRegistration in typeRegistrations) { switch (typeRegistration.Lifetime) { case Lifetime.Transient: container.Register(typeRegistration.RegistrationType, typeRegistration.ImplementationType).AsMultiInstance(); break; case Lifetime.Singleton: container.Register(typeRegistration.RegistrationType, typeRegistration.ImplementationType).AsSingleton(); break; case Lifetime.PerRequest: throw new InvalidOperationException("Unable to directly register a per request lifetime."); break; default: throw new ArgumentOutOfRangeException(); } } } /// <summary> /// Register the various collections into the container as singletons to later be resolved /// by IEnumerable{Type} constructor dependencies. /// </summary> /// <param name="container">Container to register into</param> /// <param name="collectionTypeRegistrations">Collection type registrations to register</param> protected override sealed void RegisterCollectionTypes(TinyIoCContainer container, IEnumerable<CollectionTypeRegistration> collectionTypeRegistrations) { foreach (var collectionTypeRegistration in collectionTypeRegistrations) { switch (collectionTypeRegistration.Lifetime) { case Lifetime.Transient: container.RegisterMultiple(collectionTypeRegistration.RegistrationType, collectionTypeRegistration.ImplementationTypes).AsMultiInstance(); break; case Lifetime.Singleton: container.RegisterMultiple(collectionTypeRegistration.RegistrationType, collectionTypeRegistration.ImplementationTypes).AsSingleton(); break; case Lifetime.PerRequest: throw new InvalidOperationException("Unable to directly register a per request lifetime."); break; default: throw new ArgumentOutOfRangeException(); } } } /// <summary> /// Register the given module types into the container /// </summary> /// <param name="container">Container to register into</param> /// <param name="moduleRegistrationTypes">NancyModule types</param> protected override sealed void RegisterRequestContainerModules(TinyIoCContainer container, IEnumerable<ModuleRegistration> moduleRegistrationTypes) { foreach (var moduleRegistrationType in moduleRegistrationTypes) { container.Register( typeof(INancyModule), moduleRegistrationType.ModuleType, moduleRegistrationType.ModuleType.FullName). AsSingleton(); } } /// <summary> /// Register the given instances into the container /// </summary> /// <param name="container">Container to register into</param> /// <param name="instanceRegistrations">Instance registration types</param> protected override void RegisterInstances(TinyIoCContainer container, IEnumerable<InstanceRegistration> instanceRegistrations) { foreach (var instanceRegistration in instanceRegistrations) { container.Register( instanceRegistration.RegistrationType, instanceRegistration.Implementation); } } /// <summary> /// Creates a per request child/nested container /// </summary> /// <param name="context">Current context</param> /// <returns>Request container instance</returns> protected override TinyIoCContainer CreateRequestContainer(NancyContext context) { return this.ApplicationContainer.GetChildContainer(); } /// <summary> /// Gets the diagnostics for initialisation /// </summary> /// <returns>IDiagnostics implementation</returns> protected override IDiagnostics GetDiagnostics() { return this.ApplicationContainer.Resolve<IDiagnostics>(); } /// <summary> /// Gets all registered startup tasks /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IApplicationStartup"/> instances. </returns> protected override IEnumerable<IApplicationStartup> GetApplicationStartupTasks() { return this.ApplicationContainer.ResolveAll<IApplicationStartup>(false); } /// <summary> /// Gets all registered request startup tasks /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IRequestStartup"/> instances.</returns> protected override IEnumerable<IRequestStartup> RegisterAndGetRequestStartupTasks(TinyIoCContainer container, Type[] requestStartupTypes) { container.RegisterMultiple(typeof(IRequestStartup), requestStartupTypes); return container.ResolveAll<IRequestStartup>(false); } /// <summary> /// Gets all registered application registration tasks /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> instance containing <see cref="IRegistrations"/> instances.</returns> protected override IEnumerable<IRegistrations> GetRegistrationTasks() { return this.ApplicationContainer.ResolveAll<IRegistrations>(false); } /// <summary> /// Retrieve all module instances from the container /// </summary> /// <param name="container">Container to use</param> /// <returns>Collection of NancyModule instances</returns> protected override sealed IEnumerable<INancyModule> GetAllModules(TinyIoCContainer container) { var nancyModules = container.ResolveAll<INancyModule>(false); return nancyModules; } /// <summary> /// Retrieve a specific module instance from the container /// </summary> /// <param name="container">Container to use</param> /// <param name="moduleType">Type of the module</param> /// <returns>NancyModule instance</returns> protected override sealed INancyModule GetModule(TinyIoCContainer container, Type moduleType) { container.Register(typeof(INancyModule), moduleType); return container.Resolve<INancyModule>(); } /// <summary> /// Executes auto registation with the given container. /// </summary> /// <param name="container">Container instance</param> private static void AutoRegister(TinyIoCContainer container, IEnumerable<Func<Assembly, bool>> ignoredAssemblies) { var assembly = typeof(NancyEngine).Assembly; container.AutoRegister(AppDomain.CurrentDomain.GetAssemblies().Where(a => !ignoredAssemblies.Any(ia => ia(a))), DuplicateImplementationActions.RegisterMultiple, t => t.Assembly != assembly); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Net.Http; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.Owin; using Microsoft.Owin.Infrastructure; using Microsoft.Owin.Logging; using Microsoft.Owin.Security; using Microsoft.Owin.Security.Infrastructure; using Newtonsoft.Json.Linq; namespace KatanaContrib.Security.Meetup { internal class MeetupAuthenticationHandler : AuthenticationHandler<MeetupAuthenticationOptions> { private const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string"; private const string TokenEndpoint = "https://secure.meetup.com/oauth2/access"; private const string ApiEndpoint = "https://api.meetup.com/members"; private readonly ILogger _logger; private readonly HttpClient _httpClient; public MeetupAuthenticationHandler(HttpClient httpClient, ILogger logger) { _httpClient = httpClient; _logger = logger; } protected override async Task<AuthenticationTicket> AuthenticateCoreAsync() { AuthenticationProperties properties = null; try { string code = null; string state = null; IReadableStringCollection query = Request.Query; IList<string> values = query.GetValues("code"); if (values != null && values.Count == 1) { code = values[0]; } values = query.GetValues("state"); if (values != null && values.Count == 1) { state = values[0]; } //Meetup replaces '_' charactors with spaces in the 'state' parameter when returns. //Resetting it back to it's original string state = state.Replace(' ', '_'); properties = Options.StateDataFormat.Unprotect(state); if (properties == null) { return null; } // OAuth2 10.12 CSRF if (!ValidateCorrelationId(properties, _logger)) { return new AuthenticationTicket(null, properties); } string requestPrefix = Request.Scheme + "://" + Request.Host; string redirectUri = requestPrefix + Request.PathBase + Options.CallbackPath; string tokenRequest = "grant_type=authorization_code" + "&code=" + Uri.EscapeDataString(code) + "&redirect_uri=" + Uri.EscapeDataString(redirectUri) + "&client_id=" + Uri.EscapeDataString(Options.Key) + "&client_secret=" + Uri.EscapeDataString(Options.Secret); //Meetup API requires to send the token request as a POST message. //Initiated a new HttpRequestMessage object to use as a parameter for PostAsync method. HttpRequestMessage request = new HttpRequestMessage(); HttpResponseMessage tokenResponse = await _httpClient.PostAsync(TokenEndpoint + "?" + tokenRequest, request.Content, Request.CallCancelled); tokenResponse.EnsureSuccessStatusCode(); string text = await tokenResponse.Content.ReadAsStringAsync(); //Object is returned as a JSON Object. //Parsing the string contains JSON text to a JSON Object. JObject details = JObject.Parse(text); string accessToken = null; string expires = null; foreach(var x in details) { if(x.Key == "access_token") { accessToken = (string)x.Value; } if(x.Key == "expires_in") { expires = (string)x.Value; } } HttpResponseMessage apiResponse = await _httpClient.GetAsync( ApiEndpoint + "?access_token=" + Uri.EscapeDataString(accessToken) + "&member_id=self" + "&key=" + Uri.EscapeDataString(Options.Key), Request.CallCancelled); apiResponse.EnsureSuccessStatusCode(); text = await apiResponse.Content.ReadAsStringAsync(); //Convert JSON string to a JSON Object JObject info = JObject.Parse(text); //Extract the 'results' JToken from info JToken results = info["results"]; JToken userinfo = results.First; JObject user = userinfo as JObject; var context = new MeetupAuthenticatedContext(Context, user, accessToken, expires); context.Identity = new ClaimsIdentity( Options.AuthenticationType, ClaimsIdentity.DefaultNameClaimType, ClaimsIdentity.DefaultRoleClaimType); if (!string.IsNullOrEmpty(context.Id)) { context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, context.Id, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Name)) { context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, context.Name, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.City)) { context.Identity.AddClaim(new Claim("urn:meetup:city", context.City, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Country)) { context.Identity.AddClaim(new Claim(ClaimTypes.Country, context.Country, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.Link)) { context.Identity.AddClaim(new Claim("urn:meetup:link", context.Link, XmlSchemaString, Options.AuthenticationType)); } if(!string.IsNullOrEmpty(context.Joined)) { context.Identity.AddClaim(new Claim("urn:meetup:joined", context.Joined, XmlSchemaString, Options.AuthenticationType)); } if (!string.IsNullOrEmpty(context.PhotoUrl)) { context.Identity.AddClaim(new Claim("urn:meetup:photourl", context.PhotoUrl, XmlSchemaString, Options.AuthenticationType)); } context.Properties = properties; await Options.Provider.Authenticated(context); return new AuthenticationTicket(context.Identity, context.Properties); } catch (Exception ex) { _logger.WriteError(ex.Message); } return new AuthenticationTicket(null, properties); } protected override Task ApplyResponseChallengeAsync() { if (Response.StatusCode != 401) { return Task.FromResult<object>(null); } AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode); if (challenge != null) { string baseUri = Request.Scheme + Uri.SchemeDelimiter + Request.Host + Request.PathBase; string currentUri = baseUri + Request.Path + Request.QueryString; string redirectUri = baseUri + Options.CallbackPath; AuthenticationProperties properties = challenge.Properties; if (string.IsNullOrEmpty(properties.RedirectUri)) { properties.RedirectUri = currentUri; } // OAuth2 10.12 CSRF GenerateCorrelationId(properties); string scope = string.Join(",", Options.Scope); string state = Options.StateDataFormat.Protect(properties); string authorizationEndpoint = "https://secure.meetup.com/oauth2/authorize" + "?response_type=code" + "&client_id=" + Uri.EscapeDataString(Options.Key) + "&redirect_uri=" + Uri.EscapeDataString(redirectUri) + "&scope=" + Uri.EscapeDataString(scope) + "&state=" + Uri.EscapeDataString(state); Response.Redirect(authorizationEndpoint); } return Task.FromResult<object>(null); } public override async Task<bool> InvokeAsync() { return await InvokeReplyPathAsync(); } private async Task<bool> InvokeReplyPathAsync() { if (Options.CallbackPath.HasValue && Options.CallbackPath == Request.Path) { // TODO: error responses AuthenticationTicket ticket = await AuthenticateAsync(); if (ticket == null) { _logger.WriteWarning("Invalid return state, unable to redirect."); Response.StatusCode = 500; return true; } var context = new MeetupReturnEndpointContext(Context, ticket); context.SignInAsAuthenticationType = Options.SignInAsAuthenticationType; context.RedirectUri = ticket.Properties.RedirectUri; await Options.Provider.ReturnEndpoint(context); if (context.SignInAsAuthenticationType != null && context.Identity != null) { ClaimsIdentity grantIdentity = context.Identity; if (!string.Equals(grantIdentity.AuthenticationType, context.SignInAsAuthenticationType, StringComparison.Ordinal)) { grantIdentity = new ClaimsIdentity(grantIdentity.Claims, context.SignInAsAuthenticationType, grantIdentity.NameClaimType, grantIdentity.RoleClaimType); } Context.Authentication.SignIn(context.Properties, grantIdentity); } if (!context.IsRequestCompleted && context.RedirectUri != null) { string redirectUri = context.RedirectUri; if (context.Identity == null) { // add a redirect hint that sign-in failed in some way redirectUri = WebUtilities.AddQueryString(redirectUri, "error", "access_denied"); } Response.Redirect(redirectUri); context.RequestCompleted(); } return context.IsRequestCompleted; } return false; } } }
// dnlib: See LICENSE.txt for more info using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading; using dnlib.DotNet.MD; using dnlib.DotNet.Pdb; using dnlib.Threading; namespace dnlib.DotNet { /// <summary> /// A high-level representation of a row in the Param table /// </summary> [DebuggerDisplay("{Sequence} {Name}")] public abstract class ParamDef : IHasConstant, IHasCustomAttribute, IHasFieldMarshal, IHasCustomDebugInformation { /// <summary> /// The row id in its table /// </summary> protected uint rid; #if THREAD_SAFE readonly Lock theLock = Lock.Create(); #endif /// <inheritdoc/> public MDToken MDToken => new MDToken(Table.Param, rid); /// <inheritdoc/> public uint Rid { get => rid; set => rid = value; } /// <inheritdoc/> public int HasConstantTag => 1; /// <inheritdoc/> public int HasCustomAttributeTag => 4; /// <inheritdoc/> public int HasFieldMarshalTag => 1; /// <summary> /// Gets the declaring method /// </summary> public MethodDef DeclaringMethod { get => declaringMethod; internal set => declaringMethod = value; } /// <summary/> protected MethodDef declaringMethod; /// <summary> /// From column Param.Flags /// </summary> public ParamAttributes Attributes { get => (ParamAttributes)attributes; set => attributes = (int)value; } /// <summary>Attributes</summary> protected int attributes; /// <summary> /// From column Param.Sequence /// </summary> public ushort Sequence { get => sequence; set => sequence = value; } /// <summary/> protected ushort sequence; /// <summary> /// From column Param.Name /// </summary> public UTF8String Name { get => name; set => name = value; } /// <summary>Name</summary> protected UTF8String name; /// <inheritdoc/> public MarshalType MarshalType { get { if (!marshalType_isInitialized) InitializeMarshalType(); return marshalType; } set { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif marshalType = value; marshalType_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } } /// <summary/> protected MarshalType marshalType; /// <summary/> protected bool marshalType_isInitialized; void InitializeMarshalType() { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif if (marshalType_isInitialized) return; marshalType = GetMarshalType_NoLock(); marshalType_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } /// <summary>Called to initialize <see cref="marshalType"/></summary> protected virtual MarshalType GetMarshalType_NoLock() => null; /// <summary>Reset <see cref="MarshalType"/></summary> protected void ResetMarshalType() => marshalType_isInitialized = false; /// <inheritdoc/> public Constant Constant { get { if (!constant_isInitialized) InitializeConstant(); return constant; } set { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif constant = value; constant_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } } /// <summary/> protected Constant constant; /// <summary/> protected bool constant_isInitialized; void InitializeConstant() { #if THREAD_SAFE theLock.EnterWriteLock(); try { #endif if (constant_isInitialized) return; constant = GetConstant_NoLock(); constant_isInitialized = true; #if THREAD_SAFE } finally { theLock.ExitWriteLock(); } #endif } /// <summary>Called to initialize <see cref="constant"/></summary> protected virtual Constant GetConstant_NoLock() => null; /// <summary>Reset <see cref="Constant"/></summary> protected void ResetConstant() => constant_isInitialized = false; /// <summary> /// Gets all custom attributes /// </summary> public CustomAttributeCollection CustomAttributes { get { if (customAttributes is null) InitializeCustomAttributes(); return customAttributes; } } /// <summary/> protected CustomAttributeCollection customAttributes; /// <summary>Initializes <see cref="customAttributes"/></summary> protected virtual void InitializeCustomAttributes() => Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null); /// <inheritdoc/> public bool HasCustomAttributes => CustomAttributes.Count > 0; /// <inheritdoc/> public int HasCustomDebugInformationTag => 4; /// <inheritdoc/> public bool HasCustomDebugInfos => CustomDebugInfos.Count > 0; /// <summary> /// Gets all custom debug infos /// </summary> public IList<PdbCustomDebugInfo> CustomDebugInfos { get { if (customDebugInfos is null) InitializeCustomDebugInfos(); return customDebugInfos; } } /// <summary/> protected IList<PdbCustomDebugInfo> customDebugInfos; /// <summary>Initializes <see cref="customDebugInfos"/></summary> protected virtual void InitializeCustomDebugInfos() => Interlocked.CompareExchange(ref customDebugInfos, new List<PdbCustomDebugInfo>(), null); /// <summary> /// <c>true</c> if <see cref="Constant"/> is not <c>null</c> /// </summary> public bool HasConstant => Constant is not null; /// <summary> /// Gets the constant element type or <see cref="dnlib.DotNet.ElementType.End"/> if there's no constant /// </summary> public ElementType ElementType { get { var c = Constant; return c is null ? ElementType.End : c.Type; } } /// <summary> /// <c>true</c> if <see cref="MarshalType"/> is not <c>null</c> /// </summary> public bool HasMarshalType => MarshalType is not null; /// <inheritdoc/> public string FullName { get { var n = name; if (UTF8String.IsNullOrEmpty(n)) return $"A_{sequence}"; return n.String; } } /// <summary> /// Set or clear flags in <see cref="attributes"/> /// </summary> /// <param name="set"><c>true</c> if flags should be set, <c>false</c> if flags should /// be cleared</param> /// <param name="flags">Flags to set or clear</param> void ModifyAttributes(bool set, ParamAttributes flags) { if (set) attributes |= (int)flags; else attributes &= ~(int)flags; } /// <summary> /// Gets/sets the <see cref="ParamAttributes.In"/> bit /// </summary> public bool IsIn { get => ((ParamAttributes)attributes & ParamAttributes.In) != 0; set => ModifyAttributes(value, ParamAttributes.In); } /// <summary> /// Gets/sets the <see cref="ParamAttributes.Out"/> bit /// </summary> public bool IsOut { get => ((ParamAttributes)attributes & ParamAttributes.Out) != 0; set => ModifyAttributes(value, ParamAttributes.Out); } /// <summary> /// Gets/sets the <see cref="ParamAttributes.Lcid"/> bit /// </summary> public bool IsLcid { get => ((ParamAttributes)attributes & ParamAttributes.Lcid) != 0; set => ModifyAttributes(value, ParamAttributes.Lcid); } /// <summary> /// Gets/sets the <see cref="ParamAttributes.Retval"/> bit /// </summary> public bool IsRetval { get => ((ParamAttributes)attributes & ParamAttributes.Retval) != 0; set => ModifyAttributes(value, ParamAttributes.Retval); } /// <summary> /// Gets/sets the <see cref="ParamAttributes.Optional"/> bit /// </summary> public bool IsOptional { get => ((ParamAttributes)attributes & ParamAttributes.Optional) != 0; set => ModifyAttributes(value, ParamAttributes.Optional); } /// <summary> /// Gets/sets the <see cref="ParamAttributes.HasDefault"/> bit /// </summary> public bool HasDefault { get => ((ParamAttributes)attributes & ParamAttributes.HasDefault) != 0; set => ModifyAttributes(value, ParamAttributes.HasDefault); } /// <summary> /// Gets/sets the <see cref="ParamAttributes.HasFieldMarshal"/> bit /// </summary> public bool HasFieldMarshal { get => ((ParamAttributes)attributes & ParamAttributes.HasFieldMarshal) != 0; set => ModifyAttributes(value, ParamAttributes.HasFieldMarshal); } } /// <summary> /// A Param row created by the user and not present in the original .NET file /// </summary> public class ParamDefUser : ParamDef { /// <summary> /// Default constructor /// </summary> public ParamDefUser() { } /// <summary> /// Constructor /// </summary> /// <param name="name">Name</param> public ParamDefUser(UTF8String name) : this(name, 0) { } /// <summary> /// Constructor /// </summary> /// <param name="name">Name</param> /// <param name="sequence">Sequence</param> public ParamDefUser(UTF8String name, ushort sequence) : this(name, sequence, 0) { } /// <summary> /// Constructor /// </summary> /// <param name="name">Name</param> /// <param name="sequence">Sequence</param> /// <param name="flags">Flags</param> public ParamDefUser(UTF8String name, ushort sequence, ParamAttributes flags) { this.name = name; this.sequence = sequence; attributes = (int)flags; } } /// <summary> /// Created from a row in the Param table /// </summary> sealed class ParamDefMD : ParamDef, IMDTokenProviderMD { /// <summary>The module where this instance is located</summary> readonly ModuleDefMD readerModule; readonly uint origRid; /// <inheritdoc/> public uint OrigRid => origRid; /// <inheritdoc/> protected override MarshalType GetMarshalType_NoLock() => readerModule.ReadMarshalType(Table.Param, origRid, GenericParamContext.Create(declaringMethod)); /// <inheritdoc/> protected override Constant GetConstant_NoLock() => readerModule.ResolveConstant(readerModule.Metadata.GetConstantRid(Table.Param, origRid)); /// <inheritdoc/> protected override void InitializeCustomAttributes() { var list = readerModule.Metadata.GetCustomAttributeRidList(Table.Param, origRid); var tmp = new CustomAttributeCollection(list.Count, list, (list2, index) => readerModule.ReadCustomAttribute(list[index])); Interlocked.CompareExchange(ref customAttributes, tmp, null); } /// <inheritdoc/> protected override void InitializeCustomDebugInfos() { var list = new List<PdbCustomDebugInfo>(); readerModule.InitializeCustomDebugInfos(new MDToken(MDToken.Table, origRid), GenericParamContext.Create(declaringMethod), list); Interlocked.CompareExchange(ref customDebugInfos, list, null); } /// <summary> /// Constructor /// </summary> /// <param name="readerModule">The module which contains this <c>Param</c> row</param> /// <param name="rid">Row ID</param> /// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception> /// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception> public ParamDefMD(ModuleDefMD readerModule, uint rid) { #if DEBUG if (readerModule is null) throw new ArgumentNullException("readerModule"); if (readerModule.TablesStream.ParamTable.IsInvalidRID(rid)) throw new BadImageFormatException($"Param rid {rid} does not exist"); #endif origRid = rid; this.rid = rid; this.readerModule = readerModule; bool b = readerModule.TablesStream.TryReadParamRow(origRid, out var row); Debug.Assert(b); attributes = row.Flags; sequence = row.Sequence; name = readerModule.StringsStream.ReadNoNull(row.Name); declaringMethod = readerModule.GetOwner(this); } internal ParamDefMD InitializeAll() { MemberMDInitializer.Initialize(DeclaringMethod); MemberMDInitializer.Initialize(Attributes); MemberMDInitializer.Initialize(Sequence); MemberMDInitializer.Initialize(Name); MemberMDInitializer.Initialize(MarshalType); MemberMDInitializer.Initialize(Constant); MemberMDInitializer.Initialize(CustomAttributes); return this; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; using Environment = System.Environment; namespace LibGit2Sharp { /// <summary> /// Show changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, or changes between two files on disk. /// <para> /// Copied and renamed files currently cannot be detected, as the feature is not supported by libgit2 yet. /// These files will be shown as a pair of Deleted/Added files.</para> /// </summary> public class Diff { private readonly Repository repo; private static GitDiffOptions BuildOptions(DiffModifiers diffOptions, FilePath[] filePaths = null, MatchedPathsAggregator matchedPathsAggregator = null, CompareOptions compareOptions = null) { var options = new GitDiffOptions(); options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_TYPECHANGE; compareOptions = compareOptions ?? new CompareOptions(); options.ContextLines = (ushort)compareOptions.ContextLines; options.InterhunkLines = (ushort)compareOptions.InterhunkLines; if (diffOptions.HasFlag(DiffModifiers.IncludeUntracked)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNTRACKED | GitDiffOptionFlags.GIT_DIFF_RECURSE_UNTRACKED_DIRS | GitDiffOptionFlags.GIT_DIFF_SHOW_UNTRACKED_CONTENT; } if (diffOptions.HasFlag(DiffModifiers.IncludeIgnored)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_IGNORED | GitDiffOptionFlags.GIT_DIFF_RECURSE_IGNORED_DIRS; } if (diffOptions.HasFlag(DiffModifiers.IncludeUnmodified) || compareOptions.IncludeUnmodified || (compareOptions.Similarity != null && (compareOptions.Similarity.RenameDetectionMode == RenameDetectionMode.CopiesHarder || compareOptions.Similarity.RenameDetectionMode == RenameDetectionMode.Exact))) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNMODIFIED; } if (diffOptions.HasFlag(DiffModifiers.DisablePathspecMatch)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_DISABLE_PATHSPEC_MATCH; } if (matchedPathsAggregator != null) { options.NotifyCallback = matchedPathsAggregator.OnGitDiffNotify; } if (filePaths == null) { return options; } options.PathSpec = GitStrArrayIn.BuildFrom(filePaths); return options; } /// <summary> /// Needed for mocking purposes. /// </summary> protected Diff() { } internal Diff(Repository repo) { this.repo = repo; } private static readonly IDictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>> HandleRetrieverDispatcher = BuildHandleRetrieverDispatcher(); private static IDictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>> BuildHandleRetrieverDispatcher() { return new Dictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>> { { DiffTargets.Index, IndexToTree }, { DiffTargets.WorkingDirectory, WorkdirToTree }, { DiffTargets.Index | DiffTargets.WorkingDirectory, WorkdirAndIndexToTree }, }; } private static readonly IDictionary<Type, Func<DiffSafeHandle, object>> ChangesBuilders = new Dictionary<Type, Func<DiffSafeHandle, object>> { { typeof(Patch), diff => new Patch(diff) }, { typeof(TreeChanges), diff => new TreeChanges(diff) }, { typeof(PatchStats), diff => new PatchStats(diff) }, }; /// <summary> /// Show changes between two <see cref="Blob"/>s. /// </summary> /// <param name="oldBlob">The <see cref="Blob"/> you want to compare from.</param> /// <param name="newBlob">The <see cref="Blob"/> you want to compare to.</param> /// <param name="compareOptions">Additional options to define comparison behavior.</param> /// <returns>A <see cref="ContentChanges"/> containing the changes between the <paramref name="oldBlob"/> and the <paramref name="newBlob"/>.</returns> public virtual ContentChanges Compare(Blob oldBlob, Blob newBlob, CompareOptions compareOptions = null) { using (GitDiffOptions options = BuildOptions(DiffModifiers.None, compareOptions: compareOptions)) { return new ContentChanges(repo, oldBlob, newBlob, options); } } /// <summary> /// Show changes between two <see cref="Tree"/>s. /// </summary> /// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param> /// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <param name="explicitPathsOptions"> /// If set, the passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> /// <param name="compareOptions">Additional options to define patch generation behavior.</param> /// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns> public virtual T Compare<T>(Tree oldTree, Tree newTree, IEnumerable<string> paths = null, ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) where T : class { Func<DiffSafeHandle, object> builder; if (!ChangesBuilders.TryGetValue(typeof (T), out builder)) { throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unexpected type '{0}' passed to Compare. Supported values are either '{1}' or '{2}'.", typeof (T), typeof (TreeChanges), typeof (Patch))); } var comparer = TreeToTree(repo); ObjectId oldTreeId = oldTree != null ? oldTree.Id : null; ObjectId newTreeId = newTree != null ? newTree.Id : null; var diffOptions = DiffModifiers.None; if (explicitPathsOptions != null) { diffOptions |= DiffModifiers.DisablePathspecMatch; if (explicitPathsOptions.ShouldFailOnUnmatchedPath || explicitPathsOptions.OnUnmatchedPath != null) { diffOptions |= DiffModifiers.IncludeUnmodified; } } using (DiffSafeHandle diff = BuildDiffList(oldTreeId, newTreeId, comparer, diffOptions, paths, explicitPathsOptions, compareOptions)) { return (T)builder(diff); } } /// <summary> /// Show changes between a <see cref="Tree"/> and the Index, the Working Directory, or both. /// <para> /// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/> /// or <see cref="Patch"/> type as the generic parameter. /// </para> /// </summary> /// <param name="oldTree">The <see cref="Tree"/> to compare from.</param> /// <param name="diffTargets">The targets to compare to.</param> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <param name="explicitPathsOptions"> /// If set, the passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> /// <param name="compareOptions">Additional options to define patch generation behavior.</param> /// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or /// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam> /// <returns>A <typeparamref name="T"/> containing the changes between the <see cref="Tree"/> and the selected target.</returns> public virtual T Compare<T>(Tree oldTree, DiffTargets diffTargets, IEnumerable<string> paths = null, ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) where T : class { Func<DiffSafeHandle, object> builder; if (!ChangesBuilders.TryGetValue(typeof (T), out builder)) { throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unexpected type '{0}' passed to Compare. Supported values are either '{1}' or '{2}'.", typeof (T), typeof (TreeChanges), typeof (Patch))); } var comparer = HandleRetrieverDispatcher[diffTargets](repo); ObjectId oldTreeId = oldTree != null ? oldTree.Id : null; DiffModifiers diffOptions = diffTargets.HasFlag(DiffTargets.WorkingDirectory) ? DiffModifiers.IncludeUntracked : DiffModifiers.None; if (explicitPathsOptions != null) { diffOptions |= DiffModifiers.DisablePathspecMatch; if (explicitPathsOptions.ShouldFailOnUnmatchedPath || explicitPathsOptions.OnUnmatchedPath != null) { diffOptions |= DiffModifiers.IncludeUnmodified; } } using (DiffSafeHandle diff = BuildDiffList(oldTreeId, null, comparer, diffOptions, paths, explicitPathsOptions, compareOptions)) { return (T)builder(diff); } } /// <summary> /// Show changes between the working directory and the index. /// <para> /// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/> /// or <see cref="Patch"/> type as the generic parameter. /// </para> /// </summary> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <param name="includeUntracked">If true, include untracked files from the working dir as additions. Otherwise ignore them.</param> /// <param name="explicitPathsOptions"> /// If set, the passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> /// <param name="compareOptions">Additional options to define patch generation behavior.</param> /// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or /// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam> /// <returns>A <typeparamref name="T"/> containing the changes between the working directory and the index.</returns> public virtual T Compare<T>(IEnumerable<string> paths = null, bool includeUntracked = false, ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) where T : class { return Compare<T>(includeUntracked ? DiffModifiers.IncludeUntracked : DiffModifiers.None, paths, explicitPathsOptions); } internal virtual T Compare<T>(DiffModifiers diffOptions, IEnumerable<string> paths = null, ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) where T : class { Func<DiffSafeHandle, object> builder; if (!ChangesBuilders.TryGetValue(typeof (T), out builder)) { throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unexpected type '{0}' passed to Compare. Supported values are either '{1}' or '{2}'.", typeof (T), typeof (TreeChanges), typeof (Patch))); } var comparer = WorkdirToIndex(repo); if (explicitPathsOptions != null) { diffOptions |= DiffModifiers.DisablePathspecMatch; if (explicitPathsOptions.ShouldFailOnUnmatchedPath || explicitPathsOptions.OnUnmatchedPath != null) { diffOptions |= DiffModifiers.IncludeUnmodified; } } using (DiffSafeHandle diff = BuildDiffList(null, null, comparer, diffOptions, paths, explicitPathsOptions, compareOptions)) { return (T)builder(diff); } } internal delegate DiffSafeHandle TreeComparisonHandleRetriever(ObjectId oldTreeId, ObjectId newTreeId, GitDiffOptions options); private static TreeComparisonHandleRetriever TreeToTree(Repository repo) { return (oh, nh, o) => Proxy.git_diff_tree_to_tree(repo.Handle, oh, nh, o); } private static TreeComparisonHandleRetriever WorkdirToIndex(Repository repo) { return (oh, nh, o) => Proxy.git_diff_index_to_workdir(repo.Handle, repo.Index.Handle, o); } private static TreeComparisonHandleRetriever WorkdirToTree(Repository repo) { return (oh, nh, o) => Proxy.git_diff_tree_to_workdir(repo.Handle, oh, o); } private static TreeComparisonHandleRetriever WorkdirAndIndexToTree(Repository repo) { TreeComparisonHandleRetriever comparisonHandleRetriever = (oh, nh, o) => { DiffSafeHandle diff = null, diff2 = null; try { diff = Proxy.git_diff_tree_to_index(repo.Handle, repo.Index.Handle, oh, o); diff2 = Proxy.git_diff_index_to_workdir(repo.Handle, repo.Index.Handle, o); Proxy.git_diff_merge(diff, diff2); } catch { diff.SafeDispose(); throw; } finally { diff2.SafeDispose(); } return diff; }; return comparisonHandleRetriever; } private static TreeComparisonHandleRetriever IndexToTree(Repository repo) { return (oh, nh, o) => Proxy.git_diff_tree_to_index(repo.Handle, repo.Index.Handle, oh, o); } private DiffSafeHandle BuildDiffList(ObjectId oldTreeId, ObjectId newTreeId, TreeComparisonHandleRetriever comparisonHandleRetriever, DiffModifiers diffOptions, IEnumerable<string> paths, ExplicitPathsOptions explicitPathsOptions, CompareOptions compareOptions) { var matchedPaths = new MatchedPathsAggregator(); var filePaths = repo.ToFilePaths(paths); using (GitDiffOptions options = BuildOptions(diffOptions, filePaths, matchedPaths, compareOptions)) { var diffList = comparisonHandleRetriever(oldTreeId, newTreeId, options); try { if (explicitPathsOptions != null) { DispatchUnmatchedPaths(explicitPathsOptions, filePaths, matchedPaths); } } catch { diffList.Dispose(); throw; } DetectRenames(diffList, compareOptions); return diffList; } } private static void DetectRenames(DiffSafeHandle diffList, CompareOptions compareOptions) { var similarityOptions = (compareOptions == null) ? null : compareOptions.Similarity; if (similarityOptions == null || similarityOptions.RenameDetectionMode == RenameDetectionMode.Default) { Proxy.git_diff_find_similar(diffList, null); return; } if (similarityOptions.RenameDetectionMode == RenameDetectionMode.None) { return; } var opts = new GitDiffFindOptions { RenameThreshold = (ushort)similarityOptions.RenameThreshold, RenameFromRewriteThreshold = (ushort)similarityOptions.RenameFromRewriteThreshold, CopyThreshold = (ushort)similarityOptions.CopyThreshold, BreakRewriteThreshold = (ushort)similarityOptions.BreakRewriteThreshold, RenameLimit = (UIntPtr)similarityOptions.RenameLimit, }; switch (similarityOptions.RenameDetectionMode) { case RenameDetectionMode.Exact: opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_EXACT_MATCH_ONLY | GitDiffFindFlags.GIT_DIFF_FIND_RENAMES | GitDiffFindFlags.GIT_DIFF_FIND_COPIES | GitDiffFindFlags.GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED; break; case RenameDetectionMode.Renames: opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES; break; case RenameDetectionMode.Copies: opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES | GitDiffFindFlags.GIT_DIFF_FIND_COPIES; break; case RenameDetectionMode.CopiesHarder: opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES | GitDiffFindFlags.GIT_DIFF_FIND_COPIES | GitDiffFindFlags.GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED; break; } if (!compareOptions.IncludeUnmodified) { opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_REMOVE_UNMODIFIED; } switch (similarityOptions.WhitespaceMode) { case WhitespaceMode.DontIgnoreWhitespace: opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_DONT_IGNORE_WHITESPACE; break; case WhitespaceMode.IgnoreLeadingWhitespace: opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_IGNORE_LEADING_WHITESPACE; break; case WhitespaceMode.IgnoreAllWhitespace: opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_IGNORE_WHITESPACE; break; } Proxy.git_diff_find_similar(diffList, opts); } private static void DispatchUnmatchedPaths(ExplicitPathsOptions explicitPathsOptions, IEnumerable<FilePath> filePaths, IEnumerable<FilePath> matchedPaths) { List<FilePath> unmatchedPaths = (filePaths != null ? filePaths.Except(matchedPaths) : Enumerable.Empty<FilePath>()).ToList(); if (!unmatchedPaths.Any()) { return; } if (explicitPathsOptions.OnUnmatchedPath != null) { unmatchedPaths.ForEach(filePath => explicitPathsOptions.OnUnmatchedPath(filePath.Native)); } if (explicitPathsOptions.ShouldFailOnUnmatchedPath) { throw new UnmatchedPathException(BuildUnmatchedPathsMessage(unmatchedPaths)); } } private static string BuildUnmatchedPathsMessage(List<FilePath> unmatchedPaths) { var message = new StringBuilder("There were some unmatched paths:" + Environment.NewLine); unmatchedPaths.ForEach(filePath => message.AppendFormat("- {0}{1}", filePath.Native, Environment.NewLine)); return message.ToString(); } } }
// 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.IO; using System.Text; using System.Collections.Generic; using System.Globalization; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.Build.Tasks.Hosting; using Microsoft.CodeAnalysis.CompilerServer; using System.Diagnostics; namespace Microsoft.CodeAnalysis.BuildTasks { /// <summary> /// This class defines the "Vbc" XMake task, which enables building assemblies from VB /// source files by invoking the VB compiler. This is the new Roslyn XMake task, /// meaning that the code is compiled by using the Roslyn compiler server, rather /// than vbc.exe. The two should be functionally identical, but the compiler server /// should be significantly faster with larger projects and have a smaller memory /// footprint. /// </summary> public class Vbc : ManagedCompiler { private bool _useHostCompilerIfAvailable; // The following 1 fields are used, set and re-set in LogEventsFromTextOutput() /// <summary> /// This stores the original lines and error priority together in the order in which they were received. /// </summary> private readonly Queue<VBError> _vbErrorLines = new Queue<VBError>(); // Used when parsing vbc output to determine the column number of an error private bool _isDoneOutputtingErrorMessage; private int _numberOfLinesInErrorMessage; #region Properties // Please keep these alphabetized. These are the parameters specific to Vbc. The // ones shared between Vbc and Csc are defined in ManagedCompiler.cs, which is // the base class. public string BaseAddress { set { _store[nameof(BaseAddress)] = value; } get { return (string)_store[nameof(BaseAddress)]; } } public string DisabledWarnings { set { _store[nameof(DisabledWarnings)] = value; } get { return (string)_store[nameof(DisabledWarnings)]; } } public string DocumentationFile { set { _store[nameof(DocumentationFile)] = value; } get { return (string)_store[nameof(DocumentationFile)]; } } public string ErrorReport { set { _store[nameof(ErrorReport)] = value; } get { return (string)_store[nameof(ErrorReport)]; } } public bool GenerateDocumentation { set { _store[nameof(GenerateDocumentation)] = value; } get { return _store.GetOrDefault(nameof(GenerateDocumentation), false); } } public ITaskItem[] Imports { set { _store[nameof(Imports)] = value; } get { return (ITaskItem[])_store[nameof(Imports)]; } } public string LangVersion { set { _store[nameof(LangVersion)] = value; } get { return (string)_store[nameof(LangVersion)]; } } public string ModuleAssemblyName { set { _store[nameof(ModuleAssemblyName)] = value; } get { return (string)_store[nameof(ModuleAssemblyName)]; } } public bool NoStandardLib { set { _store[nameof(NoStandardLib)] = value; } get { return _store.GetOrDefault(nameof(NoStandardLib), false); } } // This is not a documented switch. It prevents the automatic reference to Microsoft.VisualBasic.dll. // The VB team believes the only scenario for this is when you are building that assembly itself. // We have to support the switch here so that we can build the SDE and VB trees, which need to build this assembly. // Although undocumented, it cannot be wrapped with #if BUILDING_DF_LKG because this would prevent dogfood builds // within VS, which must use non-LKG msbuild bits. public bool NoVBRuntimeReference { set { _store[nameof(NoVBRuntimeReference)] = value; } get { return _store.GetOrDefault(nameof(NoVBRuntimeReference), false); } } public bool NoWarnings { set { _store[nameof(NoWarnings)] = value; } get { return _store.GetOrDefault(nameof(NoWarnings), false); } } public string OptionCompare { set { _store[nameof(OptionCompare)] = value; } get { return (string)_store[nameof(OptionCompare)]; } } public bool OptionExplicit { set { _store[nameof(OptionExplicit)] = value; } get { return _store.GetOrDefault(nameof(OptionExplicit), true); } } public bool OptionStrict { set { _store[nameof(OptionStrict)] = value; } get { return _store.GetOrDefault(nameof(OptionStrict), false); } } public bool OptionInfer { set { _store[nameof(OptionInfer)] = value; } get { return _store.GetOrDefault(nameof(OptionInfer), false); } } // Currently only /optionstrict:custom public string OptionStrictType { set { _store[nameof(OptionStrictType)] = value; } get { return (string)_store[nameof(OptionStrictType)]; } } public bool RemoveIntegerChecks { set { _store[nameof(RemoveIntegerChecks)] = value; } get { return _store.GetOrDefault(nameof(RemoveIntegerChecks), false); } } public string RootNamespace { set { _store[nameof(RootNamespace)] = value; } get { return (string)_store[nameof(RootNamespace)]; } } public string SdkPath { set { _store[nameof(SdkPath)] = value; } get { return (string)_store[nameof(SdkPath)]; } } /// <summary> /// Name of the language passed to "/preferreduilang" compiler option. /// </summary> /// <remarks> /// If set to null, "/preferreduilang" option is omitted, and vbc.exe uses its default setting. /// Otherwise, the value is passed to "/preferreduilang" as is. /// </remarks> public string PreferredUILang { set { _store[nameof(PreferredUILang)] = value; } get { return (string)_store[nameof(PreferredUILang)]; } } public string VsSessionGuid { set { _store[nameof(VsSessionGuid)] = value; } get { return (string)_store[nameof(VsSessionGuid)]; } } public bool TargetCompactFramework { set { _store[nameof(TargetCompactFramework)] = value; } get { return _store.GetOrDefault(nameof(TargetCompactFramework), false); } } public bool UseHostCompilerIfAvailable { set { _useHostCompilerIfAvailable = value; } get { return _useHostCompilerIfAvailable; } } public string VBRuntimePath { set { _store[nameof(VBRuntimePath)] = value; } get { return (string)_store[nameof(VBRuntimePath)]; } } public string Verbosity { set { _store[nameof(Verbosity)] = value; } get { return (string)_store[nameof(Verbosity)]; } } public string WarningsAsErrors { set { _store[nameof(WarningsAsErrors)] = value; } get { return (string)_store[nameof(WarningsAsErrors)]; } } public string WarningsNotAsErrors { set { _store[nameof(WarningsNotAsErrors)] = value; } get { return (string)_store[nameof(WarningsNotAsErrors)]; } } public string VBRuntime { set { _store[nameof(VBRuntime)] = value; } get { return (string)_store[nameof(VBRuntime)]; } } public string PdbFile { set { _store[nameof(PdbFile)] = value; } get { return (string)_store[nameof(PdbFile)]; } } #endregion #region Tool Members internal override BuildProtocolConstants.RequestLanguage Language => BuildProtocolConstants.RequestLanguage.VisualBasicCompile; private static readonly string[] s_separator = { "\r\n" }; internal override void LogMessages(string output, MessageImportance messageImportance) { var lines = output.Split(s_separator, StringSplitOptions.None); foreach (string line in lines) { //Code below will parse the set of four lines that comprise a VB //error message into a single object. The four-line format contains //a second line that is blank. This must be passed to the code below //to satisfy the parser. The parser needs to work with output from //old compilers as well. LogEventsFromTextOutput(line, messageImportance); } } /// <summary> /// Return the name of the tool to execute. /// </summary> override protected string ToolName { get { return "vbc.exe"; } } /// <summary> /// Override Execute so that we can moved the PDB file if we need to, /// after the compiler is done. /// </summary> public override bool Execute() { if (!base.Execute()) { return false; } MovePdbFileIfNecessary(OutputAssembly.ItemSpec); return !Log.HasLoggedErrors; } /// <summary> /// Move the PDB file if the PDB file that was generated by the compiler /// is not at the specified path, or if it is newer than the one there. /// VBC does not have a switch to specify the PDB path, so we are essentially implementing that for it here. /// We need make this possible to avoid colliding with the PDB generated by WinMDExp. /// /// If at some future point VBC.exe offers a /pdbfile switch, this function can be removed. /// </summary> internal void MovePdbFileIfNecessary(string outputAssembly) { // Get the name of the output assembly because the pdb will be written beside it and will have the same name if (String.IsNullOrEmpty(PdbFile) || String.IsNullOrEmpty(outputAssembly)) { return; } try { string actualPdb = Path.ChangeExtension(outputAssembly, ".pdb"); // This is the pdb that the compiler generated FileInfo actualPdbInfo = new FileInfo(actualPdb); string desiredLocation = PdbFile; if (!desiredLocation.EndsWith(".pdb", StringComparison.OrdinalIgnoreCase)) { desiredLocation += ".pdb"; } FileInfo desiredPdbInfo = new FileInfo(desiredLocation); // If the compiler generated a pdb.. if (actualPdbInfo.Exists) { // .. and the desired one does not exist or it's older... if (!desiredPdbInfo.Exists || (desiredPdbInfo.Exists && actualPdbInfo.LastWriteTime > desiredPdbInfo.LastWriteTime)) { // Delete the existing one if it's already there, as Move would otherwise fail if (desiredPdbInfo.Exists) { Utilities.DeleteNoThrow(desiredPdbInfo.FullName); } // Move the file to where we actually wanted VBC to put it File.Move(actualPdbInfo.FullName, desiredLocation); } } } catch (Exception e) when (Utilities.IsIoRelatedException(e)) { Log.LogErrorWithCodeFromResources("VBC_RenamePDB", PdbFile, e.Message); } } /// <summary> /// Generate the path to the tool /// </summary> protected override string GenerateFullPathToTool() { string pathToTool = ToolLocationHelper.GetPathToBuildToolsFile(ToolName, ToolLocationHelper.CurrentToolsVersion); if (null == pathToTool) { pathToTool = ToolLocationHelper.GetPathToDotNetFrameworkFile(ToolName, TargetDotNetFrameworkVersion.VersionLatest); if (null == pathToTool) { Log.LogErrorWithCodeFromResources("General_FrameworksFileNotFound", ToolName, ToolLocationHelper.GetDotNetFrameworkVersionFolderPrefix(TargetDotNetFrameworkVersion.VersionLatest)); } } return pathToTool; } /// <summary> /// vbc.exe only takes the BaseAddress in hexadecimal format. But we allow the caller /// of the task to pass in the BaseAddress in either decimal or hexadecimal format. /// Examples of supported hex formats include "0x10000000" or "&amp;H10000000". /// </summary> internal string GetBaseAddressInHex() { string originalBaseAddress = this.BaseAddress; if (originalBaseAddress != null) { if (originalBaseAddress.Length > 2) { string twoLetterPrefix = originalBaseAddress.Substring(0, 2); if ( (0 == String.Compare(twoLetterPrefix, "0x", StringComparison.OrdinalIgnoreCase)) || (0 == String.Compare(twoLetterPrefix, "&h", StringComparison.OrdinalIgnoreCase)) ) { // The incoming string is already in hex format ... we just need to // remove the 0x or &H from the beginning. return originalBaseAddress.Substring(2); } } // The incoming BaseAddress is not in hexadecimal format, so we need to // convert it to hex. try { uint baseAddressDecimal = UInt32.Parse(originalBaseAddress, CultureInfo.InvariantCulture); return baseAddressDecimal.ToString("X", CultureInfo.InvariantCulture); } catch (FormatException e) { throw Utilities.GetLocalizedArgumentException(e, ErrorString.Vbc_ParameterHasInvalidValue, "BaseAddress", originalBaseAddress); } } return null; } /// <summary> /// Looks at all the parameters that have been set, and builds up the string /// containing all the command-line switches. /// </summary> protected internal override void AddResponseFileCommands(CommandLineBuilderExtension commandLine) { commandLine.AppendSwitchIfNotNull("/baseaddress:", this.GetBaseAddressInHex()); commandLine.AppendSwitchIfNotNull("/libpath:", this.AdditionalLibPaths, ","); commandLine.AppendSwitchIfNotNull("/imports:", this.Imports, ","); // Make sure this /doc+ switch comes *before* the /doc:<file> switch (which is handled in the // ManagedCompiler.cs base class). /doc+ is really just an alias for /doc:<assemblyname>.xml, // and the last /doc switch on the command-line wins. If the user provided a specific doc filename, // we want that one to win. commandLine.AppendPlusOrMinusSwitch("/doc", this._store, "GenerateDocumentation"); commandLine.AppendSwitchIfNotNull("/optioncompare:", this.OptionCompare); commandLine.AppendPlusOrMinusSwitch("/optionexplicit", this._store, "OptionExplicit"); // Make sure this /optionstrict+ switch appears *before* the /optionstrict:xxxx switch below /* twhitney: In Orcas a change was made for devdiv bug 16889 that set Option Strict-, whenever this.DisabledWarnings was * empty. That was clearly the wrong thing to do and we found it when we had a project with all the warning configuration * entries set to WARNING. Because this.DisabledWarnings was empty in that case we would end up sending /OptionStrict- * effectively silencing all the warnings that had been selected. * * Now what we do is: * If option strict+ is specified, that trumps everything and we just set option strict+ * Otherwise, just set option strict:custom. * You may wonder why we don't try to set Option Strict- The reason is that Option Strict- just implies a certain * set of warnings that should be disabled (there's ten of them today) You get the same effect by sending * option strict:custom on along with the correct list of disabled warnings. * Rather than make this code know the current set of disabled warnings that comprise Option strict-, we just send * option strict:custom on with the understanding that we'll get the same behavior as option strict- since we are passing * the /nowarn line on that contains all the warnings OptionStrict- would disable anyway. The IDE knows what they are * and puts them in the project file so we are good. And by not making this code aware of which warnings comprise * Option Strict-, we have one less place we have to keep up to date in terms of what comprises option strict- */ // Decide whether we are Option Strict+ or Option Strict:custom object optionStrictSetting = this._store["OptionStrict"]; bool optionStrict = optionStrictSetting != null ? (bool)optionStrictSetting : false; if (optionStrict) { commandLine.AppendSwitch("/optionstrict+"); } else // OptionStrict+ wasn't specified so use :custom. { commandLine.AppendSwitch("/optionstrict:custom"); } commandLine.AppendSwitchIfNotNull("/optionstrict:", this.OptionStrictType); commandLine.AppendWhenTrue("/nowarn", this._store, "NoWarnings"); commandLine.AppendSwitchWithSplitting("/nowarn:", this.DisabledWarnings, ",", ';', ','); commandLine.AppendPlusOrMinusSwitch("/optioninfer", this._store, "OptionInfer"); commandLine.AppendWhenTrue("/nostdlib", this._store, "NoStandardLib"); commandLine.AppendWhenTrue("/novbruntimeref", this._store, "NoVBRuntimeReference"); commandLine.AppendSwitchIfNotNull("/errorreport:", this.ErrorReport); commandLine.AppendSwitchIfNotNull("/platform:", this.PlatformWith32BitPreference); commandLine.AppendPlusOrMinusSwitch("/removeintchecks", this._store, "RemoveIntegerChecks"); commandLine.AppendSwitchIfNotNull("/rootnamespace:", this.RootNamespace); commandLine.AppendSwitchIfNotNull("/sdkpath:", this.SdkPath); commandLine.AppendSwitchIfNotNull("/langversion:", this.LangVersion); commandLine.AppendSwitchIfNotNull("/moduleassemblyname:", this.ModuleAssemblyName); commandLine.AppendWhenTrue("/netcf", this._store, "TargetCompactFramework"); commandLine.AppendSwitchIfNotNull("/preferreduilang:", this.PreferredUILang); commandLine.AppendPlusOrMinusSwitch("/highentropyva", this._store, "HighEntropyVA"); if (0 == String.Compare(this.VBRuntimePath, this.VBRuntime, StringComparison.OrdinalIgnoreCase)) { commandLine.AppendSwitchIfNotNull("/vbruntime:", this.VBRuntimePath); } else if (this.VBRuntime != null) { string vbRuntimeSwitch = this.VBRuntime; if (0 == String.Compare(vbRuntimeSwitch, "EMBED", StringComparison.OrdinalIgnoreCase)) { commandLine.AppendSwitch("/vbruntime*"); } else if (0 == String.Compare(vbRuntimeSwitch, "NONE", StringComparison.OrdinalIgnoreCase)) { commandLine.AppendSwitch("/vbruntime-"); } else if (0 == String.Compare(vbRuntimeSwitch, "DEFAULT", StringComparison.OrdinalIgnoreCase)) { commandLine.AppendSwitch("/vbruntime+"); } else { commandLine.AppendSwitchIfNotNull("/vbruntime:", vbRuntimeSwitch); } } // Verbosity if ( (this.Verbosity != null) && ( (0 == String.Compare(this.Verbosity, "quiet", StringComparison.OrdinalIgnoreCase)) || (0 == String.Compare(this.Verbosity, "verbose", StringComparison.OrdinalIgnoreCase)) ) ) { commandLine.AppendSwitchIfNotNull("/", this.Verbosity); } commandLine.AppendSwitchIfNotNull("/doc:", this.DocumentationFile); commandLine.AppendSwitchUnquotedIfNotNull("/define:", Vbc.GetDefineConstantsSwitch(this.DefineConstants)); AddReferencesToCommandLine(commandLine); commandLine.AppendSwitchIfNotNull("/win32resource:", this.Win32Resource); // Special case for "Sub Main" (See VSWhidbey 381254) if (0 != String.Compare("Sub Main", this.MainEntryPoint, StringComparison.OrdinalIgnoreCase)) { commandLine.AppendSwitchIfNotNull("/main:", this.MainEntryPoint); } base.AddResponseFileCommands(commandLine); // This should come after the "TreatWarningsAsErrors" flag is processed (in managedcompiler.cs). // Because if TreatWarningsAsErrors=false, then we'll have a /warnaserror- on the command-line, // and then any specific warnings that should be treated as errors should be specified with // /warnaserror+:<list> after the /warnaserror- switch. The order of the switches on the command-line // does matter. // // Note that // /warnaserror+ // is just shorthand for: // /warnaserror+:<all possible warnings> // // Similarly, // /warnaserror- // is just shorthand for: // /warnaserror-:<all possible warnings> commandLine.AppendSwitchWithSplitting("/warnaserror+:", this.WarningsAsErrors, ",", ';', ','); commandLine.AppendSwitchWithSplitting("/warnaserror-:", this.WarningsNotAsErrors, ",", ';', ','); // If not design time build and the globalSessionGuid property was set then add a -globalsessionguid:<guid> bool designTime = false; if (this.HostObject != null) { var vbHost = this.HostObject as IVbcHostObject; designTime = vbHost.IsDesignTime(); } if (!designTime) { if (!string.IsNullOrWhiteSpace(this.VsSessionGuid)) { commandLine.AppendSwitchIfNotNull("/sqmsessionguid:", this.VsSessionGuid); } } // It's a good idea for the response file to be the very last switch passed, just // from a predictability perspective. It also solves the problem that a dogfooder // ran into, which is described in an email thread attached to bug VSWhidbey 146883. // See also bugs 177762 and 118307 for additional bugs related to response file position. if (this.ResponseFiles != null) { foreach (ITaskItem response in this.ResponseFiles) { commandLine.AppendSwitchIfNotNull("@", response.ItemSpec); } } } private void AddReferencesToCommandLine(CommandLineBuilderExtension commandLine) { if ((this.References == null) || (this.References.Length == 0)) { return; } var references = new List<ITaskItem>(this.References.Length); var links = new List<ITaskItem>(this.References.Length); foreach (ITaskItem reference in this.References) { bool embed = Utilities.TryConvertItemMetadataToBool(reference, "EmbedInteropTypes"); if (embed) { links.Add(reference); } else { references.Add(reference); } } if (links.Count > 0) { commandLine.AppendSwitchIfNotNull("/link:", links.ToArray(), ","); } if (references.Count > 0) { commandLine.AppendSwitchIfNotNull("/reference:", references.ToArray(), ","); } } /// <summary> /// Validate parameters, log errors and warnings and return true if /// Execute should proceed. /// </summary> protected override bool ValidateParameters() { if (!base.ValidateParameters()) { return false; } // Validate that the "Verbosity" parameter is one of "quiet", "normal", or "verbose". if (this.Verbosity != null) { if ((0 != String.Compare(Verbosity, "normal", StringComparison.OrdinalIgnoreCase)) && (0 != String.Compare(Verbosity, "quiet", StringComparison.OrdinalIgnoreCase)) && (0 != String.Compare(Verbosity, "verbose", StringComparison.OrdinalIgnoreCase))) { Log.LogErrorWithCodeFromResources("Vbc_EnumParameterHasInvalidValue", "Verbosity", this.Verbosity, "Quiet, Normal, Verbose"); return false; } } return true; } /// <summary> /// This method intercepts the lines to be logged coming from STDOUT from VBC. /// Once we see a standard vb warning or error, then we capture it and grab the next 3 /// lines so we can transform the string form the form of FileName.vb(line) to FileName.vb(line,column) /// which will allow us to report the line and column to the IDE, and thus filter the error /// in the duplicate case for multi-targeting, or just squiggle the appropriate token /// instead of the entire line. /// </summary> /// <param name="singleLine">A single line from the STDOUT of the vbc compiler</param> /// <param name="messageImportance">High,Low,Normal</param> protected override void LogEventsFromTextOutput(string singleLine, MessageImportance messageImportance) { // We can return immediately if this was not called by the out of proc compiler if (!this.UsedCommandLineTool) { base.LogEventsFromTextOutput(singleLine, messageImportance); return; } // We can also return immediately if the current string is not a warning or error // and we have not seen a warning or error yet. 'Error' and 'Warning' are not localized. if (_vbErrorLines.Count == 0 && singleLine.IndexOf("warning", StringComparison.OrdinalIgnoreCase) == -1 && singleLine.IndexOf("error", StringComparison.OrdinalIgnoreCase) == -1) { base.LogEventsFromTextOutput(singleLine, messageImportance); return; } ParseVBErrorOrWarning(singleLine, messageImportance); } /// <summary> /// Given a string, parses it to find out whether it's an error or warning and, if so, /// make sure it's validated properly. /// </summary> /// <comments> /// INTERNAL FOR UNITTESTING ONLY /// </comments> /// <param name="singleLine">The line to parse</param> /// <param name="messageImportance">The MessageImportance to use when reporting the error.</param> internal void ParseVBErrorOrWarning(string singleLine, MessageImportance messageImportance) { // if this string is empty then we haven't seen the first line of an error yet if (_vbErrorLines.Count > 0) { // vbc separates the error message from the source text with an empty line, so // we can check for an empty line to see if vbc finished outputting the error message if (!_isDoneOutputtingErrorMessage && singleLine.Length == 0) { _isDoneOutputtingErrorMessage = true; _numberOfLinesInErrorMessage = _vbErrorLines.Count; } _vbErrorLines.Enqueue(new VBError(singleLine, messageImportance)); // We are looking for the line that indicates the column (contains the '~'), // which vbc outputs 3 lines below the error message: // // <error message> // <blank line> // <line with the source text> // <line with the '~'> if (_isDoneOutputtingErrorMessage && _vbErrorLines.Count == _numberOfLinesInErrorMessage + 3) { // Once we have the 4th line (error line + 3), then parse it for the first ~ // which will correspond to the column of the token with the error because // VBC respects the users's indentation settings in the file it is compiling // and only outputs SPACE chars to STDOUT. // The +1 is to translate the index into user columns which are 1 based. VBError originalVBError = _vbErrorLines.Dequeue(); string originalVBErrorString = originalVBError.Message; int column = singleLine.IndexOf('~') + 1; int endParenthesisLocation = originalVBErrorString.IndexOf(')'); // If for some reason the line does not contain any ~ then something went wrong // so abort and return the original string. if (column < 0 || endParenthesisLocation < 0) { // we need to output all of the original lines we ate. Log.LogMessageFromText(originalVBErrorString, originalVBError.MessageImportance); foreach (VBError vberror in _vbErrorLines) { base.LogEventsFromTextOutput(vberror.Message, vberror.MessageImportance); } _vbErrorLines.Clear(); return; } string newLine = null; newLine = originalVBErrorString.Substring(0, endParenthesisLocation) + "," + column + originalVBErrorString.Substring(endParenthesisLocation); // Output all of the lines of the error, but with the modified first line as well. Log.LogMessageFromText(newLine, originalVBError.MessageImportance); foreach (VBError vberror in _vbErrorLines) { base.LogEventsFromTextOutput(vberror.Message, vberror.MessageImportance); } _vbErrorLines.Clear(); } } else { CanonicalError.Parts parts = CanonicalError.Parse(singleLine); if (parts == null) { base.LogEventsFromTextOutput(singleLine, messageImportance); } else if ((parts.category == CanonicalError.Parts.Category.Error || parts.category == CanonicalError.Parts.Category.Warning) && parts.column == CanonicalError.Parts.numberNotSpecified) { if (parts.line != CanonicalError.Parts.numberNotSpecified) { // If we got here, then this is a standard VBC error or warning. _vbErrorLines.Enqueue(new VBError(singleLine, messageImportance)); _isDoneOutputtingErrorMessage = false; _numberOfLinesInErrorMessage = 0; } else { // Project-level errors don't have line numbers -- just output now. base.LogEventsFromTextOutput(singleLine, messageImportance); } } } } #endregion /// <summary> /// Many VisualStudio VB projects have values for the DefineConstants property that /// contain quotes and spaces. Normally we don't allow parameters passed into the /// task to contain quotes, because if we weren't careful, we might accidentally /// allow a parameter injection attach. But for "DefineConstants", we have to allow /// it. /// So this method prepares the string to be passed in on the /define: command-line /// switch. It does that by quoting the entire string, and escaping the embedded /// quotes. /// </summary> internal static string GetDefineConstantsSwitch ( string originalDefineConstants ) { if ((originalDefineConstants == null) || (originalDefineConstants.Length == 0)) { return null; } StringBuilder finalDefineConstants = new StringBuilder(originalDefineConstants); // Replace slash-quote with slash-slash-quote. finalDefineConstants.Replace("\\\"", "\\\\\""); // Replace quote with slash-quote. finalDefineConstants.Replace("\"", "\\\""); // Surround the whole thing with a pair of double-quotes. finalDefineConstants.Insert(0, '"'); finalDefineConstants.Append('"'); // Now it's ready to be passed in to the /define: switch. return finalDefineConstants.ToString(); } /// <summary> /// This method will initialize the host compiler object with all the switches, /// parameters, resources, references, sources, etc. /// /// It returns true if everything went according to plan. It returns false if the /// host compiler had a problem with one of the parameters that was passed in. /// /// This method also sets the "this.HostCompilerSupportsAllParameters" property /// accordingly. /// /// Example: /// If we attempted to pass in Platform="foobar", then this method would /// set HostCompilerSupportsAllParameters=true, but it would throw an /// exception because the host compiler fully supports /// the Platform parameter, but "foobar" is an illegal value. /// /// Example: /// If we attempted to pass in NoConfig=false, then this method would set /// HostCompilerSupportsAllParameters=false, because while this is a legal /// thing for csc.exe, the IDE compiler cannot support it. In this situation /// the return value will also be false. /// </summary> /// <owner>RGoel</owner> private bool InitializeHostCompiler(IVbcHostObject vbcHostObject) { this.HostCompilerSupportsAllParameters = this.UseHostCompilerIfAvailable; string param = "Unknown"; try { param = nameof(vbcHostObject.BeginInitialization); vbcHostObject.BeginInitialization(); CheckHostObjectSupport(param = nameof(AdditionalLibPaths), vbcHostObject.SetAdditionalLibPaths(AdditionalLibPaths)); CheckHostObjectSupport(param = nameof(AddModules), vbcHostObject.SetAddModules(AddModules)); // For host objects which support them, set the analyzers, ruleset and additional files. IAnalyzerHostObject analyzerHostObject = vbcHostObject as IAnalyzerHostObject; if (analyzerHostObject != null) { CheckHostObjectSupport(param = nameof(Analyzers), analyzerHostObject.SetAnalyzers(Analyzers)); CheckHostObjectSupport(param = nameof(CodeAnalysisRuleSet), analyzerHostObject.SetRuleSet(CodeAnalysisRuleSet)); CheckHostObjectSupport(param = nameof(AdditionalFiles), analyzerHostObject.SetAdditionalFiles(AdditionalFiles)); } CheckHostObjectSupport(param = nameof(BaseAddress), vbcHostObject.SetBaseAddress(TargetType, GetBaseAddressInHex())); CheckHostObjectSupport(param = nameof(CodePage), vbcHostObject.SetCodePage(CodePage)); CheckHostObjectSupport(param = nameof(DebugType), vbcHostObject.SetDebugType(EmitDebugInformation, DebugType)); CheckHostObjectSupport(param = nameof(DefineConstants), vbcHostObject.SetDefineConstants(DefineConstants)); CheckHostObjectSupport(param = nameof(DelaySign), vbcHostObject.SetDelaySign(DelaySign)); CheckHostObjectSupport(param = nameof(DocumentationFile), vbcHostObject.SetDocumentationFile(DocumentationFile)); CheckHostObjectSupport(param = nameof(FileAlignment), vbcHostObject.SetFileAlignment(FileAlignment)); CheckHostObjectSupport(param = nameof(GenerateDocumentation), vbcHostObject.SetGenerateDocumentation(GenerateDocumentation)); CheckHostObjectSupport(param = nameof(Imports), vbcHostObject.SetImports(Imports)); CheckHostObjectSupport(param = nameof(KeyContainer), vbcHostObject.SetKeyContainer(KeyContainer)); CheckHostObjectSupport(param = nameof(KeyFile), vbcHostObject.SetKeyFile(KeyFile)); CheckHostObjectSupport(param = nameof(LinkResources), vbcHostObject.SetLinkResources(LinkResources)); CheckHostObjectSupport(param = nameof(MainEntryPoint), vbcHostObject.SetMainEntryPoint(MainEntryPoint)); CheckHostObjectSupport(param = nameof(NoConfig), vbcHostObject.SetNoConfig(NoConfig)); CheckHostObjectSupport(param = nameof(NoStandardLib), vbcHostObject.SetNoStandardLib(NoStandardLib)); CheckHostObjectSupport(param = nameof(NoWarnings), vbcHostObject.SetNoWarnings(NoWarnings)); CheckHostObjectSupport(param = nameof(Optimize), vbcHostObject.SetOptimize(Optimize)); CheckHostObjectSupport(param = nameof(OptionCompare), vbcHostObject.SetOptionCompare(OptionCompare)); CheckHostObjectSupport(param = nameof(OptionExplicit), vbcHostObject.SetOptionExplicit(OptionExplicit)); CheckHostObjectSupport(param = nameof(OptionStrict), vbcHostObject.SetOptionStrict(OptionStrict)); CheckHostObjectSupport(param = nameof(OptionStrictType), vbcHostObject.SetOptionStrictType(OptionStrictType)); CheckHostObjectSupport(param = nameof(OutputAssembly), vbcHostObject.SetOutputAssembly(OutputAssembly?.ItemSpec)); // For host objects which support them, set platform with 32BitPreference, HighEntropyVA, and SubsystemVersion IVbcHostObject5 vbcHostObject5 = vbcHostObject as IVbcHostObject5; if (vbcHostObject5 != null) { CheckHostObjectSupport(param = nameof(PlatformWith32BitPreference), vbcHostObject5.SetPlatformWith32BitPreference(PlatformWith32BitPreference)); CheckHostObjectSupport(param = nameof(HighEntropyVA), vbcHostObject5.SetHighEntropyVA(HighEntropyVA)); CheckHostObjectSupport(param = nameof(SubsystemVersion), vbcHostObject5.SetSubsystemVersion(SubsystemVersion)); } else { CheckHostObjectSupport(param = nameof(Platform), vbcHostObject.SetPlatform(Platform)); } IVbcHostObject6 vbcHostObject6 = vbcHostObject as IVbcHostObject6; if (vbcHostObject6 != null) { CheckHostObjectSupport(param = nameof(ErrorLog), vbcHostObject6.SetErrorLog(ErrorLog)); CheckHostObjectSupport(param = nameof(ReportAnalyzer), vbcHostObject6.SetReportAnalyzer(ReportAnalyzer)); } CheckHostObjectSupport(param = nameof(References), vbcHostObject.SetReferences(References)); CheckHostObjectSupport(param = nameof(RemoveIntegerChecks), vbcHostObject.SetRemoveIntegerChecks(RemoveIntegerChecks)); CheckHostObjectSupport(param = nameof(Resources), vbcHostObject.SetResources(Resources)); CheckHostObjectSupport(param = nameof(ResponseFiles), vbcHostObject.SetResponseFiles(ResponseFiles)); CheckHostObjectSupport(param = nameof(RootNamespace), vbcHostObject.SetRootNamespace(RootNamespace)); CheckHostObjectSupport(param = nameof(SdkPath), vbcHostObject.SetSdkPath(SdkPath)); CheckHostObjectSupport(param = nameof(Sources), vbcHostObject.SetSources(Sources)); CheckHostObjectSupport(param = nameof(TargetCompactFramework), vbcHostObject.SetTargetCompactFramework(TargetCompactFramework)); CheckHostObjectSupport(param = nameof(TargetType), vbcHostObject.SetTargetType(TargetType)); CheckHostObjectSupport(param = nameof(TreatWarningsAsErrors), vbcHostObject.SetTreatWarningsAsErrors(TreatWarningsAsErrors)); CheckHostObjectSupport(param = nameof(WarningsAsErrors), vbcHostObject.SetWarningsAsErrors(WarningsAsErrors)); CheckHostObjectSupport(param = nameof(WarningsNotAsErrors), vbcHostObject.SetWarningsNotAsErrors(WarningsNotAsErrors)); // DisabledWarnings needs to come after WarningsAsErrors and WarningsNotAsErrors, because // of the way the host object works, and the fact that DisabledWarnings trump Warnings[Not]AsErrors. CheckHostObjectSupport(param = nameof(DisabledWarnings), vbcHostObject.SetDisabledWarnings(DisabledWarnings)); CheckHostObjectSupport(param = nameof(Win32Icon), vbcHostObject.SetWin32Icon(Win32Icon)); CheckHostObjectSupport(param = nameof(Win32Resource), vbcHostObject.SetWin32Resource(Win32Resource)); // In order to maintain compatibility with previous host compilers, we must // light-up for IVbcHostObject2 if (vbcHostObject is IVbcHostObject2) { IVbcHostObject2 vbcHostObject2 = (IVbcHostObject2)vbcHostObject; CheckHostObjectSupport(param = nameof(ModuleAssemblyName), vbcHostObject2.SetModuleAssemblyName(ModuleAssemblyName)); CheckHostObjectSupport(param = nameof(OptionInfer), vbcHostObject2.SetOptionInfer(OptionInfer)); CheckHostObjectSupport(param = nameof(Win32Manifest), vbcHostObject2.SetWin32Manifest(GetWin32ManifestSwitch(NoWin32Manifest, Win32Manifest))); // initialize option Infer CheckHostObjectSupport(param = nameof(OptionInfer), vbcHostObject2.SetOptionInfer(OptionInfer)); } else { // If we have been given a property that the host compiler doesn't support // then we need to state that we are falling back to the command line compiler if (!String.IsNullOrEmpty(ModuleAssemblyName)) { CheckHostObjectSupport(param = nameof(ModuleAssemblyName), resultFromHostObjectSetOperation: false); } if (_store.ContainsKey(nameof(OptionInfer))) { CheckHostObjectSupport(param = nameof(OptionInfer), resultFromHostObjectSetOperation: false); } if (!String.IsNullOrEmpty(Win32Manifest)) { CheckHostObjectSupport(param = nameof(Win32Manifest), resultFromHostObjectSetOperation: false); } } // Check for support of the LangVersion property if (vbcHostObject is IVbcHostObject3) { IVbcHostObject3 vbcHostObject3 = (IVbcHostObject3)vbcHostObject; CheckHostObjectSupport(param = nameof(LangVersion), vbcHostObject3.SetLanguageVersion(LangVersion)); } else if (!String.IsNullOrEmpty(LangVersion) && !UsedCommandLineTool) { CheckHostObjectSupport(param = nameof(LangVersion), resultFromHostObjectSetOperation: false); } if (vbcHostObject is IVbcHostObject4) { IVbcHostObject4 vbcHostObject4 = (IVbcHostObject4)vbcHostObject; CheckHostObjectSupport(param = nameof(VBRuntime), vbcHostObject4.SetVBRuntime(VBRuntime)); } // Support for NoVBRuntimeReference was added to this task after IVbcHostObject was frozen. That doesn't matter much because the host // compiler doesn't support it, and almost nobody uses it anyway. But if someone has set it, we need to hard code falling back to // the command line compiler here. if (NoVBRuntimeReference) { CheckHostObjectSupport(param = nameof(NoVBRuntimeReference), resultFromHostObjectSetOperation: false); } // In general, we don't support preferreduilang with the in-proc compiler. It will always use the same locale as the // host process, so in general, we have to fall back to the command line compiler if this option is specified. // However, we explicitly allow two values (mostly for parity with C#): // Null is supported because it means that option should be omitted, and compiler default used - obviously always valid. // Explicitly specified name of current locale is also supported, since it is effectively a no-op. if (!String.IsNullOrEmpty(PreferredUILang) && !String.Equals(PreferredUILang, System.Globalization.CultureInfo.CurrentUICulture.Name, StringComparison.OrdinalIgnoreCase)) { CheckHostObjectSupport(param = nameof(PreferredUILang), resultFromHostObjectSetOperation: false); } } catch (Exception e) when (!Utilities.IsCriticalException(e)) { if (this.HostCompilerSupportsAllParameters) { // If the host compiler doesn't support everything we need, we're going to end up // shelling out to the command-line compiler anyway. That means the command-line // compiler will log the error. So here, we only log the error if we would've // tried to use the host compiler. Log.LogErrorWithCodeFromResources("General_CouldNotSetHostObjectParameter", param, e.Message); } return false; } finally { // In the case of the VB host compiler, the EndInitialization method will // throw (due to FAILED HRESULT) if there was a bad value for one of the // parameters. vbcHostObject.EndInitialization(); } return true; } /// <summary> /// This method will get called during Execute() if a host object has been passed into the Vbc /// task. Returns one of the following values to indicate what the next action should be: /// UseHostObjectToExecute Host compiler exists and was initialized. /// UseAlternateToolToExecute Host compiler doesn't exist or was not appropriate. /// NoActionReturnSuccess Host compiler was already up-to-date, and we're done. /// NoActionReturnFailure Bad parameters were passed into the task. /// </summary> /// <owner>RGoel</owner> protected override HostObjectInitializationStatus InitializeHostObject() { if (this.HostObject != null) { // When the host object was passed into the task, it was passed in as a generic // "Object" (because ITask interface obviously can't have any Vbc-specific stuff // in it, and each task is going to want to communicate with its host in a unique // way). Now we cast it to the specific type that the Vbc task expects. If the // host object does not match this type, the host passed in an invalid host object // to Vbc, and we error out. // NOTE: For compat reasons this must remain IVbcHostObject // we can dynamically test for smarter interfaces later.. using (RCWForCurrentContext<IVbcHostObject> hostObject = new RCWForCurrentContext<IVbcHostObject>(this.HostObject as IVbcHostObject)) { IVbcHostObject vbcHostObject = hostObject.RCW; if (vbcHostObject != null) { bool hostObjectSuccessfullyInitialized = InitializeHostCompiler(vbcHostObject); // If we're currently only in design-time (as opposed to build-time), // then we're done. We've initialized the host compiler as best we // can, and we certainly don't want to actually do the final compile. // So return true, saying we're done and successful. if (vbcHostObject.IsDesignTime()) { // If we are design-time then we do not want to continue the build at // this time. return hostObjectSuccessfullyInitialized ? HostObjectInitializationStatus.NoActionReturnSuccess : HostObjectInitializationStatus.NoActionReturnFailure; } // Roslyn doesn't support using the host object for compilation // Since the host compiler has refused to take on the responsibility for this compilation, // we're about to shell out to the command-line compiler to handle it. If some of the // references don't exist on disk, we know the command-line compiler will fail, so save // the trouble, and just throw a consistent error ourselves. This allows us to give // more information than the compiler would, and also make things consistent across // Vbc / Csc / etc. Actually, the real reason is bug 275726 (ddsuites\src\vs\env\vsproject\refs\ptp3). // This suite behaves differently in localized builds than on English builds because // VBC.EXE doesn't localize the word "error" when they emit errors and so we can't scan for it. if (!CheckAllReferencesExistOnDisk()) { return HostObjectInitializationStatus.NoActionReturnFailure; } // The host compiler doesn't support some of the switches/parameters // being passed to it. Therefore, we resort to using the command-line compiler // in this case. UsedCommandLineTool = true; return HostObjectInitializationStatus.UseAlternateToolToExecute; } else { Log.LogErrorWithCodeFromResources("General_IncorrectHostObject", "Vbc", "IVbcHostObject"); } } } // No appropriate host object was found. UsedCommandLineTool = true; return HostObjectInitializationStatus.UseAlternateToolToExecute; } /// <summary> /// This method will get called during Execute() if a host object has been passed into the Vbc /// task. Returns true if an appropriate host object was found, it was called to do the compile, /// and the compile succeeded. Otherwise, we return false. /// </summary> /// <owner>RGoel</owner> protected override bool CallHostObjectToExecute() { Debug.Assert(this.HostObject != null, "We should not be here if the host object has not been set."); IVbcHostObject vbcHostObject = this.HostObject as IVbcHostObject; Debug.Assert(vbcHostObject != null, "Wrong kind of host object passed in!"); IVbcHostObject5 vbcHostObject5 = vbcHostObject as IVbcHostObject5; Debug.Assert(vbcHostObject5 != null, "Wrong kind of host object passed in!"); // IVbcHostObjectFreeThreaded::Compile is the preferred way to compile the host object // because while it is still synchronous it does its waiting on our BG thread // (as opposed to the UI thread for IVbcHostObject::Compile) if (vbcHostObject5 != null) { IVbcHostObjectFreeThreaded freeThreadedHostObject = vbcHostObject5.GetFreeThreadedHostObject(); return freeThreadedHostObject.Compile(); } else { // If for some reason we can't get to IVbcHostObject5 we just fall back to the old // Compile method. This method unfortunately allows for reentrancy on the UI thread. return vbcHostObject.Compile(); } } /// <summary> /// private class that just holds together name, value pair for the vbErrorLines Queue /// </summary> private class VBError { public string Message { get; } public MessageImportance MessageImportance { get; } public VBError(string message, MessageImportance importance) { this.Message = message; this.MessageImportance = importance; } } } }
using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Web; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Web; using Umbraco.ModelsBuilder; using Umbraco.ModelsBuilder.Umbraco; [assembly: PureLiveAssembly] [assembly:ModelsBuilderAssembly(PureLive = true, SourceHash = "4ad86b1aa0722510")] [assembly:System.Reflection.AssemblyVersion("0.0.0.1")] // FILE: models.generated.cs //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Umbraco.ModelsBuilder v3.0.7.99 // // Changes to this file will be lost if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Umbraco.Web.PublishedContentModels { /// <summary>Blog Post</summary> [PublishedContentModel("BlogPost")] public partial class BlogPost : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "BlogPost"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public BlogPost(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<BlogPost, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Content ///</summary> [ImplementPropertyType("content")] public Newtonsoft.Json.Linq.JToken Content { get { return this.GetPropertyValue<Newtonsoft.Json.Linq.JToken>("content"); } } ///<summary> /// Introduction ///</summary> [ImplementPropertyType("introduction")] public string Introduction { get { return this.GetPropertyValue<string>("introduction"); } } ///<summary> /// Tags: Tags related to this blog post ///</summary> [ImplementPropertyType("tags")] public IEnumerable<string> Tags { get { return this.GetPropertyValue<IEnumerable<string>>("tags"); } } ///<summary> /// Url Name: The url name which should be used ///</summary> [ImplementPropertyType("umbracoUrlName")] public string UmbracoUrlName { get { return this.GetPropertyValue<string>("umbracoUrlName"); } } } /// <summary>Blog Post Repository</summary> [PublishedContentModel("BlogPostRepository")] public partial class BlogPostRepository : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "BlogPostRepository"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public BlogPostRepository(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<BlogPostRepository, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Hide in bottom navigation? ///</summary> [ImplementPropertyType("umbracoNaviHide")] public bool UmbracoNaviHide { get { return this.GetPropertyValue<bool>("umbracoNaviHide"); } } } /// <summary>Home</summary> [PublishedContentModel("Home")] public partial class Home : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "Home"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public Home(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Home, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Content ///</summary> [ImplementPropertyType("content")] public Newtonsoft.Json.Linq.JToken Content { get { return this.GetPropertyValue<Newtonsoft.Json.Linq.JToken>("content"); } } ///<summary> /// Site Description ///</summary> [ImplementPropertyType("siteDescription")] public string SiteDescription { get { return this.GetPropertyValue<string>("siteDescription"); } } ///<summary> /// Site Logo ///</summary> [ImplementPropertyType("siteLogo")] public string SiteLogo { get { return this.GetPropertyValue<string>("siteLogo"); } } ///<summary> /// Site Title ///</summary> [ImplementPropertyType("siteTitle")] public string SiteTitle { get { return this.GetPropertyValue<string>("siteTitle"); } } } /// <summary>Landing Page</summary> [PublishedContentModel("LandingPage")] public partial class LandingPage : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "LandingPage"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public LandingPage(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<LandingPage, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Content ///</summary> [ImplementPropertyType("content")] public Newtonsoft.Json.Linq.JToken Content { get { return this.GetPropertyValue<Newtonsoft.Json.Linq.JToken>("content"); } } ///<summary> /// Hide in bottom navigation? ///</summary> [ImplementPropertyType("umbracoNaviHide")] public bool UmbracoNaviHide { get { return this.GetPropertyValue<bool>("umbracoNaviHide"); } } } /// <summary>Text Page</summary> [PublishedContentModel("TextPage")] public partial class TextPage : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "TextPage"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public TextPage(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<TextPage, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Content ///</summary> [ImplementPropertyType("content")] public Newtonsoft.Json.Linq.JToken Content { get { return this.GetPropertyValue<Newtonsoft.Json.Linq.JToken>("content"); } } } /// <summary>RealEstate</summary> [PublishedContentModel("realEstate")] public partial class RealEstate : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "realEstate"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public RealEstate(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<RealEstate, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// City: The city the real estate is located ///</summary> [ImplementPropertyType("city")] public string City { get { return this.GetPropertyValue<string>("city"); } } ///<summary> /// Type: The type of this real estate ///</summary> [ImplementPropertyType("type")] public string Type { get { return this.GetPropertyValue<string>("type"); } } } /// <summary>ProductDetails</summary> [PublishedContentModel("ProductDetails")] public partial class ProductDetails : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "ProductDetails"; public new const PublishedItemType ModelItemType = PublishedItemType.Content; #pragma warning restore 0109 public ProductDetails(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<ProductDetails, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } } /// <summary>Folder</summary> [PublishedContentModel("Folder")] public partial class Folder : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "Folder"; public new const PublishedItemType ModelItemType = PublishedItemType.Media; #pragma warning restore 0109 public Folder(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Folder, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Contents: ///</summary> [ImplementPropertyType("contents")] public object Contents { get { return this.GetPropertyValue("contents"); } } } /// <summary>Image</summary> [PublishedContentModel("Image")] public partial class Image : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "Image"; public new const PublishedItemType ModelItemType = PublishedItemType.Media; #pragma warning restore 0109 public Image(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Image, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Size ///</summary> [ImplementPropertyType("umbracoBytes")] public string UmbracoBytes { get { return this.GetPropertyValue<string>("umbracoBytes"); } } ///<summary> /// Type ///</summary> [ImplementPropertyType("umbracoExtension")] public string UmbracoExtension { get { return this.GetPropertyValue<string>("umbracoExtension"); } } ///<summary> /// Upload image ///</summary> [ImplementPropertyType("umbracoFile")] public Umbraco.Web.Models.ImageCropDataSet UmbracoFile { get { return this.GetPropertyValue<Umbraco.Web.Models.ImageCropDataSet>("umbracoFile"); } } ///<summary> /// Height ///</summary> [ImplementPropertyType("umbracoHeight")] public string UmbracoHeight { get { return this.GetPropertyValue<string>("umbracoHeight"); } } ///<summary> /// Width ///</summary> [ImplementPropertyType("umbracoWidth")] public string UmbracoWidth { get { return this.GetPropertyValue<string>("umbracoWidth"); } } } /// <summary>File</summary> [PublishedContentModel("File")] public partial class File : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "File"; public new const PublishedItemType ModelItemType = PublishedItemType.Media; #pragma warning restore 0109 public File(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<File, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Size ///</summary> [ImplementPropertyType("umbracoBytes")] public string UmbracoBytes { get { return this.GetPropertyValue<string>("umbracoBytes"); } } ///<summary> /// Type ///</summary> [ImplementPropertyType("umbracoExtension")] public string UmbracoExtension { get { return this.GetPropertyValue<string>("umbracoExtension"); } } ///<summary> /// Upload file ///</summary> [ImplementPropertyType("umbracoFile")] public string UmbracoFile { get { return this.GetPropertyValue<string>("umbracoFile"); } } } /// <summary>Member</summary> [PublishedContentModel("Member")] public partial class Member : PublishedContentModel { #pragma warning disable 0109 // new is redundant public new const string ModelTypeAlias = "Member"; public new const PublishedItemType ModelItemType = PublishedItemType.Member; #pragma warning restore 0109 public Member(IPublishedContent content) : base(content) { } #pragma warning disable 0109 // new is redundant public new static PublishedContentType GetModelContentType() { return PublishedContentType.Get(ModelItemType, ModelTypeAlias); } #pragma warning restore 0109 public static PublishedPropertyType GetModelPropertyType<TValue>(Expression<Func<Member, TValue>> selector) { return PublishedContentModelUtility.GetModelPropertyType(GetModelContentType(), selector); } ///<summary> /// Is Approved ///</summary> [ImplementPropertyType("umbracoMemberApproved")] public bool UmbracoMemberApproved { get { return this.GetPropertyValue<bool>("umbracoMemberApproved"); } } ///<summary> /// Comments ///</summary> [ImplementPropertyType("umbracoMemberComments")] public string UmbracoMemberComments { get { return this.GetPropertyValue<string>("umbracoMemberComments"); } } ///<summary> /// Failed Password Attempts ///</summary> [ImplementPropertyType("umbracoMemberFailedPasswordAttempts")] public string UmbracoMemberFailedPasswordAttempts { get { return this.GetPropertyValue<string>("umbracoMemberFailedPasswordAttempts"); } } ///<summary> /// Last Lockout Date ///</summary> [ImplementPropertyType("umbracoMemberLastLockoutDate")] public string UmbracoMemberLastLockoutDate { get { return this.GetPropertyValue<string>("umbracoMemberLastLockoutDate"); } } ///<summary> /// Last Login Date ///</summary> [ImplementPropertyType("umbracoMemberLastLogin")] public string UmbracoMemberLastLogin { get { return this.GetPropertyValue<string>("umbracoMemberLastLogin"); } } ///<summary> /// Last Password Change Date ///</summary> [ImplementPropertyType("umbracoMemberLastPasswordChangeDate")] public string UmbracoMemberLastPasswordChangeDate { get { return this.GetPropertyValue<string>("umbracoMemberLastPasswordChangeDate"); } } ///<summary> /// Is Locked Out ///</summary> [ImplementPropertyType("umbracoMemberLockedOut")] public bool UmbracoMemberLockedOut { get { return this.GetPropertyValue<bool>("umbracoMemberLockedOut"); } } ///<summary> /// Password Answer ///</summary> [ImplementPropertyType("umbracoMemberPasswordRetrievalAnswer")] public string UmbracoMemberPasswordRetrievalAnswer { get { return this.GetPropertyValue<string>("umbracoMemberPasswordRetrievalAnswer"); } } ///<summary> /// Password Question ///</summary> [ImplementPropertyType("umbracoMemberPasswordRetrievalQuestion")] public string UmbracoMemberPasswordRetrievalQuestion { get { return this.GetPropertyValue<string>("umbracoMemberPasswordRetrievalQuestion"); } } } } // EOF
using System; using System.Collections.Generic; using CoreGraphics; using System.Linq; using System.Text; using Foundation; using UIKit; using ObjCRuntime; using CoreText; namespace SimpleTextInput { [Adopts ("UITextInput")] [Adopts ("UIKeyInput")] [Adopts ("UITextInputTraits")] [Register ("EditableCoreTextView")] public class EditableCoreTextView : UIView { StringBuilder text = new StringBuilder (); IUITextInputTokenizer tokenizer; SimpleCoreTextView textView; NSDictionary markedTextStyle; IUITextInputDelegate inputDelegate; public delegate void ViewWillEditDelegate (EditableCoreTextView editableCoreTextView); public event ViewWillEditDelegate ViewWillEdit; public EditableCoreTextView (CGRect frame) : base (frame) { // Add tap gesture recognizer to let the user enter editing mode UITapGestureRecognizer tap = new UITapGestureRecognizer (Tap) { ShouldReceiveTouch = delegate(UIGestureRecognizer recognizer, UITouch touch) { // If gesture touch occurs in our view, we want to handle it return touch.View == this; } }; AddGestureRecognizer (tap); // Create our tokenizer and text storage tokenizer = new UITextInputStringTokenizer (); // Create and set up our SimpleCoreTextView that will do the drawing textView = new SimpleCoreTextView (Bounds.Inset (5, 5)); textView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight; UserInteractionEnabled = true; AutosizesSubviews = true; AddSubview (textView); textView.Text = string.Empty; textView.UserInteractionEnabled = false; } protected override void Dispose (bool disposing) { markedTextStyle = null; tokenizer = null; text = null; textView = null; base.Dispose (disposing); } #region Custom user interaction // UIResponder protocol override - our view can become first responder to // receive user text input public override bool CanBecomeFirstResponder { get { return true; } } // UIResponder protocol override - called when our view is being asked to resign // first responder state (in this sample by using the "Done" button) public override bool ResignFirstResponder () { textView.IsEditing = false; return base.ResignFirstResponder (); } // Our tap gesture recognizer selector that enters editing mode, or if already // in editing mode, updates the text insertion point [Export ("Tap:")] public void Tap (UITapGestureRecognizer tap) { if (!IsFirstResponder) { // Inform controller that we're about to enter editing mode if (ViewWillEdit != null) ViewWillEdit (this); // Flag that underlying SimpleCoreTextView is now in edit mode textView.IsEditing = true; // Become first responder state (which shows software keyboard, if applicable) BecomeFirstResponder (); } else { // Already in editing mode, set insertion point (via selectedTextRange) // Find and update insertion point in underlying SimpleCoreTextView int index = textView.ClosestIndex (tap.LocationInView (textView)); textView.MarkedTextRange = new NSRange (NSRange.NotFound, 0); textView.SelectedTextRange = new NSRange (index, 0); } } #endregion #region UITextInput methods [Export ("inputDelegate")] public IUITextInputDelegate InputDelegate { get { return inputDelegate; } set { inputDelegate = value; } } [Export ("markedTextStyle")] public NSDictionary MarkedTextStyle { get { return markedTextStyle; } set { markedTextStyle = value; } } #region UITextInput - Replacing and Returning Text // UITextInput required method - called by text system to get the string for // a given range in the text storage [Export ("textInRange:")] string TextInRange (UITextRange range) { IndexedRange r = (IndexedRange) range; return text.ToString ().Substring ((int)r.Range.Location, (int)r.Range.Length); } // UITextInput required method - called by text system to replace the given // text storage range with new text [Export ("replaceRange:withText:")] void ReplaceRange (UITextRange range, string text) { IndexedRange r = (IndexedRange) range; NSRange selectedNSRange = textView.SelectedTextRange; // Determine if replaced range intersects current selection range // and update selection range if so. if (r.Range.Location + r.Range.Length <= selectedNSRange.Location) { // This is the easy case. selectedNSRange.Location -= (r.Range.Length - text.Length); } else { // Need to also deal with overlapping ranges. Not addressed // in this simplified sample. } // Now replace characters in text storage this.text.Remove ((int)r.Range.Location, (int)r.Range.Length); this.text.Insert ((int)r.Range.Location, text); // Update underlying SimpleCoreTextView textView.Text = this.text.ToString (); textView.SelectedTextRange = selectedNSRange; } #endregion #region UITextInput - Working with Marked and Selected Text // UITextInput selectedTextRange property accessor overrides // (access/update underlaying SimpleCoreTextView) [Export ("selectedTextRange")] IndexedRange SelectedTextRange { get { return IndexedRange.GetRange (textView.SelectedTextRange); } set { textView.SelectedTextRange = value.Range; } } // UITextInput markedTextRange property accessor overrides // (access/update underlaying SimpleCoreTextView) [Export ("markedTextRange")] IndexedRange MarkedTextRange { get { return IndexedRange.GetRange (textView.MarkedTextRange); } } // UITextInput required method - Insert the provided text and marks it to indicate // that it is part of an active input session. [Export ("setMarkedText:selectedRange:")] void SetMarkedText (string markedText, NSRange selectedRange) { NSRange selectedNSRange = textView.SelectedTextRange; NSRange markedTextRange = textView.MarkedTextRange; if (markedText == null) markedText = string.Empty; if (markedTextRange.Location != NSRange.NotFound) { // Replace characters in text storage and update markedText range length text.Remove ((int)markedTextRange.Location, (int)markedTextRange.Length); text.Insert ((int)markedTextRange.Location, markedText); markedTextRange.Length = markedText.Length; } else if (selectedNSRange.Length > 0) { // There currently isn't a marked text range, but there is a selected range, // so replace text storage at selected range and update markedTextRange. text.Remove ((int)selectedNSRange.Location, (int)selectedNSRange.Length); text.Insert ((int)selectedNSRange.Location, markedText); markedTextRange.Location = selectedNSRange.Location; markedTextRange.Length = markedText.Length; } else { // There currently isn't marked or selected text ranges, so just insert // given text into storage and update markedTextRange. text.Insert ((int)selectedNSRange.Location, markedText); markedTextRange.Location = selectedNSRange.Location; markedTextRange.Length = markedText.Length; } // Updated selected text range and underlying SimpleCoreTextView selectedNSRange = new NSRange (selectedRange.Location + markedTextRange.Location, selectedRange.Length); textView.Text = text.ToString (); textView.MarkedTextRange = markedTextRange; textView.SelectedTextRange = selectedNSRange; } // UITextInput required method - Unmark the currently marked text. [Export ("unmarkText")] void UnmarkText () { NSRange markedTextRange = textView.MarkedTextRange; if (markedTextRange.Location == NSRange.NotFound) return; // unmark the underlying SimpleCoreTextView.markedTextRange markedTextRange.Location = NSRange.NotFound; textView.MarkedTextRange = markedTextRange; } #endregion #region UITextInput - Computing Text Ranges and Text Positions // UITextInput beginningOfDocument property accessor override [Export ("beginningOfDocument")] IndexedPosition BeginningOfDocument { get { // For this sample, the document always starts at index 0 and is the full // length of the text storage return IndexedPosition.GetPosition (0); } } // UITextInput endOfDocument property accessor override [Export ("endOfDocument")] IndexedPosition EndOfDocument { get { // For this sample, the document always starts at index 0 and is the full // length of the text storage return IndexedPosition.GetPosition (text.Length); } } // UITextInput protocol required method - Return the range between two text positions // using our implementation of UITextRange [Export ("textRangeFromPosition:toPosition:")] IndexedRange GetTextRange (UITextPosition fromPosition, UITextPosition toPosition) { // Generate IndexedPosition instances that wrap the to and from ranges IndexedPosition @from = (IndexedPosition) fromPosition; IndexedPosition @to = (IndexedPosition) toPosition; NSRange range = new NSRange (Math.Min (@from.Index, @to.Index), Math.Abs (to.Index - @from.Index)); return IndexedRange.GetRange (range); } // UITextInput protocol required method - Returns the text position at a given offset // from another text position using our implementation of UITextPosition [Export ("positionFromPosition:offset:")] IndexedPosition GetPosition (UITextPosition position, int offset) { // Generate IndexedPosition instance, and increment index by offset IndexedPosition pos = (IndexedPosition) position; int end = pos.Index + offset; // Verify position is valid in document if (end > text.Length || end < 0) return null; return IndexedPosition.GetPosition (end); } // UITextInput protocol required method - Returns the text position at a given offset // in a specified direction from another text position using our implementation of // UITextPosition. [Export ("positionFromPosition:inDirection:offset:")] IndexedPosition GetPosition (UITextPosition position, UITextLayoutDirection direction, int offset) { // Note that this sample assumes LTR text direction IndexedPosition pos = (IndexedPosition) position; int newPos = pos.Index; switch (direction) { case UITextLayoutDirection.Right: newPos += offset; break; case UITextLayoutDirection.Left: newPos -= offset; break; case UITextLayoutDirection.Up: case UITextLayoutDirection.Down: // This sample does not support vertical text directions break; } // Verify new position valid in document if (newPos < 0) newPos = 0; if (newPos > text.Length) newPos = text.Length; return IndexedPosition.GetPosition (newPos); } #endregion #region UITextInput - Evaluating Text Positions // UITextInput protocol required method - Return how one text position compares to another // text position. [Export ("comparePosition:toPosition:")] NSComparisonResult ComparePosition (UITextPosition position, UITextPosition other) { IndexedPosition pos = (IndexedPosition) position; IndexedPosition o = (IndexedPosition) other; // For this sample, we simply compare position index values if (pos.Index == o.Index) { return NSComparisonResult.Same; } else if (pos.Index < o.Index) { return NSComparisonResult.Ascending; } else { return NSComparisonResult.Descending; } } // UITextInput protocol required method - Return the number of visible characters // between one text position and another text position. [Export ("offsetFromPosition:toPosition:")] int GetOffset (IndexedPosition @from, IndexedPosition toPosition) { return @from.Index - toPosition.Index; } #endregion #region UITextInput - Text Input Delegate and Text Input Tokenizer // UITextInput tokenizer property accessor override // // An input tokenizer is an object that provides information about the granularity // of text units by implementing the UITextInputTokenizer protocol. Standard units // of granularity include characters, words, lines, and paragraphs. In most cases, // you may lazily create and assign an instance of a subclass of // UITextInputStringTokenizer for this purpose, as this sample does. If you require // different behavior than this system-provided tokenizer, you can create a custom // tokenizer that adopts the UITextInputTokenizer protocol. [Export ("tokenizer")] IUITextInputTokenizer Tokenizer { get { return tokenizer; } } #endregion #region UITextInput - Text Layout, writing direction and position related methods // UITextInput protocol method - Return the text position that is at the farthest // extent in a given layout direction within a range of text. [Export ("positionWithinRange:farthestInDirection:")] IndexedPosition GetPosition (UITextRange range, UITextLayoutDirection direction) { // Note that this sample assumes LTR text direction IndexedRange r = (IndexedRange) range; int pos = (int)r.Range.Location; // For this sample, we just return the extent of the given range if the // given direction is "forward" in a LTR context (UITextLayoutDirectionRight // or UITextLayoutDirectionDown), otherwise we return just the range position switch (direction) { case UITextLayoutDirection.Up: case UITextLayoutDirection.Left: pos = (int)r.Range.Location; break; case UITextLayoutDirection.Right: case UITextLayoutDirection.Down: pos = (int)(r.Range.Location + r.Range.Length); break; } // Return text position using our UITextPosition implementation. // Note that position is not currently checked against document range. return IndexedPosition.GetPosition (pos); } // UITextInput protocol required method - Return a text range from a given text position // to its farthest extent in a certain direction of layout. [Export ("characterRangeByExtendingPosition:inDirection:")] IndexedRange GetCharacterRange (UITextPosition position, UITextLayoutDirection direction) { // Note that this sample assumes LTR text direction IndexedPosition pos = (IndexedPosition) position; NSRange result = new NSRange (pos.Index, 1); switch (direction) { case UITextLayoutDirection.Up: case UITextLayoutDirection.Left: result = new NSRange (pos.Index - 1, 1); break; case UITextLayoutDirection.Right: case UITextLayoutDirection.Down: result = new NSRange (pos.Index, 1); break; } // Return range using our UITextRange implementation // Note that range is not currently checked against document range. return IndexedRange.GetRange (result); } // UITextInput protocol required method - Return the base writing direction for // a position in the text going in a specified text direction. [Export ("baseWritingDirectionForPosition:inDirection:")] UITextWritingDirection GetBaseWritingDirection (UITextPosition position, UITextStorageDirection direction) { return UITextWritingDirection.LeftToRight; } // UITextInput protocol required method - Set the base writing direction for a // given range of text in a document. [Export ("setBaseWritingDirection:forRange:")] void SetBaseWritingDirection (UITextWritingDirection writingDirection, UITextRange range) { // This sample assumes LTR text direction and does not currently support BiDi or RTL. } #endregion #region UITextInput - Geometry methods // UITextInput protocol required method - Return the first rectangle that encloses // a range of text in a document. [Export ("firstRectForRange:")] CGRect FirstRect (UITextRange range) { // FIXME: the Objective-C code doesn't get a null range // This is the reason why we don't get the autocorrection suggestions // (it'll just autocorrect without showing any suggestions). // Possibly due to http://bugzilla.xamarin.com/show_bug.cgi?id=265 IndexedRange r = (IndexedRange) (range ?? IndexedRange.GetRange (new NSRange (0, 1))); // Use underlying SimpleCoreTextView to get rect for range CGRect rect = textView.FirstRect (r.Range); // Convert rect to our view coordinates return ConvertRectFromView (rect, textView); } // UITextInput protocol required method - Return a rectangle used to draw the caret // at a given insertion point. [Export ("caretRectForPosition:")] CGRect CaretRect (UITextPosition position) { // FIXME: the Objective-C code doesn't get a null position // This is the reason why we don't get the autocorrection suggestions // (it'll just autocorrect without showing any suggestions). // Possibly due to http://bugzilla.xamarin.com/show_bug.cgi?id=265 IndexedPosition pos = (IndexedPosition) (position ?? IndexedPosition.GetPosition (0)); // Get caret rect from underlying SimpleCoreTextView CGRect rect = textView.CaretRect (pos.Index); // Convert rect to our view coordinates return ConvertRectFromView (rect, textView); } #endregion #region UITextInput - Hit testing // Note that for this sample hit testing methods are not implemented, as there // is no implemented mechanic for letting user select text via touches. There // is a wide variety of approaches for this (gestures, drag rects, etc) and // any approach chosen will depend greatly on the design of the application. // UITextInput protocol required method - Return the position in a document that // is closest to a specified point. [Export ("closestPositionToPoint:")] UITextPosition ClosestPosition (CGPoint point) { // Not implemented in this sample. Could utilize underlying // SimpleCoreTextView:closestIndexToPoint:point return null; } // UITextInput protocol required method - Return the position in a document that // is closest to a specified point in a given range. [Export ("closestPositionToPoint:withinRange:")] UITextPosition ClosestPosition (CGPoint point, UITextRange range) { // Not implemented in this sample. Could utilize underlying // SimpleCoreTextView:closestIndexToPoint:point return null; } // UITextInput protocol required method - Return the character or range of // characters that is at a given point in a document. [Export ("characterRangeAtPoint:")] UITextRange CharacterRange (CGPoint point) { // Not implemented in this sample. Could utilize underlying // SimpleCoreTextView:closestIndexToPoint:point return null; } #endregion #region UITextInput - Returning Text Styling Information // UITextInput protocol method - Return a dictionary with properties that specify // how text is to be style at a certain location in a document. [Export ("textStylingAtPosition:inDirection:")] NSDictionary TextStyling (UITextPosition position, UITextStorageDirection direction) { // This sample assumes all text is single-styled, so this is easy. return new NSDictionary (CTStringAttributeKey.Font, textView.Font); } #endregion #region UIKeyInput methods // UIKeyInput required method - A Boolean value that indicates whether the text-entry // objects have any text. [Export ("hasText")] bool HasText { get { return text.Length > 0; } } // UIKeyInput required method - Insert a character into the displayed text. // Called by the text system when the user has entered simple text [Export ("insertText:")] void InsertText (string text) { NSRange selectedNSRange = textView.SelectedTextRange; NSRange markedTextRange = textView.MarkedTextRange; // Note: While this sample does not provide a way for the user to // create marked or selected text, the following code still checks for // these ranges and acts accordingly. if (markedTextRange.Location != NSRange.NotFound) { // There is marked text -- replace marked text with user-entered text this.text.Remove ((int)markedTextRange.Location, (int)markedTextRange.Length); this.text.Insert ((int)markedTextRange.Location, text); selectedNSRange.Location = markedTextRange.Location + text.Length; selectedNSRange.Length = 0; markedTextRange = new NSRange (NSRange.NotFound, 0); } else if (selectedNSRange.Length > 0) { // Replace selected text with user-entered text this.text.Remove ((int)selectedNSRange.Location, (int)selectedNSRange.Length); this.text.Insert ((int)selectedNSRange.Location, text); selectedNSRange.Length = 0; selectedNSRange.Location += text.Length; } else { // Insert user-entered text at current insertion point this.text.Insert ((int)selectedNSRange.Location, text); selectedNSRange.Location += text.Length; } // Update underlying SimpleCoreTextView textView.Text = this.text.ToString (); textView.MarkedTextRange = markedTextRange; textView.SelectedTextRange = selectedNSRange; } // UIKeyInput required method - Delete a character from the displayed text. // Called by the text system when the user is invoking a delete (e.g. pressing // the delete software keyboard key) [Export ("deleteBackward")] void DeleteBackward () { NSRange selectedNSRange = textView.SelectedTextRange; NSRange markedTextRange = textView.MarkedTextRange; // Note: While this sample does not provide a way for the user to // create marked or selected text, the following code still checks for // these ranges and acts accordingly. if (markedTextRange.Location != NSRange.NotFound) { // There is marked text, so delete it text.Remove ((int)markedTextRange.Location, (int)markedTextRange.Length); selectedNSRange.Location = markedTextRange.Location; selectedNSRange.Length = 0; markedTextRange = new NSRange (NSRange.NotFound, 0); } else if (selectedNSRange.Length > 0) { // Delete the selected text text.Remove ((int)selectedNSRange.Location, (int)selectedNSRange.Length); selectedNSRange.Length = 0; } else if (selectedNSRange.Location > 0) { // Delete one char of text at the current insertion point selectedNSRange.Location--; selectedNSRange.Length = 1; text.Remove ((int)selectedNSRange.Location, (int)selectedNSRange.Length); selectedNSRange.Length = 0; } // Update underlying SimpleCoreTextView textView.Text = text.ToString (); textView.MarkedTextRange = markedTextRange; textView.SelectedTextRange = selectedNSRange; } } #endregion #endregion }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.Common; using System.Drawing; using System.Windows.Forms; using System.Text; using Epi; using Epi.Data; using Epi.Windows.Dialogs; namespace Epi.Windows.MakeView.Dialogs { /// <summary> /// Dialog for Read command /// </summary> public partial class ReadDialog : DialogBase { /// <summary> /// Selected Table /// </summary> public string SelectedTable = null; /// <summary> /// New View Name /// </summary> public string NewViewName = null; private bool ButtonOkClicked = false; /// <summary> /// Selected DataSource /// </summary> public IDbDriver SelectedDataSource { get { if (this.selectedDataSource == null) { return null; } else { if (this.selectedDataSource is Project) { Project P = (Project)this.selectedDataSource; IDbDriver result = this.GetDbDriver(P.CollectedDataDriver); result.ConnectionString = P.CollectedDataConnectionString; return result; } else { return (IDbDriver)this.selectedDataSource; } } } } #region Private Nested Class private class ComboBoxItem { #region Implementation private string key; public string Key { get { return key; } set { key = value; } } private object value; public object Value { get { return this.value; } set { this.value = value; } } private string text; public string Text { get { return text; } set { text = value; } } public ComboBoxItem(string key, string text, object value) { this.key = key; this.value = value; this.text = text; } public override string ToString() { return text.ToString(); } #endregion } #endregion Private Nested Class #region Private Attributes private Project sourceProject; private Project selectedProject; private object selectedDataSource; private System.Collections.Hashtable SourceProjectNames; private bool ignoreDataFormatIndexChange = false; //--Ei-148 List<string> Sourcedatatables = new List<string>(); List<string> SourceNonViewnames = new List<string>(); private int count = 1; //-- #endregion Private Attributes #region Constructor /// <summary> /// Default constructor - NOT TO BE USED FOR INSTANTIATION /// </summary> [Obsolete("Use of default constructor not allowed", true)] protected ReadDialog() { InitializeComponent(); } /// <summary> /// Constructor for Read dialog /// </summary> public ReadDialog(Epi.Windows.MakeView.Forms.MakeViewMainForm frm) : base(frm) { InitializeComponent(); Construct(); SourceProjectNames = new Hashtable(); if (frm.projectExplorer != null) { if (frm.projectExplorer.currentPage != null) { this.sourceProject = frm.projectExplorer.currentPage.view.Project; this.selectedProject = this.sourceProject; this.selectedDataSource = this.selectedProject; //--EI-48 //Adds datatable names to viewlist to enable other tables in project List<string> SourceViewnames = this.sourceProject.GetViewNames(); SourceNonViewnames = this.sourceProject.GetNonViewTableNames(); foreach(string str in SourceViewnames) { View MView = this.sourceProject.GetViewByName(str); DataTable ViewPages = MView.GetMetadata().GetPagesForView(MView.Id); foreach(DataRow dt in ViewPages.Rows) { string ViewdataTable = MView.TableName + dt[ColumnNames.PAGE_ID]; Sourcedatatables.Add(ViewdataTable); } if (SourceNonViewnames.Contains(str)) { SourceNonViewnames.Remove(str); } } foreach(string str in Sourcedatatables) { SourceViewnames.Add(str); if (SourceNonViewnames.Contains(str)) { SourceNonViewnames.Remove(str);} } //-- foreach (string s in this.sourceProject.GetNonViewTableNames()) { string key = s.ToUpperInvariant().Trim(); if (!SourceProjectNames.Contains(key)) { if (SourceViewnames.Contains(s)) { SourceProjectNames.Add(key, true); } } } foreach (string s in this.sourceProject.GetViewNames()) { string key = s.ToUpperInvariant().Trim(); if (!SourceProjectNames.Contains(key)) { SourceProjectNames.Add(key, true); } } } } } #endregion Constructor #region Private Methods private void Construct() { if (!this.DesignMode) // designer throws an error { //this.btnOK.Click += new System.EventHandler(this.btnOK_Click); } } private void LoadForm() { PopulateDataSourcePlugIns(); /* IProjectHost host = Module.GetService(typeof(IProjectHost)) as IProjectHost; try { Project project = null; if (host != null) { project = host.CurrentProject; } project = Epi.Core.Interpreter.Reduction.CurrentProject; if (project != null) { this.selectedProject = project; this.selectedDataSource = project; } } catch (CurrentProjectInvalidException ex) { if (host != null) { host.CurrentProject = null; } Epi.Windows.MsgBox.ShowInformation(ex.Message); //throw; }*/ RefreshForm(); } private void RefreshForm() { lvDataSourceObjects.Groups.Clear(); lvDataSourceObjects.Items.Clear(); //txtCurrentProj.Text = (selectedProject == null) ? "(none)" : selectedProject.FullName; if (selectedDataSource is IDbDriver) { IDbDriver db = selectedDataSource as IDbDriver; this.txtDataSource.Text = db.ConnectionString; List<string> tableNames = db.GetTableNames(); foreach (string tableName in tableNames) { ListViewItem newItem = new ListViewItem(new string[] { tableName, tableName }); this.lvDataSourceObjects.Items.Add(newItem); } gbxExplorer.Enabled = true; } else if (selectedDataSource is Project) { Project project = selectedDataSource as Project; txtDataSource.Text = (selectedDataSource == selectedProject) ? SharedStrings.CURRENT_PROJECT : project.FullName; ListViewGroup tablesGroup = new ListViewGroup("Tables"); this.lvDataSourceObjects.Groups.Add(tablesGroup); foreach (string s in project.GetNonViewTableNames()) { ListViewItem newItem = new ListViewItem(new string[] { s, "Table" }, tablesGroup); this.lvDataSourceObjects.Items.Add(newItem); } gbxExplorer.Enabled = true; } else { // Clear ... this.txtDataSource.Text = "(none)"; this.lvDataSourceObjects.Items.Clear();// DataSource = null; gbxExplorer.Enabled = false; } this.CheckForInputSufficiency(); } /// <summary> /// Attach the DataFormats combobox with supported data formats /// </summary> private void PopulateDataSourcePlugIns() { try { Configuration config = Configuration.GetNewInstance(); ignoreDataFormatIndexChange = true; if (cmbDataSourcePlugIns.Items.Count == 0) { cmbDataSourcePlugIns.Items.Clear(); //cmbDataSourcePlugIns.Items.Add(new ComboBoxItem(null, "Epi Info 7 Project", null)); foreach (Epi.DataSets.Config.DataDriverRow row in config.DataDrivers) { cmbDataSourcePlugIns.Items.Add(new ComboBoxItem(row.Type,row.DisplayName,null)); } } cmbDataSourcePlugIns.SelectedIndex = 0; } finally { ignoreDataFormatIndexChange = false; } } private void OpenSelectProjectDialog() { try { Project oldSelectedProject = this.selectedProject; Project newSelectedProject = base.SelectProject(); if (newSelectedProject != null) { this.selectedProject = newSelectedProject; if (oldSelectedProject != newSelectedProject) { SetDataSourceToSelectedProject(); } this.RefreshForm(); } } catch (Exception ex) { MsgBox.ShowException(ex); } } private void SetDataSourceToSelectedProject() { this.selectedDataSource = selectedProject; this.cmbDataSourcePlugIns.SelectedIndex = 0; } private void OpenSelectDataSourceDialog() { ComboBoxItem selectedPlugIn = cmbDataSourcePlugIns.SelectedItem as ComboBoxItem; if (selectedPlugIn == null) { throw new GeneralException("No data source plug-in is selected in combo box."); } if (selectedPlugIn.Key == null) // default project { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Title = SharedStrings.SELECT_DATA_SOURCE; openFileDialog.Filter = "Epi Info " + SharedStrings.PROJECT_FILE + " (*.prj)|*.prj"; openFileDialog.FilterIndex = 1; openFileDialog.Multiselect = false; DialogResult result = openFileDialog.ShowDialog(); if (result == DialogResult.OK) { string filePath = openFileDialog.FileName.Trim(); if (System.IO.File.Exists(filePath)) { try { IProjectManager manager = Module.GetService(typeof(IProjectManager)) as IProjectManager; if (manager == null) { throw new GeneralException("Project manager is not registered."); } selectedDataSource = manager.OpenProject(filePath); this.SelectedTable = null; } catch (Exception ex) { MessageBox.Show("Could not load project: \n\n" + ex.Message); return; } } } } else { IDbDriverFactory dbFactory = null; switch(selectedPlugIn.Key) { case Configuration.SqlDriver://"Epi.Data.SqlServer.SqlDBFactory, Epi.Data.SqlServer": dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.SqlDriver); break; case Configuration.MySQLDriver: //"Epi.Data.MySQL.MySQLDBFactory, Epi.Data.MySQL": dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.MySQLDriver); break; case Configuration.PostgreSQLDriver: dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.PostgreSQLDriver); break; case Configuration.ExcelDriver: dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.ExcelDriver); break; case Configuration.Excel2007Driver: dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.Excel2007Driver); break; case Configuration.AccessDriver: //"Epi.Data.Office.AccessDBFactory, Epi.Data.Office": dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.AccessDriver); break; case Configuration.Access2007Driver: dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.Access2007Driver); break; case Configuration.CsvDriver: dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.CsvDriver); break; case Configuration.WebDriver: //"Epi.Data.WebDriver": dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.WebDriver); break; default: dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.AccessDriver); break; } DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder(); IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder); //IDbDriver db = DatabaseFactoryCreator.CreateDatabaseInstance(selectedPlugIn.Key); //IConnectionStringGui dialog = db.GetConnectionStringGuiForExistingDb(); ////IConnectionStringGui dialog = this.selectedProject.Metadata.DBFactory.GetConnectionStringGuiForExistingDb(); IConnectionStringGui dialog = dbFactory.GetConnectionStringGuiForExistingDb(); DialogResult result = ((Form)dialog).ShowDialog(); if (result == DialogResult.OK) { bool success = false; db.ConnectionString = dialog.DbConnectionStringBuilder.ToString() ; txtDataSource.Text = db.ConnectionDescription; try { success = db.TestConnection(); } catch { success = false; MessageBox.Show("Could not connect to selected data source."); } if (success) { this.selectedDataSource = db; this.SelectedTable = null; } else { this.selectedDataSource = null; this.SelectedTable = null; } } else { this.selectedDataSource = null; this.SelectedTable = null; } } RefreshForm(); } #endregion Private Methods #region Protected Methods /// <summary> /// Validates input /// </summary> /// <returns>true if validation passes; else false</returns> protected override bool ValidateInput() { base.ValidateInput (); if (string.IsNullOrEmpty(this.txtViewName.Text)) { ErrorMessages.Add(SharedStrings.SPECIFY_PROJECT); }/* if (cmbDataSourcePlugIns.SelectedIndex == -1) { ErrorMessages.Add(SharedStrings.SPECIFY_DATAFORMAT); }*/ if (string.IsNullOrEmpty(txtDataSource.Text)) { ErrorMessages.Add(SharedStrings.SPECIFY_DATASOURCE); } if (this.lvDataSourceObjects.SelectedIndices.Count == 0) { ErrorMessages.Add(SharedStrings.SPECIFY_TABLE_OR_VIEW); } return (ErrorMessages.Count == 0); } /// <summary> /// Checks if the input provided is sufficient and enables control buttons accordingly. /// </summary> public override void CheckForInputSufficiency() { bool inputValid = ValidateInput(); if (inputValid && !string.IsNullOrEmpty(txtViewName.Text) && txtViewName.Text != "enter new view name") { if (!this.SourceProjectNames.Contains(txtViewName.Text.ToUpperInvariant().Trim())) { btnOK.Enabled = true; NewViewName = txtViewName.Text; } else { btnOK.Enabled = false; NewViewName = null; } } else { btnOK.Enabled = false; NewViewName = null; } } #endregion Protected Methods #region Event Handlers private void ReadDialog_Load(object sender, System.EventArgs e) { LoadForm(); } private void btnFindProject_Click(object sender, System.EventArgs e) { OpenSelectProjectDialog(); } private void cmbDataSourcePlugIns_SelectedIndexChanged(object sender, System.EventArgs e) { if (ignoreDataFormatIndexChange) return; this.selectedDataSource = null; // TODO: Review this code. Select known database driver from configuration or prj file this.RefreshForm(); } private void btnClear_Click(object sender, System.EventArgs e) { lvDataSourceObjects.SelectedItems.Clear(); SetDataSourceToSelectedProject(); } private void txtCurrentProj_TextChanged(object sender, System.EventArgs e) { //CheckForInputSufficiency(); } private void txtDataSource_TextChanged(object sender, System.EventArgs e) { //CheckForInputSufficiency(); } private void btnFindDataSource_Click(object sender, System.EventArgs e) { OpenSelectDataSourceDialog(); } private void lvDataSourceObjects_SelectedIndexChanged(object sender, System.EventArgs e) { ListView LV = ((ListView)sender); if (LV.SelectedItems.Count > 0) { this.SelectedTable = LV.SelectedItems[0].Text; this.txtViewName.Text = this.SelectedTable.Replace("$", string.Empty); //---Ei-48 if (SourceNonViewnames.Contains(txtViewName.Text)) { txtViewName.Text = txtViewName.Text + count.ToString(); } // } else { this.SelectedTable = null; } CheckForInputSufficiency(); } private void lvDataSourceObjects_DataSourceChanged(object sender, System.EventArgs e) { if (lvDataSourceObjects.Items.Count > 0) { lvDataSourceObjects.SelectedIndices.Clear(); } } private void lvDataSourceObjects_Resize(object sender, EventArgs e) { // leave space for scroll bar this.lvDataSourceObjects.Columns[0].Width = this.lvDataSourceObjects.Width - 25; } private void lvDataSourceObjects_DoubleClick(object sender, EventArgs e) { if (this.btnOK.Enabled) { ListBox LB = ((ListBox)sender); if (LB.SelectedIndex > -1) { this.SelectedTable = LB.SelectedItem.ToString(); } else { this.SelectedTable = null; } //btnOK_Click(sender, e); } } #endregion Event Handlers private void btnOK_Click(object sender, EventArgs e) { bool valid = true; string validationMessage = string.Empty; valid = View.IsValidViewName(txtViewName.Text, ref validationMessage); if (!valid) { MsgBox.ShowError(validationMessage); return; } //---Ei-48 //case where tablename exists in current project if (SourceNonViewnames.Contains(txtViewName.Text.Trim())) { validationMessage = SharedStrings.INVALID_VIEW_NAME_DUPLICATE + " " + txtViewName.Text ; MsgBox.ShowError(validationMessage); return; } //-- ButtonOkClicked = true; this.Close(); } private void btnCancel_Click(object sender, EventArgs e) { this.selectedProject = null; this.selectedDataSource = null; this.SelectedTable = null; this.Close(); } private IDbDriver GetDbDriver(string pKey) { IDbDriverFactory dbFactory = null; switch (pKey) { case "Epi.Data.SqlServer.SqlDBFactory, Epi.Data.SqlServer": dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.SqlDriver); break; case "Epi.Data.MySQL.MySQLDBFactory, Epi.Data.MySQL": dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.MySQLDriver); break; case "Epi.Data.Office.AccessDBFactory, Epi.Data.Office": dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.AccessDriver); break; //case "": // dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.ExcelDriver); // break; default: dbFactory = DbDriverFactoryCreator.GetDbDriverFactory(Configuration.AccessDriver); break; } DbConnectionStringBuilder dbCnnStringBuilder = new DbConnectionStringBuilder(); IDbDriver db = dbFactory.CreateDatabaseObject(dbCnnStringBuilder); db.ConnectionString = dbCnnStringBuilder.ToString(); return db; } private void txtViewName_TextChanged(object sender, EventArgs e) { CheckForInputSufficiency(); } private void ReadDialog_FormClosing(object sender, FormClosingEventArgs e) { if (!ButtonOkClicked) { this.selectedProject = null; this.selectedDataSource = null; this.SelectedTable = null; } } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure; using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Reflection; namespace Microsoft.Azure.Commands.Compute.Automation { public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet { protected object CreateVirtualMachineScaleSetCreateOrUpdateDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pName = new RuntimeDefinedParameter(); pName.Name = "Name"; pName.ParameterType = typeof(string); pName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("Name", pName); var pParameters = new RuntimeDefinedParameter(); pParameters.Name = "VirtualMachineScaleSet"; pParameters.ParameterType = typeof(VirtualMachineScaleSet); pParameters.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true }); pParameters.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VirtualMachineScaleSet", pParameters); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 4, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return dynamicParameters; } protected void ExecuteVirtualMachineScaleSetCreateOrUpdateMethod(object[] invokeMethodInputParameters) { string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]); string name = (string)ParseParameter(invokeMethodInputParameters[1]); VirtualMachineScaleSet parameters = (VirtualMachineScaleSet)ParseParameter(invokeMethodInputParameters[2]); var result = VirtualMachineScaleSetsClient.CreateOrUpdate(resourceGroupName, name, parameters); WriteObject(result); } } public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet { protected PSArgument[] CreateVirtualMachineScaleSetCreateOrUpdateParameters() { string resourceGroupName = string.Empty; string name = string.Empty; VirtualMachineScaleSet parameters = new VirtualMachineScaleSet(); return ConvertFromObjectsToArguments( new string[] { "ResourceGroupName", "Name", "Parameters" }, new object[] { resourceGroupName, name, parameters }); } } [Cmdlet("New", "AzureRmVmss", DefaultParameterSetName = "InvokeByDynamicParameters", SupportsShouldProcess = true)] public partial class NewAzureRmVmss : InvokeAzureComputeMethodCmdlet { public override string MethodName { get; set; } protected override void ProcessRecord() { this.MethodName = "VirtualMachineScaleSetCreateOrUpdate"; if (ShouldProcess(this.dynamicParameters["Name"].Value.ToString(), VerbsCommon.New)) { base.ProcessRecord(); } } public override object GetDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true, ValueFromPipeline = false }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pName = new RuntimeDefinedParameter(); pName.Name = "Name"; pName.ParameterType = typeof(string); pName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true, ValueFromPipeline = false }); pName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("Name", pName); var pParameters = new RuntimeDefinedParameter(); pParameters.Name = "VirtualMachineScaleSet"; pParameters.ParameterType = typeof(VirtualMachineScaleSet); pParameters.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true, ValueFromPipeline = true }); pParameters.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VirtualMachineScaleSet", pParameters); return dynamicParameters; } } [Cmdlet("Update", "AzureRmVmss", DefaultParameterSetName = "InvokeByDynamicParameters", SupportsShouldProcess = true)] public partial class UpdateAzureRmVmss : InvokeAzureComputeMethodCmdlet { public override string MethodName { get; set; } protected override void ProcessRecord() { this.MethodName = "VirtualMachineScaleSetCreateOrUpdate"; if (ShouldProcess(this.dynamicParameters["Name"].Value.ToString(), VerbsData.Update)) { base.ProcessRecord(); } } public override object GetDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true, ValueFromPipeline = false }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pName = new RuntimeDefinedParameter(); pName.Name = "Name"; pName.ParameterType = typeof(string); pName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true, ValueFromPipeline = false }); pName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("Name", pName); var pParameters = new RuntimeDefinedParameter(); pParameters.Name = "VirtualMachineScaleSet"; pParameters.ParameterType = typeof(VirtualMachineScaleSet); pParameters.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true, ValueFromPipeline = true }); pParameters.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VirtualMachineScaleSet", pParameters); return dynamicParameters; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using LCAToolAPI.Areas.HelpPage.ModelDescriptions; using LCAToolAPI.Areas.HelpPage.Models; namespace LCAToolAPI.Areas.HelpPage { /// <summary> /// Help Page configuration extensions. /// </summary> public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Reflection; using System.Web; using bv.common.Core; using bv.common.Diagnostics; //[assembly: InternalsVisibleTo("bv_tests")] namespace bv.common.Configuration { //This class loads configuration settings from <appSettings> section of several configuration classes using the next rules: //1. It searches the directory where the executable or bv_common.dll is placed (current directory) //2. It searches top level general config file (eidds_general.config) starting the current directory and MaxRecursiveLevel leveles up. // if file is found the settings are readed from this file //2. It searches first machine dependant general_MACHINEMAME.config file starting the current directory and MaxRecursiveLevel leveles up. // if file is found the settings are readed from this file //3. it searches executableName.config for windows app in the Application.UserAppDataPath directory // if file is found the settings are readed from this file. //4. it searches executableName.config for windows app in the Application.CommonAppDataPath directory // if file is found the settings are readed from this file. //5. It searches local congig file (executableName.config for windows app and web.config for ASP.NET app) // starting the current directory and 3 leveles up. // if file is found the settings are readed from this file. //5. Existing setings that are read already and exist in the current file are not overritten. // Configuration file priority is eidds_general.config ->general_MACHINEMAME.config->bv.config->local config. public class Config { private const int MaxRecursiveLevel = 4; internal static IDictionary<string, string> m_Settings; private static string m_ConfigFileName; private static string m_LocalConfigFileName; private static readonly string m_MachineConfigName = string.Format("general_{0}.config", Environment.MachineName); private const string GeneralConfigName = "eidss_general.config"; private static string m_LocalConfigName = ""; private static bool m_Intialized; private static int m_RecursiveLevel; private Config() { // NOOP } internal static IDictionary<string, string> Settings { get { return m_Settings; } } public static bool IsInitialized { get { return m_Intialized; } } internal static string AppConfigFileName { get { Assembly asm = Assembly.GetEntryAssembly(); if (asm != null) { return Path.GetFileName(asm.Location) + ".config"; } return ""; } } public static string FileName { get { return m_ConfigFileName; } set { m_LocalConfigFileName = value; } } public static string MachineConfigName { get { return m_MachineConfigName; } } public static void InitSettingsWithDir(string dir) { InitSettings(dir); } internal static void InitSettings(string dir = null) { if (m_Settings != null) { return; } m_Settings = new Dictionary<string, string>(); if (m_LocalConfigFileName == null) { LoadGeneralSettings(); LoadMachineGeneralSettings(dir); LoadWinUserSettings(); LoadWinAppSettings(); } LoadLocalSettings(); m_Intialized = true; } public static void ReloadSettings() { m_Intialized = false; m_Settings = null; InitSettings(); } private static void LoadSettings(string fileName) { if (!File.Exists(fileName)) { return; } var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = fileName }; System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel .None); foreach (string key in config.AppSettings.Settings.AllKeys) { //Dbg.Assert(!Utils.IsEmpty(key), "setting key not specified", null); string value = config.AppSettings.Settings[key].Value; //Dbg.Assert(Not Utils.IsEmpty(value), "setting value not specified") if (!m_Settings.ContainsKey(key)) { m_Settings.Add(key, value); } else { Dbg.Debug("duplicate key <{0}> in file {1}", key, fileName); } } } private static void LoadWinUserSettings() { if (HttpContext.Current == null && !string.IsNullOrEmpty(UserConfigWriter.Instance.FileName)) { LoadSettings(UserConfigWriter.Instance.FileName); } } private static void LoadWinAppSettings() { if (HttpContext.Current == null && !string.IsNullOrEmpty(AppConfigWriter.Instance.FileName)) { LoadSettings(AppConfigWriter.Instance.FileName); } } private static void LoadGeneralSettings() { FindGeneralConfigFile(); if (!Utils.IsEmpty(m_ConfigFileName)) { LoadSettings(m_ConfigFileName); } } private static void LoadMachineGeneralSettings(string dir) { FindMachineGeneralConfigFile(dir); if (!Utils.IsEmpty(m_ConfigFileName)) { LoadSettings(m_ConfigFileName); } } private static void LoadLocalSettings() { if (Utils.IsEmpty(m_LocalConfigFileName)) { FindLocalConfigFile(); } else { m_ConfigFileName = m_LocalConfigFileName; } if (!Utils.IsEmpty(m_ConfigFileName)) { LoadSettings(m_ConfigFileName); } } public static void FindMachineGeneralConfigFile(string appLocation) { m_ConfigFileName = null; appLocation = appLocation ?? GetConfigFileDir(); string appPath = Path.GetDirectoryName(appLocation); if (appPath == null) return; var dir = new DirectoryInfo(appPath); if (!FindFileRecursive(dir, m_MachineConfigName)) { Dbg.Debug("unable to locate machine config via application root path"); } } private static readonly string m_CommonApplicationDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "\\EIDSS"; private static readonly string m_DefaultGeneralConfigPath = m_CommonApplicationDataFolder + "\\" + GeneralConfigName; public string DefaultGeneralConfigPath { get { return m_DefaultGeneralConfigPath; } } public static void FindGeneralConfigFile() { m_ConfigFileName = null; string appLocation = GetConfigFileDir(); string appPath = Path.GetDirectoryName(appLocation); if (appPath == null) return; var dir = new DirectoryInfo(appPath); if (!FindFileRecursive(dir, GeneralConfigName)) { if (FindConfigFileInFolder(m_CommonApplicationDataFolder, GeneralConfigName)) return; if (CreateGeneralConfig()) { if (FindConfigFileInFolder(m_CommonApplicationDataFolder, GeneralConfigName)) return; } Dbg.Debug("unable to locate machine config via application root path"); } } public static bool CreateGeneralConfig() { try { if (File.Exists(m_DefaultGeneralConfigPath)) return true; if (!Directory.Exists(m_CommonApplicationDataFolder)) { Directory.CreateDirectory(m_CommonApplicationDataFolder); } var config = new ConfigWriter(); config.Read(m_DefaultGeneralConfigPath); return config.Save(); } catch (Exception ex) { Dbg.Debug("Error during creating general config file {0}: {1}", m_DefaultGeneralConfigPath, ex); return false; } } public static void FindLocalConfigFile() { m_ConfigFileName = null; string appLocation = GetConfigFileDir(); string appPath = Path.GetDirectoryName(appLocation); if (appPath == null) return; var dir = new DirectoryInfo(appPath); if (HttpContext.Current != null) { m_LocalConfigName = "Web.config"; } else { m_LocalConfigName = AppConfigFileName; if (m_LocalConfigName == "") { return; } } if (!FindFileRecursive(dir, m_LocalConfigName)) { Dbg.Debug("unable to locate app config via application root path"); } } public static string GetConfigFileDir() { return Utils.GetExecutingPath(); } public static bool FindConfigFileInFolder(string dir, string fileName) { if (!dir.EndsWith("\\")) { dir = dir + "\\"; } string configPath = dir + fileName; if (File.Exists(configPath)) { m_ConfigFileName = configPath; return true; } return false; } public static string GetSetting(string key, string defaultValue = "") { InitSettings(); if (m_Settings.ContainsKey(key)) { return m_Settings[key]; } return defaultValue; } public static bool GetBoolSetting(string key, bool defaultValue = false) { string setting = GetSetting(key, null); if (Utils.Str(setting).ToLowerInvariant() == "true") { return true; } if (Utils.Str(setting).ToLowerInvariant() == "false") { return false; } return defaultValue; } public static int GetIntSetting(string key, int defaultValue) { string setting = GetSetting(key, null); int value; if (int.TryParse(setting, out value)) { return value; } return defaultValue; } public static double GetDoubleSetting(string key, double defaultValue) { string setting = GetSetting(key, null); double value; if (double.TryParse(setting, out value)) { return value; } return defaultValue; } private static bool FindFileRecursive(DirectoryInfo dir, string fileName) { if (m_RecursiveLevel >= MaxRecursiveLevel || dir == null) { return false; } m_RecursiveLevel += 1; try { if (FindConfigFileInFolder(dir.FullName, fileName)) { return true; } if (dir.Parent == null) { return false; } return FindFileRecursive(dir.Parent, fileName); } catch (Exception ex) { Dbg.Debug("error during cofig reading: {0}", ex); return false; } finally { m_RecursiveLevel -= 1; } } } }
/* * Cellstore API * * <h3>CellStore API</h3> * * OpenAPI spec version: vX.X.X * Contact: support@28.io * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Reflection; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace CellStore.Client { /// <summary> /// Represents a set of configuration settings /// </summary> public class Configuration { /// <summary> /// Initializes a new instance of the Configuration class with different settings /// </summary> /// <param name="apiClient">Api client</param> /// <param name="defaultHeader">Dictionary of default HTTP header</param> /// <param name="username">Username</param> /// <param name="password">Password</param> /// <param name="accessToken">accessToken</param> /// <param name="apiKey">Dictionary of API key</param> /// <param name="apiKeyPrefix">Dictionary of API key prefix</param> /// <param name="tempFolderPath">Temp folder path</param> /// <param name="dateTimeFormat">DateTime format string</param> /// <param name="timeout">HTTP connection timeout (in milliseconds)</param> /// <param name="userAgent">HTTP user agent</param> public Configuration(ApiClient apiClient = null, Dictionary<String, String> defaultHeader = null, string username = null, string password = null, string accessToken = null, Dictionary<String, String> apiKey = null, Dictionary<String, String> apiKeyPrefix = null, string tempFolderPath = null, string dateTimeFormat = null, int timeout = 1800000, string userAgent = "Swagger-Codegen/5.5.1/csharp" ) { setApiClientUsingDefault(apiClient); Username = username; Password = password; AccessToken = accessToken; UserAgent = userAgent; if (defaultHeader != null) DefaultHeader = defaultHeader; if (apiKey != null) ApiKey = apiKey; if (apiKeyPrefix != null) ApiKeyPrefix = apiKeyPrefix; TempFolderPath = tempFolderPath; DateTimeFormat = dateTimeFormat; Timeout = timeout; } /// <summary> /// Initializes a new instance of the Configuration class. /// </summary> /// <param name="apiClient">Api client.</param> public Configuration(ApiClient apiClient) { setApiClientUsingDefault(apiClient); } /// <summary> /// Version of the package. /// </summary> /// <value>Version of the package.</value> public const string Version = "5.5.1"; /// <summary> /// Gets or sets the default Configuration. /// </summary> /// <value>Configuration.</value> public static Configuration Default = new Configuration(); /// <summary> /// Default creation of exceptions for a given method name and response object /// </summary> public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, request, response) => { int status = (int) response.StatusCode; if (status >= 400) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.Content), request, response); if (status == 0) return new ApiException(status, String.Format("Error calling {0}: {1}", methodName, response.ErrorMessage), request, response); return null; }; /// <summary> /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 1800000 milliseconds. /// </summary> /// <value>Timeout.</value> public int Timeout { get { return ApiClient.RestClient.Timeout; } set { if (ApiClient != null) ApiClient.RestClient.Timeout = value; } } /// <summary> /// Gets or sets the default API client for making HTTP calls. /// </summary> /// <value>The API client.</value> public ApiClient ApiClient; /// <summary> /// Set the ApiClient using Default or ApiClient instance. /// </summary> /// <param name="apiClient">An instance of ApiClient.</param> /// <returns></returns> public void setApiClientUsingDefault (ApiClient apiClient = null) { if (apiClient == null) { if (Default != null && Default.ApiClient == null) Default.ApiClient = new ApiClient(); ApiClient = Default != null ? Default.ApiClient : new ApiClient(); } else { if (Default != null && Default.ApiClient == null) Default.ApiClient = apiClient; ApiClient = apiClient; } } private Dictionary<String, String> _defaultHeaderMap = new Dictionary<String, String>(); /// <summary> /// Gets or sets the default header. /// </summary> public Dictionary<String, String> DefaultHeader { get { return _defaultHeaderMap; } set { _defaultHeaderMap = value; } } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> public void AddDefaultHeader(string key, string value) { _defaultHeaderMap[key] = value; } /// <summary> /// Add Api Key Header. /// </summary> /// <param name="key">Api Key name.</param> /// <param name="value">Api Key value.</param> /// <returns></returns> public void AddApiKey(string key, string value) { ApiKey[key] = value; } /// <summary> /// Sets the API key prefix. /// </summary> /// <param name="key">Api Key name.</param> /// <param name="value">Api Key value.</param> public void AddApiKeyPrefix(string key, string value) { ApiKeyPrefix[key] = value; } /// <summary> /// Gets or sets the HTTP user agent. /// </summary> /// <value>Http user agent.</value> public String UserAgent { get; set; } /// <summary> /// Gets or sets the username (HTTP basic authentication). /// </summary> /// <value>The username.</value> public String Username { get; set; } /// <summary> /// Gets or sets the password (HTTP basic authentication). /// </summary> /// <value>The password.</value> public String Password { get; set; } /// <summary> /// Gets or sets the access token for OAuth2 authentication. /// </summary> /// <value>The access token.</value> public String AccessToken { get; set; } /// <summary> /// Gets or sets the API key based on the authentication name. /// </summary> /// <value>The API key.</value> public Dictionary<String, String> ApiKey = new Dictionary<String, String>(); /// <summary> /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. /// </summary> /// <value>The prefix of the API key.</value> public Dictionary<String, String> ApiKeyPrefix = new Dictionary<String, String>(); /// <summary> /// Get the API key with prefix. /// </summary> /// <param name="apiKeyIdentifier">API key identifier (authentication scheme).</param> /// <returns>API key with prefix.</returns> public string GetApiKeyWithPrefix (string apiKeyIdentifier) { var apiKeyValue = ""; ApiKey.TryGetValue (apiKeyIdentifier, out apiKeyValue); var apiKeyPrefix = ""; if (ApiKeyPrefix.TryGetValue (apiKeyIdentifier, out apiKeyPrefix)) return apiKeyPrefix + " " + apiKeyValue; else return apiKeyValue; } private string _tempFolderPath = Path.GetTempPath(); /// <summary> /// Gets or sets the temporary folder path to store the files downloaded from the server. /// </summary> /// <value>Folder path.</value> public String TempFolderPath { get { return _tempFolderPath; } set { if (String.IsNullOrEmpty(value)) { _tempFolderPath = value; return; } // create the directory if it does not exist if (!Directory.Exists(value)) Directory.CreateDirectory(value); // check if the path contains directory separator at the end if (value[value.Length - 1] == Path.DirectorySeparatorChar) _tempFolderPath = value; else _tempFolderPath = value + Path.DirectorySeparatorChar; } } private const string ISO8601_DATETIME_FORMAT = "o"; private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; /// <summary> /// Gets or sets the the date time format used when serializing in the ApiClient /// By default, it's set to ISO 8601 - "o", for others see: /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx /// No validation is done to ensure that the string you're providing is valid /// </summary> /// <value>The DateTimeFormat string</value> public String DateTimeFormat { get { return _dateTimeFormat; } set { if (string.IsNullOrEmpty(value)) { // Never allow a blank or null string, go back to the default _dateTimeFormat = ISO8601_DATETIME_FORMAT; return; } // Caution, no validation when you choose date time format other than ISO 8601 // Take a look at the above links _dateTimeFormat = value; } } /// <summary> /// Returns a string with essential information for debugging. /// </summary> public static String ToDebugReport() { String report = "C# SDK (CellStore) Debug Report:\n"; report += " OS: " + Environment.OSVersion + "\n"; report += " .NET Framework Version: " + Assembly .GetExecutingAssembly() .GetReferencedAssemblies() .Where(x => x.Name == "System.Core").First().Version.ToString() + "\n"; report += " Version of the API: vX.X.X\n"; report += " SDK Package Version: 5.5.1\n"; return report; } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Collections.Generic; using System.Linq; using System.Threading; using ASC.Files.Core; using ASC.Files.Core.Data; using ASC.Files.Core.Security; using ASC.Files.Thirdparty.Box; using ASC.Files.Thirdparty.Dropbox; using ASC.Files.Thirdparty.GoogleDrive; using ASC.Files.Thirdparty.OneDrive; using ASC.Files.Thirdparty.SharePoint; using ASC.Files.Thirdparty.Sharpbox; using ASC.Web.Files.Resources; using ASC.Web.Files.Utils; using ASC.Web.Studio.Core; namespace ASC.Files.Thirdparty.ProviderDao { internal class ProviderDaoBase { private static readonly List<IDaoSelector> Selectors = new List<IDaoSelector>(); protected static IDaoSelector Default { get; private set; } static ProviderDaoBase() { Default = new DbDaoSelector( x => new DaoFactory().GetFileDao(), x => new DaoFactory().GetFolderDao(), x => new DaoFactory().GetSecurityDao(), x => new DaoFactory().GetTagDao()); //Fill in selectors Selectors.Add(Default); //Legacy DB dao Selectors.Add(new SharpBoxDaoSelector()); Selectors.Add(new SharePointDaoSelector()); Selectors.Add(new GoogleDriveDaoSelector()); Selectors.Add(new BoxDaoSelector()); Selectors.Add(new DropboxDaoSelector()); Selectors.Add(new OneDriveDaoSelector()); } protected bool IsCrossDao(object id1, object id2) { if (id2 == null || id1 == null) return false; return !Equals(GetSelector(id1).GetIdCode(id1), GetSelector(id2).GetIdCode(id2)); } protected IDaoSelector GetSelector(object id) { return Selectors.FirstOrDefault(selector => selector.IsMatch(id)) ?? Default; } protected void SetSharedProperty(IEnumerable<FileEntry> entries) { using (var securityDao = TryGetSecurityDao()) { securityDao.GetPureShareRecords(entries) //.Where(x => x.Owner == SecurityContext.CurrentAccount.ID) .Select(x => x.EntryId).Distinct().ToList() .ForEach(id => { var firstEntry = entries.FirstOrDefault(y => y.ID.Equals(id)); if (firstEntry != null) firstEntry.Shared = true; }); } } protected IEnumerable<IDaoSelector> GetSelectors() { return Selectors; } //For working with function where no id is availible protected IFileDao TryGetFileDao() { foreach (var daoSelector in Selectors) { try { return daoSelector.GetFileDao(null); } catch (Exception) { } } throw new InvalidOperationException("No DAO can't be instanced without ID"); } //For working with function where no id is availible protected ISecurityDao TryGetSecurityDao() { foreach (var daoSelector in Selectors) { try { return daoSelector.GetSecurityDao(null); } catch (Exception) { } } throw new InvalidOperationException("No DAO can't be instanced without ID"); } //For working with function where no id is availible protected ITagDao TryGetTagDao() { foreach (var daoSelector in Selectors) { try { return daoSelector.GetTagDao(null); } catch (Exception) { } } throw new InvalidOperationException("No DAO can't be instanced without ID"); } //For working with function where no id is availible protected IFolderDao TryGetFolderDao() { foreach (var daoSelector in Selectors) { try { return daoSelector.GetFolderDao(null); } catch (Exception) { } } throw new InvalidOperationException("No DAO can't be instanced without ID"); } protected File PerformCrossDaoFileCopy(object fromFileId, object toFolderId, bool deleteSourceFile) { var fromSelector = GetSelector(fromFileId); var toSelector = GetSelector(toFolderId); //Get File from first dao var fromFileDao = fromSelector.GetFileDao(fromFileId); var toFileDao = toSelector.GetFileDao(toFolderId); var fromFile = fromFileDao.GetFile(fromSelector.ConvertId(fromFileId)); if (fromFile.ContentLength > SetupInfo.AvailableFileSize) { throw new Exception(string.Format(deleteSourceFile ? FilesCommonResource.ErrorMassage_FileSizeMove : FilesCommonResource.ErrorMassage_FileSizeCopy, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize))); } using (var securityDao = TryGetSecurityDao()) using (var tagDao = TryGetTagDao()) { var fromFileShareRecords = securityDao.GetPureShareRecords(fromFile).Where(x => x.EntryType == FileEntryType.File); var fromFileNewTags = tagDao.GetNewTags(Guid.Empty, fromFile).ToList(); var fromFileLockTag = tagDao.GetTags(fromFile.ID, FileEntryType.File, TagType.Locked).FirstOrDefault(); var fromFileFavoriteTag = tagDao.GetTags(fromFile.ID, FileEntryType.File, TagType.Favorite); var fromFileTemplateTag = tagDao.GetTags(fromFile.ID, FileEntryType.File, TagType.Template); var toFile = new File { Title = fromFile.Title, Encrypted = fromFile.Encrypted, FolderID = toSelector.ConvertId(toFolderId) }; fromFile.ID = fromSelector.ConvertId(fromFile.ID); var mustConvert = !string.IsNullOrEmpty(fromFile.ConvertedType); using (var fromFileStream = mustConvert ? FileConverter.Exec(fromFile) : fromFileDao.GetFileStream(fromFile)) { toFile.ContentLength = fromFileStream.CanSeek ? fromFileStream.Length : fromFile.ContentLength; toFile = toFileDao.SaveFile(toFile, fromFileStream); } if (fromFile.ThumbnailStatus == Thumbnail.Created) { using (var thumbnail = fromFileDao.GetThumbnail(fromFile)) { toFileDao.SaveThumbnail(toFile, thumbnail); } toFile.ThumbnailStatus = Thumbnail.Created; } if (deleteSourceFile) { if (fromFileShareRecords.Any()) fromFileShareRecords.ToList().ForEach(x => { x.EntryId = toFile.ID; securityDao.SetShare(x); }); var fromFileTags = fromFileNewTags; if (fromFileLockTag != null) fromFileTags.Add(fromFileLockTag); if (fromFileFavoriteTag != null) fromFileTags.AddRange(fromFileFavoriteTag); if (fromFileTemplateTag != null) fromFileTags.AddRange(fromFileTemplateTag); if (fromFileTags.Any()) { fromFileTags.ForEach(x => x.EntryId = toFile.ID); tagDao.SaveTags(fromFileTags); } //Delete source file if needed fromFileDao.DeleteFile(fromSelector.ConvertId(fromFileId)); } return toFile; } } protected Folder PerformCrossDaoFolderCopy(object fromFolderId, object toRootFolderId, bool deleteSourceFolder, CancellationToken? cancellationToken) { //Things get more complicated var fromSelector = GetSelector(fromFolderId); var toSelector = GetSelector(toRootFolderId); var fromFolderDao = fromSelector.GetFolderDao(fromFolderId); var fromFileDao = fromSelector.GetFileDao(fromFolderId); //Create new folder in 'to' folder var toFolderDao = toSelector.GetFolderDao(toRootFolderId); //Ohh var fromFolder = fromFolderDao.GetFolder(fromSelector.ConvertId(fromFolderId)); var toFolder = toFolderDao.GetFolder(fromFolder.Title, toSelector.ConvertId(toRootFolderId)); var toFolderId = toFolder != null ? toFolder.ID : toFolderDao.SaveFolder( new Folder { Title = fromFolder.Title, ParentFolderID = toSelector.ConvertId(toRootFolderId) }); var foldersToCopy = fromFolderDao.GetFolders(fromSelector.ConvertId(fromFolderId)); var fileIdsToCopy = fromFileDao.GetFiles(fromSelector.ConvertId(fromFolderId)); Exception copyException = null; //Copy files first foreach (var fileId in fileIdsToCopy) { if (cancellationToken.HasValue) cancellationToken.Value.ThrowIfCancellationRequested(); try { PerformCrossDaoFileCopy(fileId, toFolderId, deleteSourceFolder); } catch (Exception ex) { copyException = ex; } } foreach (var folder in foldersToCopy) { if (cancellationToken.HasValue) cancellationToken.Value.ThrowIfCancellationRequested(); try { PerformCrossDaoFolderCopy(folder.ID, toFolderId, deleteSourceFolder, cancellationToken); } catch (Exception ex) { copyException = ex; } } if (deleteSourceFolder) { using (var securityDao = TryGetSecurityDao()) { var fromFileShareRecords = securityDao.GetPureShareRecords(fromFolder) .Where(x => x.EntryType == FileEntryType.Folder); if (fromFileShareRecords.Any()) { fromFileShareRecords.ToList().ForEach(x => { x.EntryId = toFolderId; securityDao.SetShare(x); }); } } using (var tagDao = TryGetTagDao()) { var fromFileNewTags = tagDao.GetNewTags(Guid.Empty, fromFolder).ToList(); if (fromFileNewTags.Any()) { fromFileNewTags.ForEach(x => x.EntryId = toFolderId); tagDao.SaveTags(fromFileNewTags); } } if (copyException == null) fromFolderDao.DeleteFolder(fromSelector.ConvertId(fromFolderId)); } if (copyException != null) throw copyException; return toFolderDao.GetFolder(toSelector.ConvertId(toFolderId)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Rotate { internal class App { public static int s_weightCount = 1; private class BaseNode { private char _BASEPAD_0; public BaseNode() { _BASEPAD_0 = 'k'; } public virtual void VerifyValid() { if (_BASEPAD_0 != 'k') throw new Exception("m_BASEPAD_0"); } } private class Node : BaseNode { private ulong _PREPAD_0; private byte _PREPAD_1; private byte _PREPAD_2; private String _PREPAD_3; private ulong _PREPAD_4; private String _PREPAD_5; public Node m_leftChild; private ulong _MID1PAD_0; private ushort _MID1PAD_1; private String _MID1PAD_2; public int m_weight; private byte _MID2PAD_0; private uint _MID2PAD_1; private char _MID2PAD_2; private byte _MID2PAD_3; private String _MID2PAD_4; private ulong _MID2PAD_5; private ulong _MID2PAD_6; private String _MID2PAD_7; private byte _MID2PAD_8; private uint _MID2PAD_9; private uint _MID2PAD_10; private int _MID2PAD_11; public Node m_rightChild; private ulong _AFTERPAD_0; private ulong _AFTERPAD_1; private ulong _AFTERPAD_2; private uint _AFTERPAD_3; private int _AFTERPAD_4; private ushort _AFTERPAD_5; private byte _AFTERPAD_6; public Node() { m_weight = s_weightCount++; _PREPAD_0 = 84; _PREPAD_1 = 230; _PREPAD_2 = 70; _PREPAD_3 = "31530"; _PREPAD_4 = 97; _PREPAD_5 = "2235"; _MID1PAD_0 = 171; _MID1PAD_1 = 56; _MID1PAD_2 = "29777"; _MID2PAD_0 = 63; _MID2PAD_1 = 0; _MID2PAD_2 = 'P'; _MID2PAD_3 = 62; _MID2PAD_4 = "28537"; _MID2PAD_5 = 221; _MID2PAD_6 = 214; _MID2PAD_7 = "32307"; _MID2PAD_8 = 83; _MID2PAD_9 = 223; _MID2PAD_10 = 43; _MID2PAD_11 = 174; _AFTERPAD_0 = 220; _AFTERPAD_1 = 194; _AFTERPAD_2 = 125; _AFTERPAD_3 = 109; _AFTERPAD_4 = 126; _AFTERPAD_5 = 48; _AFTERPAD_6 = 214; } public override void VerifyValid() { base.VerifyValid(); if (_PREPAD_0 != 84) throw new Exception("m_PREPAD_0"); if (_PREPAD_1 != 230) throw new Exception("m_PREPAD_1"); if (_PREPAD_2 != 70) throw new Exception("m_PREPAD_2"); if (_PREPAD_3 != "31530") throw new Exception("m_PREPAD_3"); if (_PREPAD_4 != 97) throw new Exception("m_PREPAD_4"); if (_PREPAD_5 != "2235") throw new Exception("m_PREPAD_5"); if (_MID1PAD_0 != 171) throw new Exception("m_MID1PAD_0"); if (_MID1PAD_1 != 56) throw new Exception("m_MID1PAD_1"); if (_MID1PAD_2 != "29777") throw new Exception("m_MID1PAD_2"); if (_MID2PAD_0 != 63) throw new Exception("m_MID2PAD_0"); if (_MID2PAD_1 != 0) throw new Exception("m_MID2PAD_1"); if (_MID2PAD_2 != 'P') throw new Exception("m_MID2PAD_2"); if (_MID2PAD_3 != 62) throw new Exception("m_MID2PAD_3"); if (_MID2PAD_4 != "28537") throw new Exception("m_MID2PAD_4"); if (_MID2PAD_5 != 221) throw new Exception("m_MID2PAD_5"); if (_MID2PAD_6 != 214) throw new Exception("m_MID2PAD_6"); if (_MID2PAD_7 != "32307") throw new Exception("m_MID2PAD_7"); if (_MID2PAD_8 != 83) throw new Exception("m_MID2PAD_8"); if (_MID2PAD_9 != 223) throw new Exception("m_MID2PAD_9"); if (_MID2PAD_10 != 43) throw new Exception("m_MID2PAD_10"); if (_MID2PAD_11 != 174) throw new Exception("m_MID2PAD_11"); if (_AFTERPAD_0 != 220) throw new Exception("m_AFTERPAD_0"); if (_AFTERPAD_1 != 194) throw new Exception("m_AFTERPAD_1"); if (_AFTERPAD_2 != 125) throw new Exception("m_AFTERPAD_2"); if (_AFTERPAD_3 != 109) throw new Exception("m_AFTERPAD_3"); if (_AFTERPAD_4 != 126) throw new Exception("m_AFTERPAD_4"); if (_AFTERPAD_5 != 48) throw new Exception("m_AFTERPAD_5"); if (_AFTERPAD_6 != 214) throw new Exception("m_AFTERPAD_6"); } public virtual Node growTree(int maxHeight, String indent) { //Console.WriteLine(indent + m_weight.ToString()); if (maxHeight > 0) { m_leftChild = new Node(); m_leftChild.growTree(maxHeight - 1, indent + " "); m_rightChild = new Node(); m_rightChild.growTree(maxHeight - 1, indent + " "); } else m_leftChild = m_rightChild = null; return this; } public virtual void rotateTree(ref int leftWeight, ref int rightWeight) { //Console.WriteLine("rotateTree(" + m_weight.ToString() + ")"); VerifyValid(); // create node objects for children Node newLeftChild = null, newRightChild = null; if (m_leftChild != null) { newRightChild = new Node(); newRightChild.m_leftChild = m_leftChild.m_leftChild; newRightChild.m_rightChild = m_leftChild.m_rightChild; newRightChild.m_weight = m_leftChild.m_weight; } if (m_rightChild != null) { newLeftChild = new Node(); newLeftChild.m_leftChild = m_rightChild.m_leftChild; newLeftChild.m_rightChild = m_rightChild.m_rightChild; newLeftChild.m_weight = m_rightChild.m_weight; } // replace children m_leftChild = newLeftChild; m_rightChild = newRightChild; for (int I = 0; I < 32; I++) { int[] u = new int[1024]; } // verify all valid if (m_rightChild != null) { if (m_rightChild.m_leftChild != null && m_rightChild.m_rightChild != null) { m_rightChild.m_leftChild.VerifyValid(); m_rightChild.m_rightChild.VerifyValid(); m_rightChild.rotateTree( ref m_rightChild.m_leftChild.m_weight, ref m_rightChild.m_rightChild.m_weight); } else { int minus1 = -1; m_rightChild.rotateTree(ref minus1, ref minus1); } if (leftWeight != m_rightChild.m_weight) { Console.WriteLine("left weight do not match."); throw new Exception(); } } if (m_leftChild != null) { if (m_leftChild.m_leftChild != null && m_leftChild.m_rightChild != null) { m_leftChild.m_leftChild.VerifyValid(); m_leftChild.m_rightChild.VerifyValid(); m_leftChild.rotateTree( ref m_leftChild.m_leftChild.m_weight, ref m_leftChild.m_rightChild.m_weight); } else { int minus1 = -1; m_leftChild.rotateTree(ref minus1, ref minus1); } if (rightWeight != m_leftChild.m_weight) { Console.WriteLine("right weight do not match."); throw new Exception(); } } } } private static int Main() { try { Node root = new Node(); root.growTree(6, "").rotateTree( ref root.m_leftChild.m_weight, ref root.m_rightChild.m_weight); } catch (Exception) { Console.WriteLine("*** FAILED ***"); return 1; } Console.WriteLine("*** PASSED ***"); return 100; } } }
using System; using System.Data.Common; using System.Threading; using System.Threading.Tasks; using System.Transactions; using Baseline; using Marten.Exceptions; using Marten.Schema.Arguments; using Marten.Util; using Npgsql; using IsolationLevel = System.Data.IsolationLevel; namespace Marten.Services { public class ManagedConnection: IManagedConnection { private readonly IConnectionFactory _factory; private readonly CommandRunnerMode _mode; private readonly IsolationLevel _isolationLevel; private readonly int? _commandTimeout; private TransactionState _connection; private readonly bool _ownsConnection; private readonly IRetryPolicy _retryPolicy; private readonly NpgsqlConnection _externalConnection; public ManagedConnection(IConnectionFactory factory, IRetryPolicy retryPolicy) : this(factory, CommandRunnerMode.AutoCommit, retryPolicy) { } public ManagedConnection(SessionOptions options, CommandRunnerMode mode, IRetryPolicy retryPolicy) { _ownsConnection = options.OwnsConnection; _mode = options.OwnsTransactionLifecycle ? mode : CommandRunnerMode.External; _isolationLevel = options.IsolationLevel; _externalConnection = options.Connection ?? options.Transaction?.Connection; _commandTimeout = options.Timeout ?? _externalConnection?.CommandTimeout; _connection = new TransactionState(_mode, _isolationLevel, _commandTimeout, _externalConnection, _ownsConnection, options.Transaction); _retryPolicy = retryPolicy; } // 30 is NpgsqlCommand.DefaultTimeout - ok to burn it to the call site? public ManagedConnection(IConnectionFactory factory, CommandRunnerMode mode, IRetryPolicy retryPolicy, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, int? commandTimeout = null) { _factory = factory; _mode = mode; _isolationLevel = isolationLevel; _commandTimeout = commandTimeout; _ownsConnection = true; _retryPolicy = retryPolicy; } private void buildConnection() { if (_connection == null) { _connection = _factory is null ? new TransactionState(_mode, _isolationLevel, _commandTimeout, _externalConnection, _ownsConnection) : new TransactionState(_factory, _mode, _isolationLevel, _commandTimeout, _ownsConnection); _retryPolicy.Execute(() => _connection.Open()); } } private async Task buildConnectionAsync(CancellationToken token) { if (_connection == null) { _connection = _factory is null ? new TransactionState(_mode, _isolationLevel, _commandTimeout, _externalConnection, _ownsConnection) : new TransactionState(_factory, _mode, _isolationLevel, _commandTimeout, _ownsConnection); await _retryPolicy.ExecuteAsync(() => _connection.OpenAsync(token), token); } } public IMartenSessionLogger Logger { get; set; } = NulloMartenLogger.Flyweight; public int RequestCount { get; private set; } public void Commit() { if (_mode == CommandRunnerMode.External) return; buildConnection(); _retryPolicy.Execute(_connection.Commit); _connection.Dispose(); _connection = null; } public async Task CommitAsync(CancellationToken token) { if (_mode == CommandRunnerMode.External) return; await buildConnectionAsync(token); await _retryPolicy.ExecuteAsync(() => _connection.CommitAsync(token), token); await _connection.DisposeAsync(); _connection = null; } public void Rollback() { if (_connection == null) return; if (_mode == CommandRunnerMode.External) return; try { _retryPolicy.Execute(_connection.Rollback); } catch (RollbackException e) { if (e.InnerException != null) Logger.LogFailure(new NpgsqlCommand(), e.InnerException); } catch (Exception e) { Logger.LogFailure(new NpgsqlCommand(), e); } finally { _connection.Dispose(); _connection = null; } } public async Task RollbackAsync(CancellationToken token) { if (_connection == null) return; if (_mode == CommandRunnerMode.External) return; try { await _retryPolicy.ExecuteAsync(() => _connection.RollbackAsync(token), token); } catch (RollbackException e) { if (e.InnerException != null) Logger.LogFailure(new NpgsqlCommand(), e.InnerException); } catch (Exception e) { Logger.LogFailure(new NpgsqlCommand(), e); } finally { await _connection.DisposeAsync(); _connection = null; } } public void BeginSession() { if (_isolationLevel == IsolationLevel.Serializable) { BeginTransaction(); } } public void BeginTransaction() { if (InTransaction()) return; buildConnection(); _connection.BeginTransaction(); } public async Task BeginTransactionAsync(CancellationToken token) { if (InTransaction()) return; await buildConnectionAsync(token); _connection.BeginTransaction(); } public bool InTransaction() { return _connection?.Transaction != null; } public NpgsqlConnection Connection { get { buildConnection(); return _connection.Connection; } } [Obsolete("Replace with ExceptionTransforms from Baseline")] private void handleCommandException(NpgsqlCommand cmd, Exception e) { this.SafeDispose(); Logger.LogFailure(cmd, e); MartenExceptionTransformer.WrapAndThrow(cmd, e); } public int Execute(NpgsqlCommand cmd) { buildConnection(); RequestCount++; _connection.Apply(cmd); try { var returnValue = _retryPolicy.Execute(cmd.ExecuteNonQuery); Logger.LogSuccess(cmd); return returnValue; } catch (Exception e) { handleCommandException(cmd, e); throw; } } public DbDataReader ExecuteReader(NpgsqlCommand command) { buildConnection(); _connection.Apply(command); RequestCount++; try { var returnValue = _retryPolicy.Execute<DbDataReader>(command.ExecuteReader); Logger.LogSuccess(command); return returnValue; } catch (Exception e) { handleCommandException(command, e); throw; } } public async Task<DbDataReader> ExecuteReaderAsync(NpgsqlCommand command, CancellationToken token = default) { await buildConnectionAsync(token); _connection.Apply(command); Logger.OnBeforeExecute(command); RequestCount++; try { var reader = await _retryPolicy.ExecuteAsync(() => command.ExecuteReaderAsync(token), token); Logger.LogSuccess(command); return reader; } catch (Exception e) { handleCommandException(command, e); throw; } } public async Task<int> ExecuteAsync(NpgsqlCommand command, CancellationToken token = new CancellationToken()) { await buildConnectionAsync(token); RequestCount++; _connection.Apply(command); Logger.OnBeforeExecute(command); try { var returnValue = await _retryPolicy.ExecuteAsync(() => command.ExecuteNonQueryAsync(token), token); Logger.LogSuccess(command); return returnValue; } catch (Exception e) { handleCommandException(command, e); throw; } } public void Dispose() { _connection?.Dispose(); } public async ValueTask DisposeAsync() { if (_connection != null) { await _connection.DisposeAsync(); } } } }
/* * 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 Mono.Addins; using Nini.Config; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; namespace OpenSim.Region.CoreModules.World { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "CloudModule")] public class CloudModule : ICloudModule, INonSharedRegionModule { // private static readonly log4net.ILog m_log // = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private uint m_frame = 0; private int m_frameUpdateRate = 1000; private Random m_rndnums = new Random(Environment.TickCount); private Scene m_scene = null; private bool m_ready = false; private bool m_enabled = false; private float m_cloudDensity = 1.0F; private float[] cloudCover = new float[16 * 16]; public void Initialise(IConfigSource config) { IConfig cloudConfig = config.Configs["Cloud"]; if (cloudConfig != null) { m_enabled = cloudConfig.GetBoolean("enabled", false); m_cloudDensity = cloudConfig.GetFloat("density", 0.5F); m_frameUpdateRate = cloudConfig.GetInt("cloud_update_rate", 1000); } } public void AddRegion(Scene scene) { if (!m_enabled) return; m_scene = scene; scene.EventManager.OnNewClient += CloudsToClient; scene.RegisterModuleInterface<ICloudModule>(this); scene.EventManager.OnFrame += CloudUpdate; GenerateCloudCover(); m_ready = true; } public void RemoveRegion(Scene scene) { if (!m_enabled) return; m_ready = false; // Remove our hooks m_scene.EventManager.OnNewClient -= CloudsToClient; m_scene.EventManager.OnFrame -= CloudUpdate; m_scene.UnregisterModuleInterface<ICloudModule>(this); m_scene = null; } public void RegionLoaded(Scene scene) { } public void PostInitialise() { } public void Close() { } public string Name { get { return "CloudModule"; } } public Type ReplaceableInterface { get { return null; } } public float CloudCover(int x, int y, int z) { float cover = 0f; x /= 16; y /= 16; if (x < 0) x = 0; if (x > 15) x = 15; if (y < 0) y = 0; if (y > 15) y = 15; if (cloudCover != null) { cover = cloudCover[y * 16 + x]; } return cover; } private void UpdateCloudCover() { float[] newCover = new float[16 * 16]; int rowAbove = new int(); int rowBelow = new int(); int columnLeft = new int(); int columnRight = new int(); for (int x = 0; x < 16; x++) { if (x == 0) { columnRight = x + 1; columnLeft = 15; } else if (x == 15) { columnRight = 0; columnLeft = x - 1; } else { columnRight = x + 1; columnLeft = x - 1; } for (int y = 0; y< 16; y++) { if (y == 0) { rowAbove = y + 1; rowBelow = 15; } else if (y == 15) { rowAbove = 0; rowBelow = y - 1; } else { rowAbove = y + 1; rowBelow = y - 1; } float neighborAverage = (cloudCover[rowBelow * 16 + columnLeft] + cloudCover[y * 16 + columnLeft] + cloudCover[rowAbove * 16 + columnLeft] + cloudCover[rowBelow * 16 + x] + cloudCover[rowAbove * 16 + x] + cloudCover[rowBelow * 16 + columnRight] + cloudCover[y * 16 + columnRight] + cloudCover[rowAbove * 16 + columnRight] + cloudCover[y * 16 + x]) / 9; newCover[y * 16 + x] = ((neighborAverage / m_cloudDensity) + 0.175f) % 1.0f; newCover[y * 16 + x] *= m_cloudDensity; } } Array.Copy(newCover, cloudCover, 16 * 16); } private void CloudUpdate() { if (((m_frame++ % m_frameUpdateRate) != 0) || !m_ready || (m_cloudDensity == 0)) { return; } UpdateCloudCover(); } public void CloudsToClient(IClientAPI client) { if (m_ready) { client.SendCloudData(cloudCover); } } /// <summary> /// Calculate the cloud cover over the region. /// </summary> private void GenerateCloudCover() { for (int y = 0; y < 16; y++) { for (int x = 0; x < 16; x++) { cloudCover[y * 16 + x] = (float)(m_rndnums.NextDouble()); // 0 to 1 cloudCover[y * 16 + x] *= m_cloudDensity; } } } } }
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Change history * Oct 13 2008 Joe Feser joseph.feser@gmail.com * Converted ArrayLists and other .NET 1.1 collections to use Generics * Combined IExtensionElement and IExtensionElementFactory interfaces * */ #define USE_TRACING using System; using Google.GData.Client; using Google.GData.Extensions; namespace Google.GData.Contacts { ////////////////////////////////////////////////////////////////////// /// <summary> /// Entry API customization class for defining entries in an Event feed. /// </summary> ////////////////////////////////////////////////////////////////////// public class ContactEntry : BaseContactEntry { /// <summary> /// default contact term string for the contact relationship link /// </summary> public static string ContactTerm = "http://schemas.google.com/contact/2008#contact"; /// <summary>` /// Category used to label entries that contain contact extension data. /// </summary> public static AtomCategory CONTACT_CATEGORY = new AtomCategory(ContactEntry.ContactTerm, new AtomUri(BaseNameTable.gKind)); private ExtensionCollection<EMail> emails; private ExtensionCollection<IMAddress> ims; private ExtensionCollection<PhoneNumber> phonenumbers; private ExtensionCollection<StructuredPostalAddress> structuredAddress; private ExtensionCollection<Organization> organizations; private ExtensionCollection<GroupMembership> groups; private ExtensionCollection<CalendarLink> calendars; private ExtensionCollection<Event> events; private ExtensionCollection<ExternalId> externalIds; private ExtensionCollection<Hobby> hobbies; private ExtensionCollection<Jot> jots; private ExtensionCollection<Language> languages; private ExtensionCollection<Relation> relations; private ExtensionCollection<UserDefinedField> userDefinedFiels; private ExtensionCollection<Website> websites; /// <summary> /// Constructs a new ContactEntry instance with the appropriate category /// to indicate that it is an event. /// </summary> public ContactEntry() : base() { Tracing.TraceMsg("Created Contact Entry"); Categories.Add(CONTACT_CATEGORY); this.AddExtension(new GroupMembership()); this.AddExtension(new Where()); ContactsKindExtensions.AddExtension(this); // colletions this.AddExtension(new CalendarLink()); this.AddExtension(new Event()); this.AddExtension(new ExternalId()); this.AddExtension(new Hobby()); this.AddExtension(new Jot()); this.AddExtension(new Language()); this.AddExtension(new Relation()); this.AddExtension(new UserDefinedField()); this.AddExtension(new Website()); // singletons this.AddExtension(new BillingInformation()); this.AddExtension(new Birthday()); this.AddExtension(new DirectoryServer()); this.AddExtension(new Initials()); this.AddExtension(new MaidenName()); this.AddExtension(new Mileage()); this.AddExtension(new Nickname()); this.AddExtension(new Occupation()); this.AddExtension(new Priority()); this.AddExtension(new Sensitivity()); this.AddExtension(new ShortName()); this.AddExtension(new Subject()); } /// <summary> /// typed override of the Update method /// </summary> /// <returns></returns> public new ContactEntry Update() { return base.Update() as ContactEntry; } /// <summary> /// Location associated with the contact /// </summary> /// <returns></returns> public String Location { get { Where w = FindExtension(GDataParserNameTable.XmlWhereElement, BaseNameTable.gNamespace) as Where; return w != null ? w.ValueString : null; } set { Where w = null; if (value != null) { w = new Where(null, null, value); } ReplaceExtension(GDataParserNameTable.XmlWhereElement, BaseNameTable.gNamespace, w); } } /// <summary> /// convienience accessor to find the primary Email /// there is no setter, to change this use the Primary Flag on /// an individual object /// </summary> public EMail PrimaryEmail { get { foreach (EMail e in this.Emails) { if (e.Primary == true) { return e; } } return null; } } /// <summary> /// convienience accessor to find the primary Phonenumber /// there is no setter, to change this use the Primary Flag on /// an individual object /// </summary> public PhoneNumber PrimaryPhonenumber { get { foreach (PhoneNumber p in this.Phonenumbers) { if (p.Primary == true) { return p; } } return null; } } /// <summary> /// convienience accessor to find the primary PostalAddress /// there is no setter, to change this use the Primary Flag on /// an individual object /// </summary> public StructuredPostalAddress PrimaryPostalAddress { get { foreach (StructuredPostalAddress p in this.PostalAddresses) { if (p.Primary == true) { return p; } } return null; } } /// <summary> /// convienience accessor to find the primary IMAddress /// there is no setter, to change this use the Primary Flag on /// an individual object /// </summary> public IMAddress PrimaryIMAddress { get { foreach (IMAddress im in this.IMs) { if (im.Primary == true) { return im; } } return null; } } /// <summary> /// returns the groupmembership info on this object /// </summary> /// <returns></returns> public ExtensionCollection<GroupMembership> GroupMembership { get { if (this.groups == null) { this.groups = new ExtensionCollection<GroupMembership>(this); } return this.groups; } } /// <summary> /// getter/setter for the email extension element /// </summary> public ExtensionCollection<EMail> Emails { get { if (this.emails == null) { this.emails = new ExtensionCollection<EMail>(this); } return this.emails; } } /// <summary> /// getter/setter for the IM extension element /// </summary> public ExtensionCollection<IMAddress> IMs { get { if (this.ims == null) { this.ims = new ExtensionCollection<IMAddress>(this); } return this.ims; } } /// <summary> /// returns the phonenumber collection /// </summary> public ExtensionCollection<PhoneNumber> Phonenumbers { get { if (this.phonenumbers == null) { this.phonenumbers = new ExtensionCollection<PhoneNumber>(this); } return this.phonenumbers; } } /// <summary> /// Postal address split into components. It allows to store the address in locale independent format. /// The fields can be interpreted and used to generate formatted, locale dependent address /// </summary> public ExtensionCollection<StructuredPostalAddress> PostalAddresses { get { if (this.structuredAddress == null) { this.structuredAddress = new ExtensionCollection<StructuredPostalAddress>(this); } return this.structuredAddress; } } /// <summary> /// returns the phonenumber collection /// </summary> public ExtensionCollection<Organization> Organizations { get { if (this.organizations == null) { this.organizations = new ExtensionCollection<Organization>(this); } return this.organizations; } } /// <summary> /// getter for the CalendarLink collections /// </summary> public ExtensionCollection<CalendarLink> Calendars { get { if (this.calendars == null) { this.calendars = new ExtensionCollection<CalendarLink>(this); } return this.calendars; } } /// <summary> /// getter for the Events collections /// </summary> public ExtensionCollection<Event> Events { get { if (this.events == null) { this.events = new ExtensionCollection<Event>(this); } return this.events; } } /// <summary> /// getter for the externalids collections /// </summary> public ExtensionCollection<ExternalId> ExternalIds { get { if (this.externalIds == null) { this.externalIds = new ExtensionCollection<ExternalId>(this); } return this.externalIds; } } /// <summary> /// getter for the Hobby collections /// </summary> public ExtensionCollection<Hobby> Hobbies { get { if (this.hobbies == null) { this.hobbies = new ExtensionCollection<Hobby>(this); } return this.hobbies; } } /// <summary> /// getter for the Jot collections /// </summary> public ExtensionCollection<Jot> Jots { get { if (this.jots == null) { this.jots = new ExtensionCollection<Jot>(this); } return this.jots; } } /// <summary> /// getter for the languages collections /// </summary> public ExtensionCollection<Language> Languages { get { if (this.languages == null) { this.languages = new ExtensionCollection<Language>(this); } return this.languages; } } /// <summary> /// getter for the Relation collections /// </summary> public ExtensionCollection<Relation> Relations { get { if (this.relations == null) { this.relations = new ExtensionCollection<Relation>(this); } return this.relations; } } /// <summary> /// getter for the UserDefinedField collections /// </summary> public ExtensionCollection<UserDefinedField> UserDefinedFields { get { if (this.userDefinedFiels == null) { this.userDefinedFiels = new ExtensionCollection<UserDefinedField>(this); } return this.userDefinedFiels; } } /// <summary> /// getter for the website collections /// </summary> public ExtensionCollection<Website> Websites { get { if (this.websites == null) { this.websites = new ExtensionCollection<Website>(this); } return this.websites; } } /// <summary> /// retrieves the Uri of the Photo Link. To set this, you need to create an AtomLink object /// and add/replace it in the atomlinks colleciton. /// </summary> /// <returns></returns> public Uri PhotoUri { get { AtomLink link = this.Links.FindService(GDataParserNameTable.ServicePhoto, null); return link == null ? null : new Uri(link.HRef.ToString()); } } /// <summary> /// if a photo is present on this contact, it will have an etag associated with it, /// that needs to be used when you want to delete or update that picture. /// </summary> /// <returns>the etag value as a string</returns> public string PhotoEtag { get { AtomLink link = this.PhotoLink; if (link != null) { foreach (XmlExtension x in link.ExtensionElements) { if (x.XmlNameSpace == GDataParserNameTable.gNamespace && x.XmlName == GDataParserNameTable.XmlEtagAttribute) { return x.Node.Value; } } } return null; } set { AtomLink link = this.PhotoLink; if (link != null) { foreach (XmlExtension x in link.ExtensionElements) { if (x.XmlNameSpace == GDataParserNameTable.gNamespace && x.XmlName == GDataParserNameTable.XmlEtagAttribute) { x.Node.Value = value; } } } } } private AtomLink PhotoLink { get { AtomLink link = this.Links.FindService(GDataParserNameTable.ServicePhoto, null); return link; } } /// <summary> /// returns the Name object /// </summary> public Name Name { get { return FindExtension(GDataParserNameTable.NameElement, BaseNameTable.gNamespace) as Name; } set { ReplaceExtension(GDataParserNameTable.NameElement, BaseNameTable.gNamespace, value); } } /// <summary> /// Contacts billing information. /// </summary> /// <returns></returns> public string BillingInformation { get { return GetStringValue<BillingInformation>(ContactsNameTable.BillingInformationElement, ContactsNameTable.NSContacts); } set { SetStringValue<BillingInformation>(value, ContactsNameTable.BillingInformationElement, ContactsNameTable.NSContacts); } } /// <summary> /// Contact's birthday. /// </summary> /// <returns></returns> public string Birthday { get { Birthday b = FindExtension(ContactsNameTable.BirthdayElement, ContactsNameTable.NSContacts) as Birthday; if (b != null) { return b.When; } return null; } set { Birthday b = null; if (value != null) { b = new Birthday(value); } ReplaceExtension(ContactsNameTable.BirthdayElement, ContactsNameTable.NSContacts, b); } } /// <summary> /// Directory server associated with the contact. /// </summary> /// <returns></returns> public string DirectoryServer { get { return GetStringValue<DirectoryServer>(ContactsNameTable.DirectoryServerElement, ContactsNameTable.NSContacts); } set { SetStringValue<DirectoryServer>(value, ContactsNameTable.DirectoryServerElement, ContactsNameTable.NSContacts); } } /// <summary> /// Contacts initals /// </summary> /// <returns></returns> public string Initials { get { return GetStringValue<Initials>(ContactsNameTable.InitialsElement, ContactsNameTable.NSContacts); } set { SetStringValue<Initials>(value, ContactsNameTable.InitialsElement, ContactsNameTable.NSContacts); } } /// <summary> /// Maiden name associated with the contact. /// </summary> /// <returns></returns> public string MaidenName { get { return GetStringValue<MaidenName>(ContactsNameTable.MaidenNameElement, ContactsNameTable.NSContacts); } set { SetStringValue<MaidenName>(value, ContactsNameTable.MaidenNameElement, ContactsNameTable.NSContacts); } } /// <summary> /// Mileage associated with the contact. /// </summary> /// <returns></returns> public string Mileage { get { return GetStringValue<Mileage>(ContactsNameTable.MileageElement, ContactsNameTable.NSContacts); } set { SetStringValue<Mileage>(value, ContactsNameTable.MileageElement, ContactsNameTable.NSContacts); } } /// <summary> /// Nickname associated with the contact. /// </summary> /// <returns></returns> public string Nickname { get { return GetStringValue<Nickname>(ContactsNameTable.NicknameElement, ContactsNameTable.NSContacts); } set { SetStringValue<Nickname>(value, ContactsNameTable.NicknameElement, ContactsNameTable.NSContacts); } } /// <summary> /// Occupation associated with the contact. /// </summary> /// <returns></returns> public string Occupation { get { return GetStringValue<Occupation>(ContactsNameTable.OccupationElement, ContactsNameTable.NSContacts); } set { SetStringValue<Occupation>(value, ContactsNameTable.OccupationElement, ContactsNameTable.NSContacts); } } /// <summary> /// Priority ascribed to the contact. /// </summary> /// <returns></returns> public string Priority { get { Priority b = FindExtension(ContactsNameTable.PriorityElement, ContactsNameTable.NSContacts) as Priority; if (b != null) { return b.Relation; } return null; } set { Priority b = null; if (value != null) { b = new Priority(value); } ReplaceExtension(ContactsNameTable.PriorityElement, ContactsNameTable.NSContacts, b); } } /// <summary> /// Sensitivity ascribed to the contact. /// </summary> /// <returns></returns> public string Sensitivity { get { Sensitivity b = FindExtension(ContactsNameTable.SensitivityElement, ContactsNameTable.NSContacts) as Sensitivity; if (b != null) { return b.Relation; } return null; } set { Sensitivity b = null; if (value != null) { b = new Sensitivity(value); } ReplaceExtension(ContactsNameTable.SensitivityElement, ContactsNameTable.NSContacts, b); } } /// <summary> /// Contact's short name. /// </summary> /// <returns></returns> public string ShortName { get { return GetStringValue<ShortName>(ContactsNameTable.ShortNameElement, ContactsNameTable.NSContacts); } set { SetStringValue<ShortName>(value, ContactsNameTable.ShortNameElement, ContactsNameTable.NSContacts); } } /// <summary> /// Subject associated with the contact. /// </summary> /// <returns></returns> public string Subject { get { return GetStringValue<Subject>(ContactsNameTable.SubjectElement, ContactsNameTable.NSContacts); } set { SetStringValue<Subject>(value, ContactsNameTable.SubjectElement, ContactsNameTable.NSContacts); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.Xml { using System; using System.Text; using System.Diagnostics; using Microsoft.Xml.Schema; internal class XmlName : IXmlSchemaInfo { private string _prefix; private string _localName; private string _ns; private string _name; private int _hashCode; internal XmlDocument ownerDoc; internal XmlName next; public static XmlName Create(string prefix, string localName, string ns, int hashCode, XmlDocument ownerDoc, XmlName next, IXmlSchemaInfo schemaInfo) { if (schemaInfo == null) { return new XmlName(prefix, localName, ns, hashCode, ownerDoc, next); } else { return new XmlNameEx(prefix, localName, ns, hashCode, ownerDoc, next, schemaInfo); } } internal XmlName(string prefix, string localName, string ns, int hashCode, XmlDocument ownerDoc, XmlName next) { _prefix = prefix; _localName = localName; _ns = ns; _name = null; _hashCode = hashCode; this.ownerDoc = ownerDoc; this.next = next; } public string LocalName { get { return _localName; } } public string NamespaceURI { get { return _ns; } } public string Prefix { get { return _prefix; } } public int HashCode { get { return _hashCode; } } public XmlDocument OwnerDocument { get { return ownerDoc; } } public string Name { get { if (_name == null) { Debug.Assert(_prefix != null); if (_prefix.Length > 0) { if (_localName.Length > 0) { string n = string.Concat(_prefix, ":", _localName); lock (ownerDoc.NameTable) { if (_name == null) { _name = ownerDoc.NameTable.Add(n); } } } else { _name = _prefix; } } else { _name = _localName; } Debug.Assert(Ref.Equal(_name, ownerDoc.NameTable.Get(_name))); } return _name; } } public virtual XmlSchemaValidity Validity { get { return XmlSchemaValidity.NotKnown; } } public virtual bool IsDefault { get { return false; } } public virtual bool IsNil { get { return false; } } public virtual XmlSchemaSimpleType MemberType { get { return null; } } public virtual XmlSchemaType SchemaType { get { return null; } } public virtual XmlSchemaElement SchemaElement { get { return null; } } public virtual XmlSchemaAttribute SchemaAttribute { get { return null; } } public virtual bool Equals(IXmlSchemaInfo schemaInfo) { return schemaInfo == null; } public static int GetHashCode(string name) { int hashCode = 0; if (name != null) { for (int i = name.Length - 1; i >= 0; i--) { char ch = name[i]; if (ch == ':') break; hashCode += (hashCode << 7) ^ ch; } hashCode -= hashCode >> 17; hashCode -= hashCode >> 11; hashCode -= hashCode >> 5; } return hashCode; } } internal sealed class XmlNameEx : XmlName { private byte _flags; private XmlSchemaSimpleType _memberType; private XmlSchemaType _schemaType; private object _decl; // flags // 0,1 : Validity // 2 : IsDefault // 3 : IsNil private const byte ValidityMask = 0x03; private const byte IsDefaultBit = 0x04; private const byte IsNilBit = 0x08; internal XmlNameEx(string prefix, string localName, string ns, int hashCode, XmlDocument ownerDoc, XmlName next, IXmlSchemaInfo schemaInfo) : base(prefix, localName, ns, hashCode, ownerDoc, next) { SetValidity(schemaInfo.Validity); SetIsDefault(schemaInfo.IsDefault); SetIsNil(schemaInfo.IsNil); _memberType = schemaInfo.MemberType; _schemaType = schemaInfo.SchemaType; _decl = schemaInfo.SchemaElement != null ? (object)schemaInfo.SchemaElement : (object)schemaInfo.SchemaAttribute; } public override XmlSchemaValidity Validity { get { return ownerDoc.CanReportValidity ? (XmlSchemaValidity)(_flags & ValidityMask) : XmlSchemaValidity.NotKnown; } } public override bool IsDefault { get { return (_flags & IsDefaultBit) != 0; } } public override bool IsNil { get { return (_flags & IsNilBit) != 0; } } public override XmlSchemaSimpleType MemberType { get { return _memberType; } } public override XmlSchemaType SchemaType { get { return _schemaType; } } public override XmlSchemaElement SchemaElement { get { return _decl as XmlSchemaElement; } } public override XmlSchemaAttribute SchemaAttribute { get { return _decl as XmlSchemaAttribute; } } public void SetValidity(XmlSchemaValidity value) { _flags = (byte)((_flags & ~ValidityMask) | (byte)(value)); } public void SetIsDefault(bool value) { if (value) _flags = (byte)(_flags | IsDefaultBit); else _flags = (byte)(_flags & ~IsDefaultBit); } public void SetIsNil(bool value) { if (value) _flags = (byte)(_flags | IsNilBit); else _flags = (byte)(_flags & ~IsNilBit); } public override bool Equals(IXmlSchemaInfo schemaInfo) { if (schemaInfo != null && schemaInfo.Validity == (XmlSchemaValidity)(_flags & ValidityMask) && schemaInfo.IsDefault == ((_flags & IsDefaultBit) != 0) && schemaInfo.IsNil == ((_flags & IsNilBit) != 0) && (object)schemaInfo.MemberType == (object)_memberType && (object)schemaInfo.SchemaType == (object)_schemaType && (object)schemaInfo.SchemaElement == (object)(_decl as XmlSchemaElement) && (object)schemaInfo.SchemaAttribute == (object)(_decl as XmlSchemaAttribute)) { return true; } return false; } } }
#if TEST using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using Fadd; using Xunit; namespace HttpServer.Test { public class HttpClientContextTest : IDisposable { private readonly Socket _client; private readonly ManualResetEvent _disconnectEvent = new ManualResetEvent(false); private readonly ManualResetEvent _event = new ManualResetEvent(false); private readonly HttpContextFactory _factory; private readonly Socket _remoteSocket; private IHttpClientContext _context; private int _counter; private bool _disconnected; private IHttpRequest _request; private Socket _listenSocket; public HttpClientContextTest() { _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _listenSocket.Bind(new IPEndPoint(IPAddress.Any, 14862)); _listenSocket.Listen(0); IAsyncResult res = _listenSocket.BeginAccept(null, null); _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); _client.Connect("localhost", 14862); _remoteSocket = _listenSocket.EndAccept(res); _disconnectEvent.Reset(); _event.Reset(); _counter = 0; var requestParserFactory = new RequestParserFactory(); _factory = new HttpContextFactory(NullLogWriter.Instance, 8192, requestParserFactory); _factory.RequestReceived += OnRequest; _context = _factory.CreateContext(_client); _context.Disconnected += OnDisconnect; //_context = new HttpClientContext(false, new IPEndPoint(IPAddress.Loopback, 21111), OnRequest, OnDisconnect, _client.GetStream(), ConsoleLogWriter.Instance); _request = null; _disconnected = false; } /// <summary> /// Releases unmanaged resources and performs other cleanup operations before the /// <see cref="HttpClientContextTest"/> is reclaimed by garbage collection. /// </summary> ~HttpClientContextTest() { Dispose(); } private void OnDisconnect(object source, DisconnectedEventArgs args) { _disconnected = true; _disconnectEvent.Set(); } private void OnRequest(object source, RequestEventArgs args) { IHttpClientContext client = (IHttpClientContext)source; IHttpRequest request = args.Request; ++_counter; _request = (IHttpRequest) request.Clone(); _event.Set(); } [Fact] public void TestConstructor1() { Assert.Throws(typeof (CheckException), delegate { new HttpClientContext(true, new IPEndPoint(IPAddress.Loopback, 21111), null, null, 0); }); } [Fact] public void TestConstructor2() { Assert.Throws(typeof (CheckException), delegate { new HttpClientContext(true, new IPEndPoint(IPAddress.Loopback, 21111), new MemoryStream(), null, 0); }); } [Fact] public void TestConstructor3() { var stream = new MemoryStream(); stream.Close(); Assert.Throws(typeof (CheckException), delegate { new HttpClientContext(true, new IPEndPoint(IPAddress.Loopback, 21111), stream, null, 0); }); } [Fact] public void TestConstructor4() { Assert.Throws(typeof (CheckException), delegate { new HttpClientContext(true, new IPEndPoint(IPAddress.Loopback, 21111), null, null, 0); }); } [Fact] public void TestPartial1() { WriteStream("GET / HTTP/1.0\r\nhost:"); WriteStream("myhost"); WriteStream("\r\n"); WriteStream("accept: all"); WriteStream("\r\n"); WriteStream("\r\n"); _event.WaitOne(50000, true); Assert.NotNull(_request); Assert.Equal("GET", _request.Method); Assert.Equal(HttpHelper.HTTP10, _request.HttpVersion); Assert.Equal("all", _request.AcceptTypes[0]); Assert.Equal("myhost", _request.Uri.Host); } [Fact] public void TestPartials() { WriteStream("GET / "); WriteStream("HTTP/1.0\r\n"); WriteStream("host:localhost\r\n"); WriteStream("\r\n"); _event.WaitOne(500, true); Assert.NotNull(_request); Assert.Equal("GET", _request.Method); Assert.Equal("HTTP/1.0", _request.HttpVersion); Assert.Equal("/", _request.Uri.AbsolutePath); Assert.Equal("localhost", _request.Uri.Host); } [Fact] public void TestPartialWithBody() { WriteStream("GET / "); WriteStream("HTTP/1.0\r\n"); WriteStream("host:localhost\r\n"); WriteStream("cOnTenT-LENGTH:11\r\n"); WriteStream("Content-Type: text/plain"); WriteStream("\r\n"); WriteStream("\r\n"); WriteStream("Hello"); WriteStream(" World"); _event.WaitOne(5000, false); Assert.NotNull(_request); Assert.Equal("GET", _request.Method); Assert.Equal("HTTP/1.0", _request.HttpVersion); Assert.Equal("/", _request.Uri.AbsolutePath); Assert.Equal("localhost", _request.Uri.Host); var reader = new StreamReader(_request.Body); Assert.Equal("Hello World", reader.ReadToEnd()); } [Fact] public void TestTwoPartialsWithBodies() { _factory.UseTraceLogs = true; WriteStream("GET / "); WriteStream("HTTP/1.0\r\n"); WriteStream("host:localhost\r\n"); WriteStream("cOnTenT-LENGTH:11\r\n"); WriteStream("Content-Type: text/plain"); WriteStream("\r\n"); WriteStream("\r\n"); WriteStream("Hello"); WriteStream(" World"); _event.WaitOne(5000, false); Assert.NotNull(_request); Assert.Equal("GET", _request.Method); Assert.Equal("HTTP/1.0", _request.HttpVersion); Assert.Equal("/", _request.Uri.AbsolutePath); Assert.Equal("localhost", _request.Uri.Host); var reader = new StreamReader(_request.Body); Assert.Equal("Hello World", reader.ReadToEnd()); _event.Reset(); WriteStream("GET / "); WriteStream("HTTP/1.0\r\n"); WriteStream("host:localhost\r\n"); WriteStream("cOnTenT-LENGTH:7\r\n"); WriteStream("Content-Type: text/plain"); WriteStream("\r\n"); WriteStream("\r\n"); WriteStream("Goodbye"); _event.WaitOne(5000, false); Assert.NotNull(_request); Assert.Equal("GET", _request.Method); Assert.Equal("HTTP/1.0", _request.HttpVersion); Assert.Equal("/", _request.Uri.AbsolutePath); Assert.Equal("localhost", _request.Uri.Host); reader = new StreamReader(_request.Body); _request.Body.Flush(); _request.Body.Seek(0, SeekOrigin.Begin); Assert.Equal("Goodbye", reader.ReadToEnd()); } [Fact] public void TestTwoCompleteWithBodies() { _factory.UseTraceLogs = true; WriteStream(@"GET / HTTP/1.0 host:localhost cOnTenT-LENGTH:11 Content-Type: text/plain Hello World"); _event.WaitOne(5000, false); Assert.NotNull(_request); Assert.Equal("GET", _request.Method); Assert.Equal("HTTP/1.0", _request.HttpVersion); Assert.Equal("/", _request.Uri.AbsolutePath); Assert.Equal("localhost", _request.Uri.Host); var reader = new StreamReader(_request.Body); Assert.Equal("Hello World", reader.ReadToEnd()); _event.Reset(); WriteStream(@"GET / HTTP/1.0 host:localhost cOnTenT-LENGTH:7 Content-Type: text/plain Goodbye"); _event.WaitOne(5000, false); Assert.NotNull(_request); Assert.Equal("GET", _request.Method); Assert.Equal("HTTP/1.0", _request.HttpVersion); Assert.Equal("/", _request.Uri.AbsolutePath); Assert.Equal("localhost", _request.Uri.Host); reader = new StreamReader(_request.Body); _request.Body.Flush(); _request.Body.Seek(0, SeekOrigin.Begin); Assert.Equal("Goodbye", reader.ReadToEnd()); } [Fact] public void TestRequest() { WriteStream("GET / HTTP/1.0\r\nhost: localhost\r\n\r\n"); _event.WaitOne(5000, true); Assert.NotNull(_request); Assert.Equal("GET", _request.Method); Assert.Equal("/", _request.Uri.AbsolutePath); Assert.Equal(HttpHelper.HTTP10, _request.HttpVersion); Assert.Equal("localhost", _request.Uri.Host); } [Fact] public void TestTwoRequests() { WriteStream(@"GET / HTTP/1.0 host: localhost GET / HTTP/1.1 host:shit.se accept:all "); _event.WaitOne(500, true); _event.WaitOne(50, true); Assert.Equal(2, _counter); Assert.Equal("GET", _request.Method); Assert.Equal(HttpHelper.HTTP11, _request.HttpVersion); Assert.Equal("all", _request.AcceptTypes[0]); Assert.Equal("shit.se", _request.Uri.Host); } [Fact] public void TestValidInvalidValid() { WriteStream(@"GET / HTTP/1.0 host: localhost connection: keep-alive someshot jsj GET / HTTP/1.1 host:shit.se accept:all connection:close "); _disconnectEvent.WaitOne(500000, true); Assert.True(_disconnected); } private void WriteStream(string s) { _event.Reset(); byte[] bytes = Encoding.UTF8.GetBytes(s); _remoteSocket.Send(bytes); Thread.Sleep(50); } #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <filterpriority>2</filterpriority> public void Dispose() { try { _client.Close(); _listenSocket.Close(); _remoteSocket.Close(); } catch (SocketException) { } } #endregion } } #endif
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Linq; using System.Xml; using System.Xml.Linq; using Xunit; namespace XDocumentTests.SDMSample { public class SDM_Container { /// <summary> /// Tests the Add methods on Container. /// </summary> [Fact] public void ContainerAdd() { XElement element = new XElement("foo"); // Adding null does nothing. element.Add(null); Assert.Empty(element.Nodes()); // Add node, attrbute, string, some other value, and an IEnumerable. XComment comment = new XComment("this is a comment"); XComment comment2 = new XComment("this is a comment 2"); XComment comment3 = new XComment("this is a comment 3"); XAttribute attribute = new XAttribute("att", "att-value"); string str = "this is a string"; int other = 7; element.Add(comment); element.Add(attribute); element.Add(str); element.Add(other); element.Add(new XComment[] { comment2, comment3 }); Assert.Equal( new XNode[] { comment, new XText(str + other), comment2, comment3 }, element.Nodes(), XNode.EqualityComparer); Assert.Equal(new[] { attribute.Name }, element.Attributes().Select(x => x.Name)); Assert.Equal(new[] { attribute.Value }, element.Attributes().Select(x => x.Value)); element.RemoveAll(); Assert.Empty(element.Nodes()); // Now test params overload. element.Add(comment, attribute, str, other); Assert.Equal(new XNode[] { comment, new XText(str + other) }, element.Nodes(), XNode.EqualityComparer); Assert.Equal(new[] { attribute.Name }, element.Attributes().Select(x => x.Name)); Assert.Equal(new[] { attribute.Value }, element.Attributes().Select(x => x.Value)); // Not allowed to add a document as a child. XDocument document = new XDocument(); Assert.Throws<ArgumentException>(() => element.Add(document)); } /// <summary> /// Tests the AddAttributes method on Container. /// </summary> [Fact] public void ContainerAddAttributes() { // Not allowed to add attributes in the general case. // The only general case of a container is a document. XDocument document = new XDocument(); Assert.Throws<ArgumentException>(() => document.Add(new XAttribute("foo", "bar"))); // Can add to elements, but no duplicates allowed. XElement e = new XElement("element"); XAttribute a1 = new XAttribute("foo", "bar1"); XAttribute a2 = new XAttribute("foo", "bar2"); e.Add(a1); Assert.Throws<InvalidOperationException>(() => e.Add(a2)); // Can add the same attribute to different parent elements; // it gets copied. XElement e2 = new XElement("element2"); e2.Add(a1); Assert.Same(a1, e.Attribute("foo")); Assert.NotSame(a1, e2.Attribute("foo")); } /// <summary> /// Tests the AddFirst methods on Container. /// </summary> [Fact] public void ContainerAddFirst() { XElement element = new XElement("foo"); // Adding null does nothing. element.AddFirst(null); Assert.Empty(element.Nodes()); // Add a sentinal value. XText text = new XText("abcd"); element.AddFirst(text); // Add node and string. XComment comment = new XComment("this is a comment"); string str = "this is a string"; element.AddFirst(comment); element.AddFirst(str); Assert.Equal(new XNode[] { new XText(str), comment, text }, element.Nodes(), XNode.EqualityComparer); element.RemoveAll(); Assert.Empty(element.Nodes()); // Now test params overload. element.AddFirst(text); element.AddFirst(comment, str); Assert.Equal(new XNode[] { comment, new XText(str), text }, element.Nodes(), XNode.EqualityComparer); // Can't use to add attributes. XAttribute a = new XAttribute("foo", "bar"); Assert.Throws<ArgumentException>(() => element.AddFirst(a)); } /// <summary> /// Tests the Content/AllContent methods on Container /// </summary> [Fact] public void ContainerContent() { XElement element = new XElement( "foo", new XAttribute("att1", "a1"), new XComment("my comment"), new XElement("bar", new XText("abcd"), new XElement("inner")), 100); // Content should include just the elements, no attributes // or contents of nested elements. IEnumerator allContent = element.Nodes().GetEnumerator(); allContent.MoveNext(); object obj1 = allContent.Current; allContent.MoveNext(); object obj2 = allContent.Current; allContent.MoveNext(); object obj3 = allContent.Current; bool b = allContent.MoveNext(); Assert.Equal((XNode)obj1, new XComment("my comment"), XNode.EqualityComparer); Assert.Equal( (XNode)obj2, new XElement("bar", new XText("abcd"), new XElement("inner")), XNode.EqualityComparer); Assert.Equal((XNode)obj3, new XText("100"), XNode.EqualityComparer); Assert.False(b); } /// <summary> /// Validate enumeration of container descendents. /// </summary> [Fact] public void ContainerDescendents() { XComment comment = new XComment("comment"); XElement level3 = new XElement("Level3"); XElement level2 = new XElement("Level2", level3); XElement level1 = new XElement("Level1", level2, comment); XElement level0 = new XElement("Level1", level1); Assert.Equal(new XElement[] { level2, level3 }, level1.Descendants(), XNode.EqualityComparer); Assert.Equal( new XNode[] { level1, level2, level3, comment }, level0.DescendantNodes(), XNode.EqualityComparer); Assert.Empty(level0.Descendants(null)); Assert.Equal(new XElement[] { level1 }, level0.Descendants("Level1"), XNode.EqualityComparer); } /// <summary> /// Validate enumeration of container elements. /// </summary> [Fact] public void ContainerElements() { XElement level1_1 = new XElement("level1"); XElement level1_2 = new XElement("level1", new XElement("level1"), new XElement("level2")); XElement element = new XElement("level0", new XComment("my comment"), level1_1, level1_2); XElement empty = new XElement("empty"); // Can't find anything in an empty element Assert.Null(empty.Element("foo")); // Can't find element with no name or bogus name. Assert.Null(element.Element(null)); Assert.Null(element.Element("foo")); // Check element by name Assert.Equal(level1_1, element.Element("level1")); // Check element sequence -- should not include nested elements. Assert.Equal(new XElement[] { level1_1, level1_2 }, element.Elements(), XNode.EqualityComparer); // Check element sequence by name. Assert.Empty(element.Elements(null)); Assert.Equal(new XElement[] { level1_1, level1_2 }, element.Elements("level1"), XNode.EqualityComparer); } /// <summary> /// Validate ReplaceNodes on container. /// </summary> [Fact] public void ContainerReplaceNodes() { XElement element = new XElement( "foo", new XAttribute("att", "bar"), "abc", new XElement("nested", new XText("abcd"))); // Replace with a node, attribute, string, some other value, and an IEnumerable. // ReplaceNodes does not remove attributes. XComment comment = new XComment("this is a comment"); XComment comment2 = new XComment("this is a comment 2"); XComment comment3 = new XComment("this is a comment 3"); XAttribute attribute = new XAttribute("att2", "att-value"); string str = "this is a string"; TimeSpan other1 = new TimeSpan(1, 2, 3); element.ReplaceNodes(comment, attribute, str, other1, new XComment[] { comment2, comment3 }); Assert.Equal( new XNode[] { comment, new XText(str + XmlConvert.ToString(other1)), comment2, comment3 }, element.Nodes(), XNode.EqualityComparer); Assert.Equal(2, element.Attributes().Count()); Assert.Equal(element.Attribute("att").Name, "att"); Assert.Equal(element.Attribute("att").Value, "bar"); Assert.Equal(element.Attribute("att2").Name, "att2"); Assert.Equal(element.Attribute("att2").Value, "att-value"); } /// <summary> /// Validate the behavior of annotations on Container. /// </summary> [Fact] public void ContainerAnnotations() { XElement element1 = new XElement("e1"); XElement element2 = new XElement("e2"); // Check argument null exception on add. Assert.Throws<ArgumentNullException>(() => element1.AddAnnotation(null)); // Before adding anything, should not be able to get any annotations. Assert.Null(element1.Annotation(typeof(object))); element1.RemoveAnnotations(typeof(object)); Assert.Null(element1.Annotation(typeof(object))); // First annotation: 2 cases, object[] and other. object obj1 = "hello"; element1.AddAnnotation(obj1); Assert.Null(element1.Annotation(typeof(byte))); Assert.Same(obj1, element1.Annotation(typeof(string))); element1.RemoveAnnotations(typeof(string)); Assert.Null(element1.Annotation(typeof(string))); object[] obj2 = new object[] { 10, 20, 30 }; element2.AddAnnotation(obj2); Assert.Same(obj2, element2.Annotation(typeof(object[]))); Assert.Equal(element2.Annotation(typeof(object[])), new object[] { 10, 20, 30 }); element2.RemoveAnnotations(typeof(object[])); Assert.Null(element2.Annotation(typeof(object[]))); // Single annotation; add a second one. Check that duplicates are allowed. object obj3 = 10; element1.AddAnnotation(obj3); Assert.Same(obj3, element1.Annotation(typeof(int))); element1.AddAnnotation(1000); element1.RemoveAnnotations(typeof(int[])); Assert.Null(element1.Annotation(typeof(object[]))); object obj4 = "world"; element1.AddAnnotation(obj4); Assert.Same(obj3, element1.Annotation(typeof(int))); Assert.Same(obj4, element1.Annotation(typeof(string))); // Multiple annotations already. Add one on the end. object obj5 = 20L; element1.AddAnnotation(obj5); Assert.Same(obj3, element1.Annotation(typeof(int))); Assert.Same(obj4, element1.Annotation(typeof(string))); Assert.Same(obj5, element1.Annotation(typeof(long))); // Remove one from the middle and then add, which should use the // freed slot. element1.RemoveAnnotations(typeof(string)); Assert.Null(element1.Annotation(typeof(string))); object obj6 = 30m; element1.AddAnnotation(obj6); Assert.Same(obj3, element1.Annotation(typeof(int))); Assert.Same(obj5, element1.Annotation(typeof(long))); Assert.Same(obj6, element1.Annotation(typeof(decimal))); // Ensure that duplicates are allowed. element1.AddAnnotation(40m); Assert.Null(element1.Annotation(typeof(sbyte))); // A couple of additional remove cases. element2.AddAnnotation(obj2); element2.AddAnnotation(obj3); element2.AddAnnotation(obj5); element2.AddAnnotation(obj6); element2.RemoveAnnotations(typeof(float)); Assert.Null(element2.Annotation(typeof(float))); } /// <summary> /// Tests removing text content from a container. /// </summary> [Fact] public void ContainerRemoveTextual() { XElement e1 = XElement.Parse("<a>abcd</a>"); XElement e2 = new XElement(e1); XElement eb = new XElement("b"); e2.Add(eb); eb.Remove(); Assert.True(XNode.EqualityComparer.Equals(e1, e2)); // Removing non-text between some text should NOT collapse the text. e1.Add(eb); e1.Add("efgh"); Assert.Equal(new XNode[] { new XText("abcd"), eb, new XText("efgh") }, e1.Nodes(), XNode.EqualityComparer); eb.Remove(); Assert.Equal(new XNode[] { new XText("abcd"), new XText("efgh") }, e1.Nodes(), XNode.EqualityComparer); } } }
/* **************************************************************************** * * Copyright (c) Microsoft Corporation. * * This source code is subject to terms and conditions of the Apache License, Version 2.0. A * copy of the license can be found in the License.html file at the root of this distribution. If * you cannot locate the Apache License, Version 2.0, please send an email to * dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound * by the terms of the Apache License, Version 2.0. * * You must not remove this notice, or any other, from this software. * * * ***************************************************************************/ using System; using System.Collections; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using IronPython.Runtime.Operations; using IronPython.Runtime.Types; using IronPython.Runtime.Exceptions; namespace IronPython.Runtime { [PythonType("slice")] public sealed class Slice : ICodeFormattable, IComparable, ISlice { private readonly object _start, _stop, _step; public Slice(object stop) : this(null, stop, null) { } public Slice(object start, object stop) : this(start, stop, null) { } public Slice(object start, object stop, object step) { _start = start; _stop = stop; _step = step; } #region Python Public API Surface public object start { get { return _start; } } public object stop { get { return _stop; } } public object step { get { return _step; } } public int __cmp__(Slice obj) { return PythonOps.CompareArrays(new object[] { _start, _stop, _step }, 3, new object[] { obj._start, obj._stop, obj._step }, 3); } public void indices(int len, out int ostart, out int ostop, out int ostep) { PythonOps.FixSlice(len, _start, _stop, _step, out ostart, out ostop, out ostep); } public void indices(object len, out int ostart, out int ostop, out int ostep) { PythonOps.FixSlice(Converter.ConvertToIndex(len), _start, _stop, _step, out ostart, out ostop, out ostep); } public PythonTuple __reduce__() { return PythonTuple.MakeTuple( DynamicHelpers.GetPythonTypeFromType(typeof(Slice)), PythonTuple.MakeTuple( _start, _stop, _step ) ); } #endregion #region IComparable Members int IComparable.CompareTo(object obj) { Slice other = obj as Slice; if (other == null) throw new ValueErrorException("expected slice"); return __cmp__(other); } #endregion [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")] public int __hash__() { throw PythonOps.TypeErrorForUnhashableType("slice"); } #region ISlice Members object ISlice.Start { get { return start; } } object ISlice.Stop { get { return stop; } } object ISlice.Step { get { return step; } } #endregion #region ICodeFormattable Members public string/*!*/ __repr__(CodeContext/*!*/ context) { return string.Format("slice({0}, {1}, {2})", PythonOps.Repr(context, _start), PythonOps.Repr(context, _stop), PythonOps.Repr(context, _step)); } #endregion #region Internal Implementation details internal static void FixSliceArguments(int size, ref int start, ref int stop) { start = start < 0 ? 0 : start > size ? size : start; stop = stop < 0 ? 0 : stop > size ? size : stop; } internal static void FixSliceArguments(long size, ref long start, ref long stop) { start = start < 0 ? 0 : start > size ? size : start; stop = stop < 0 ? 0 : stop > size ? size : stop; } /// <summary> /// Gets the indices for the deprecated __getslice__, __setslice__, __delslice__ functions /// /// This form is deprecated in favor of using __getitem__ w/ a slice object as an index. This /// form also has subtly different mechanisms for fixing the slice index before calling the function. /// /// If an index is negative and __len__ is not defined on the object than an AttributeError /// is raised. /// </summary> internal void DeprecatedFixed(object self, out int newStart, out int newStop) { bool calcedLength = false; // only call __len__ once, even if we need it twice int length = 0; if (_start != null) { newStart = Converter.ConvertToIndex(_start); if (newStart < 0) { calcedLength = true; length = PythonOps.Length(self); newStart += length; } } else { newStart = 0; } if (_stop != null) { newStop = Converter.ConvertToIndex(_stop); if (newStop < 0) { if (!calcedLength) length = PythonOps.Length(self); newStop += length; } } else { newStop = Int32.MaxValue; } } internal delegate void SliceAssign(int index, object value); internal void DoSliceAssign(SliceAssign assign, int size, object value) { int ostart, ostop, ostep; indices(size, out ostart, out ostop, out ostep); DoSliceAssign(assign, ostart, ostop, ostep, value); } private static void DoSliceAssign(SliceAssign assign, int start, int stop, int step, object value) { stop = step > 0 ? Math.Max(stop, start) : Math.Min(stop, start); int n = Math.Max(0, (step > 0 ? (stop - start + step - 1) : (stop - start + step + 1)) / step); // fast paths, if we know the size then we can // do this quickly. if (value is IList) { ListSliceAssign(assign, start, n, step, value as IList); } else { OtherSliceAssign(assign, start, stop, step, value); } } private static void ListSliceAssign(SliceAssign assign, int start, int n, int step, IList lst) { if (lst.Count < n) throw PythonOps.ValueError("too few items in the enumerator. need {0} have {1}", n, lst.Count); else if (lst.Count != n) throw PythonOps.ValueError("too many items in the enumerator need {0} have {1}", n, lst.Count); for (int i = 0, index = start; i < n; i++, index += step) { assign(index, lst[i]); } } private static void OtherSliceAssign(SliceAssign assign, int start, int stop, int step, object value) { // get enumerable data into a list, and then // do the slice. IEnumerator enumerator = PythonOps.GetEnumerator(value); List sliceData = new List(); while (enumerator.MoveNext()) sliceData.AddNoLock(enumerator.Current); DoSliceAssign(assign, start, stop, step, sliceData); } #endregion } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. /*============================================================================= ** ** ** Purpose: A circular-array implementation of a generic queue. ** ** =============================================================================*/ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Collections.Generic { // A simple Queue of generic objects. Internally it is implemented as a // circular buffer, so Enqueue can be O(n). Dequeue is O(1). [DebuggerTypeProxy(typeof(QueueDebugView<>))] [DebuggerDisplay("Count = {Count}")] public class Queue<T> : IEnumerable<T>, System.Collections.ICollection, IReadOnlyCollection<T> { private T[] _array; private int _head; // First valid element in the queue private int _tail; // Last valid element in the queue private int _size; // Number of elements. private int _version; private Object _syncRoot; private const int MinimumGrow = 4; private const int GrowFactor = 200; // double each time private const int DefaultCapacity = 4; // Creates a queue with room for capacity objects. The default initial // capacity and grow factor are used. /// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue"]/*' /> public Queue() { _array = Array.Empty<T>(); } // Creates a queue with room for capacity objects. The default grow factor // is used. // /// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue1"]/*' /> public Queue(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException("capacity", SR.ArgumentOutOfRange_NeedNonNegNumRequired); _array = new T[capacity]; } // Fills a Queue with the elements of an ICollection. Uses the enumerator // to get each of the elements. // /// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Queue3"]/*' /> public Queue(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException("collection"); _array = new T[DefaultCapacity]; using (IEnumerator<T> en = collection.GetEnumerator()) { while (en.MoveNext()) { Enqueue(en.Current); } } } /// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Count"]/*' /> public int Count { get { return _size; } } /// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.IsSynchronized"]/*' /> bool System.Collections.ICollection.IsSynchronized { get { return false; } } Object System.Collections.ICollection.SyncRoot { get { if (_syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } // Removes all Objects from the queue. /// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Clear"]/*' /> public void Clear() { if (_head < _tail) Array.Clear(_array, _head, _size); else { Array.Clear(_array, _head, _array.Length - _head); Array.Clear(_array, 0, _tail); } _head = 0; _tail = 0; _size = 0; _version++; } // CopyTo copies a collection into an Array, starting at a particular // index into the array. // /// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.CopyTo"]/*' /> public void CopyTo(T[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException("array"); } if (arrayIndex < 0 || arrayIndex > array.Length) { throw new ArgumentOutOfRangeException("arrayIndex", SR.ArgumentOutOfRange_Index); } int arrayLen = array.Length; if (arrayLen - arrayIndex < _size) { throw new ArgumentException(SR.Argument_InvalidOffLen); } int numToCopy = (arrayLen - arrayIndex < _size) ? (arrayLen - arrayIndex) : _size; if (numToCopy == 0) return; int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy; Array.Copy(_array, _head, array, arrayIndex, firstPart); numToCopy -= firstPart; if (numToCopy > 0) { Array.Copy(_array, 0, array, arrayIndex + _array.Length - _head, numToCopy); } } void System.Collections.ICollection.CopyTo(Array array, int index) { if (array == null) { throw new ArgumentNullException("array"); } if (array.Rank != 1) { throw new ArgumentException(SR.Arg_RankMultiDimNotSupported); } if (array.GetLowerBound(0) != 0) { throw new ArgumentException(SR.Arg_NonZeroLowerBound); } int arrayLen = array.Length; if (index < 0 || index > arrayLen) { throw new ArgumentOutOfRangeException("index", SR.ArgumentOutOfRange_Index); } if (arrayLen - index < _size) { throw new ArgumentException(SR.Argument_InvalidOffLen); } int numToCopy = (arrayLen - index < _size) ? arrayLen - index : _size; if (numToCopy == 0) return; try { int firstPart = (_array.Length - _head < numToCopy) ? _array.Length - _head : numToCopy; Array.Copy(_array, _head, array, index, firstPart); numToCopy -= firstPart; if (numToCopy > 0) { Array.Copy(_array, 0, array, index + _array.Length - _head, numToCopy); } } catch (ArrayTypeMismatchException) { throw new ArgumentException(SR.Argument_InvalidArrayType); } } // Adds item to the tail of the queue. // /// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Enqueue"]/*' /> public void Enqueue(T item) { if (_size == _array.Length) { int newcapacity = (int)((long)_array.Length * (long)GrowFactor / 100); if (newcapacity < _array.Length + MinimumGrow) { newcapacity = _array.Length + MinimumGrow; } SetCapacity(newcapacity); } _array[_tail] = item; _tail = (_tail + 1) % _array.Length; _size++; _version++; } // GetEnumerator returns an IEnumerator over this Queue. This // Enumerator will support removing. // /// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.GetEnumerator"]/*' /> public Enumerator GetEnumerator() { return new Enumerator(this); } /// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.IEnumerable.GetEnumerator"]/*' /> /// <internalonly/> IEnumerator<T> IEnumerable<T>.GetEnumerator() { return new Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } // Removes the object at the head of the queue and returns it. If the queue // is empty, this method simply returns null. /// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Dequeue"]/*' /> public T Dequeue() { if (_size == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue); T removed = _array[_head]; _array[_head] = default(T); _head = (_head + 1) % _array.Length; _size--; _version++; return removed; } // Returns the object at the head of the queue. The object remains in the // queue. If the queue is empty, this method throws an // InvalidOperationException. /// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Peek"]/*' /> public T Peek() { if (_size == 0) throw new InvalidOperationException(SR.InvalidOperation_EmptyQueue); return _array[_head]; } // Returns true if the queue contains at least one object equal to item. // Equality is determined using item.Equals(). // // Exceptions: ArgumentNullException if item == null. /// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.Contains"]/*' /> public bool Contains(T item) { int index = _head; int count = _size; EqualityComparer<T> c = EqualityComparer<T>.Default; while (count-- > 0) { if (((Object)item) == null) { if (((Object)_array[index]) == null) return true; } else if (_array[index] != null && c.Equals(_array[index], item)) { return true; } index = (index + 1) % _array.Length; } return false; } internal T GetElement(int i) { return _array[(_head + i) % _array.Length]; } // Iterates over the objects in the queue, returning an array of the // objects in the Queue, or an empty array if the queue is empty. // The order of elements in the array is first in to last in, the same // order produced by successive calls to Dequeue. /// <include file='doc\Queue.uex' path='docs/doc[@for="Queue.ToArray"]/*' /> public T[] ToArray() { T[] arr = new T[_size]; if (_size == 0) return arr; // consider replacing with Array.Empty<T>() to be consistent with non-generic Queue if (_head < _tail) { Array.Copy(_array, _head, arr, 0, _size); } else { Array.Copy(_array, _head, arr, 0, _array.Length - _head); Array.Copy(_array, 0, arr, _array.Length - _head, _tail); } return arr; } // PRIVATE Grows or shrinks the buffer to hold capacity objects. Capacity // must be >= _size. private void SetCapacity(int capacity) { T[] newarray = new T[capacity]; if (_size > 0) { if (_head < _tail) { Array.Copy(_array, _head, newarray, 0, _size); } else { Array.Copy(_array, _head, newarray, 0, _array.Length - _head); Array.Copy(_array, 0, newarray, _array.Length - _head, _tail); } } _array = newarray; _head = 0; _tail = (_size == capacity) ? 0 : _size; _version++; } public void TrimExcess() { int threshold = (int)(((double)_array.Length) * 0.9); if (_size < threshold) { SetCapacity(_size); } } // Implements an enumerator for a Queue. The enumerator uses the // internal version number of the list to ensure that no modifications are // made to the list while an enumeration is in progress. /// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator"]/*' /> [SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes", Justification = "not an expected scenario")] public struct Enumerator : IEnumerator<T>, System.Collections.IEnumerator { private Queue<T> _q; private int _index; // -1 = not started, -2 = ended/disposed private int _version; private T _currentElement; internal Enumerator(Queue<T> q) { _q = q; _version = _q._version; _index = -1; _currentElement = default(T); } /// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator.Dispose"]/*' /> public void Dispose() { _index = -2; _currentElement = default(T); } /// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator.MoveNext"]/*' /> public bool MoveNext() { if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); if (_index == -2) return false; _index++; if (_index == _q._size) { _index = -2; _currentElement = default(T); return false; } _currentElement = _q.GetElement(_index); return true; } /// <include file='doc\Queue.uex' path='docs/doc[@for="QueueEnumerator.Current"]/*' /> public T Current { get { if (_index < 0) { if (_index == -1) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); else throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } return _currentElement; } } Object System.Collections.IEnumerator.Current { get { if (_index < 0) { if (_index == -1) throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted); else throw new InvalidOperationException(SR.InvalidOperation_EnumEnded); } return _currentElement; } } void System.Collections.IEnumerator.Reset() { if (_version != _q._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion); _index = -1; _currentElement = default(T); } } } }
using AjaxControlToolkit.Design; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Web; using System.Web.Script.Serialization; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Drawing; using System.Collections.ObjectModel; using System.Text.RegularExpressions; namespace AjaxControlToolkit { /// <summary> /// AjaxFileUpload is an ASP.NET AJAX Control that allows you to asynchronously upload files to the server. /// </summary> [Designer(typeof(AjaxFileUploadDesigner))] [RequiredScript(typeof(CommonToolkitScripts))] [ClientCssResource(Constants.AjaxFileUploadName)] [ClientScriptResource("Sys.Extended.UI.AjaxFileUpload.Control", Constants.AjaxFileUploadName)] [ToolboxBitmap(typeof(ToolboxIcons.Accessor), Constants.AjaxFileUploadName + Constants.IconPostfix)] public class AjaxFileUpload : ScriptControlBase { internal const string ContextKey = "{DA8BEDC8-B952-4d5d-8CC2-59FE922E2923}"; const string DefaultTempSubDir = "_AjaxFileUpload"; // Location of uploaded temporary file path string _uploadedFilePath = null; public AjaxFileUpload() : base(true, HtmlTextWriterTag.Div) { } bool IsDesignMode { get { return (HttpContext.Current == null); } } // Any value/Id that can be used when storing file. public string ContextKeys { get; set; } /// <summary> /// The ID of a control that is shown on the file upload. /// The throbber image is displayed for browsers that do not support the HTML5 File API or server-side polling. /// </summary> [Description("ID of Throbber")] [Category("Behavior")] [DefaultValue("")] public string ThrobberID { get { return (string)(ViewState["ThrobberID"] ?? string.Empty); } set { ViewState["ThrobberID"] = value; } } ///<summary> /// This will be true when a postback will be performed from the control. /// This can be used to avoid execution of unnecessary code during a partial postback. /// The default is false. /// </summary> /// <remarks>Deprecated. Always false.</remarks> [Browsable(false)] [DefaultValue(false)] [Obsolete("Always false.")] [EditorBrowsable(EditorBrowsableState.Never)] public bool IsInFileUploadPostBack { get; set; } /// <summary> /// A maximum number of files in an upload queue. /// The default is 10. /// </summary> [ExtenderControlProperty] [DefaultValue(10)] [ClientPropertyName("maximumNumberOfFiles")] public int MaximumNumberOfFiles { get; set; } /// <summary> /// A comma-separated list of allowed file extensions. /// The default is an empty string. /// </summary> [ExtenderControlProperty] [DefaultValue("")] [ClientPropertyName("allowedFileTypes")] public string AllowedFileTypes { get; set; } /// <summary> /// The size of a chunk used by HTML5 to upload large files in bytes. /// The default is 4096. /// </summary> [ExtenderControlProperty] [DefaultValue(4096)] [ClientPropertyName("chunkSize")] public int ChunkSize { get { return int.Parse((string)ViewState["ChunkSize"] ?? "4096"); } set { ViewState["ChunkSize"] = value.ToString(); } } /// <summary> /// The maximum size of a file to be uploaded in Kbytes. /// A non-positive value means the size is unlimited. /// The default is 0. /// </summary> [ExtenderControlProperty] [DefaultValue(0)] [ClientPropertyName("maxFileSize")] public int MaxFileSize { get { return int.Parse((string)ViewState["MaxFileSize"] ?? "0"); } set { ViewState["MaxFileSize"] = value.ToString(); } } /// <summary> /// Whether or not to hide file upload list container after the uploading finished /// </summary> [ExtenderControlProperty] [DefaultValue(false)] [ClientPropertyName("clearFileListAfterUpload")] public bool ClearFileListAfterUpload { get { return bool.Parse((string)ViewState["ClearFileListAfterUpload"] ?? "false"); } set { ViewState["ClearFileListAfterUpload"] = value.ToString(); } } /// <summary> /// Whether or not to use absolute path for AjaxFileUploadHandler /// </summary> /// <remarks> /// Deprecated. Use UploadHandlerPath instead. /// </remarks> [Obsolete("Use UploadHandlerPath instead.")] [ExtenderControlProperty] [DefaultValue(true)] [ClientPropertyName("useAbsoluteHandlerPath")] [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public bool UseAbsoluteHandlerPath { get { return bool.Parse((string)ViewState["UseAbsoluteHandlerPath"] ?? "true"); } set { ViewState["UseAbsoluteHandlerPath"] = value.ToString(); } } /// <summary> /// Upload handler path /// </summary> [DefaultValue("")] public string UploadHandlerPath { get { return (string)ViewState["UploadHandlerPath"] ?? ""; } set { ViewState["UploadHandlerPath"] = value; } } ///<summary> /// Specifies how AjaxFileUpload uploads files. /// If set to Auto or Client and the client browser supports HTML 5, AjaxFileUpload uploads files using AJAX requests. /// If set to Server or the browser does not support HTML 5, AjaxFileUpload uploads files by posting the HTML form. /// The default is Auto. /// </summary> [ExtenderControlProperty] [DefaultValue(AjaxFileUploadMode.Auto)] [ClientPropertyName("mode")] public AjaxFileUploadMode Mode { get { return (AjaxFileUploadMode)Enum.Parse(typeof(AjaxFileUploadMode), (string)ViewState["Mode"] ?? "Auto"); } set { ViewState["Mode"] = value.ToString(); } } /// <summary> /// Whether or not automatically start upload files after drag/drop or select in file dialog. The default is false /// </summary> [ExtenderControlProperty] [DefaultValue(false)] [ClientPropertyName("autoStartUpload")] public bool AutoStartUpload { get { return bool.Parse((string)ViewState["AutoStartUpload"] ?? "false"); } set { ViewState["AutoStartUpload"] = value.ToString(); } } /// <summary> /// An event raised when the file upload starts. /// </summary> [Bindable(true)] [Category("Server Events")] public event EventHandler<AjaxFileUploadStartEventArgs> UploadStart; /// <summary> /// An event raised when the file upload is complete. /// </summary> [Bindable(true)] [Category("Server Events")] public event EventHandler<AjaxFileUploadEventArgs> UploadComplete; /// <summary> /// An event handler that will be raised when the UploadComplete event is raised /// in all files in an upload queue, or when a user presses the Cancel button to stop uploading. /// </summary> [Bindable(true)] [Category("Server Events")] public event EventHandler<AjaxFileUploadCompleteAllEventArgs> UploadCompleteAll; /// <summary> /// The name of a JavaScript function executed on the client side before any files are uploaded. /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("uploadStart")] public string OnClientUploadStart { get { return (string)(ViewState["OnClientUploadStart"] ?? string.Empty); } set { ViewState["OnClientUploadStart"] = value; } } /// <summary> /// The name of a JavaScript function executed on the client side after a file is uploaded successfully. /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("uploadComplete")] public string OnClientUploadComplete { get { return (string)(ViewState["OnClientUploadComplete"] ?? string.Empty); } set { ViewState["OnClientUploadComplete"] = value; } } /// <summary> /// The client script that executes when all of files in queue uploaded, /// or when user hits Cancel button to stop uploading /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("uploadCompleteAll")] public string OnClientUploadCompleteAll { get { return (string)(ViewState["OnClientUploadCompleteAll"] ?? string.Empty); } set { ViewState["OnClientUploadCompleteAll"] = value; } } /// <summary> /// The name of a JavaScript function executed on the client side if the file upload failed. /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("uploadError")] public string OnClientUploadError { get { return (string)(ViewState["OnClientUploadError"] ?? string.Empty); } set { ViewState["OnClientUploadError"] = value; } } /// <summary> /// Whether or not AjaxFileUpload supports server polling. /// </summary> public bool ServerPollingSupport { get { return true; } } protected override void OnInit(EventArgs e) { base.OnInit(e); if(IsDesignMode || !AreFileUploadParamsPresent()) return; var processor = new UploadRequestProcessor { Control = this, UploadStart = UploadStart, UploadComplete = UploadComplete, UploadCompleteAll = UploadCompleteAll, SetUploadedFilePath = SetUploadedFilePath }; processor.ProcessRequest(); } bool AreFileUploadParamsPresent() { return !string.IsNullOrEmpty(Page.Request.QueryString["contextkey"]) && Page.Request.QueryString["contextkey"] == ContextKey && Page.Request.QueryString["controlID"] == ClientID; } void SetUploadedFilePath(string path) { _uploadedFilePath = path; } protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Register an empty OnSubmit statement so the ASP.NET WebForm_OnSubmit method will be automatically // created and our behavior will be able to disable input file controls prior to submission ScriptManager.RegisterOnSubmitStatement(this, typeof(AjaxFileUpload), "AjaxFileUploadOnSubmit", "null;"); } /// <summary> /// Saves the uploaded file with the specified file name /// </summary> /// <param name="fileName" type="String">Name of the file to save</param> public void SaveAs(string fileName) { var dir = Path.GetDirectoryName(_uploadedFilePath); // Override existing file if any if(File.Exists(fileName)) File.Delete(fileName); File.Copy(_uploadedFilePath, fileName); File.Delete(_uploadedFilePath); // Delete temporary data Directory.Delete(dir); } public static void CleanAllTemporaryData() { var dirInfo = new DirectoryInfo(GetRootTempFolder()); foreach(var dir in dirInfo.GetDirectories()) { dir.Delete(true); } } public static string GetTempFolder(string fileId) { return Path.Combine(GetRootTempFolder(), fileId); } public static string GetRootTempFolder() { var userPath = ToolkitConfig.TempFolder; if(!String.IsNullOrWhiteSpace(userPath)) return GetPhysicalPath(userPath); return Path.Combine(Path.GetTempPath(), DefaultTempSubDir); } static string GetPhysicalPath(string path) { if(path.StartsWith("~")) return HttpContext.Current.Server.MapPath(path); return path; } internal void CreateChilds() { Controls.Clear(); CreateChildControls(); } protected override void CreateChildControls() { GenerateHtmlInputControls(); } // Return the client id of parent div that contains all other html controls. protected string GenerateHtmlInputControls() { HtmlGenericControl parent = new HtmlGenericControl("div"); parent.Attributes.Add("class", "ajax__fileupload"); Controls.Add(parent); var inputFileStyle = "opacity:0; -moz-opacity: 0.0; filter: alpha(opacity=0);"; HtmlInputFile inputFile = new HtmlInputFile(); if(!Enabled) inputFile.Disabled = true; inputFile.Attributes.Add("id", ClientID + "_Html5InputFile"); inputFile.Attributes.Add("multiple", "multiple"); inputFile.Attributes.Add("style", inputFileStyle); HideElement(inputFile); HtmlInputFile inputFileElement = new HtmlInputFile(); if(!Enabled) inputFileElement.Disabled = true; inputFileElement.Attributes.Add("id", ClientID + "_InputFileElement"); inputFileElement.Attributes.Add("name", "act-file-data"); inputFileElement.Attributes.Add("style", inputFileStyle); HideElement(inputFileElement); HtmlGenericControl dropZone = new HtmlGenericControl("div"); dropZone.Attributes.Add("class", "ajax__fileupload_dropzone"); dropZone.Attributes.Add("id", ClientID + "_Html5DropZone"); // IE 10 requested dropzone to be have actual size dropZone.Attributes.Add("style", "width:100%; height:60px;"); HideElement(dropZone); parent.Controls.Add(dropZone); HtmlGenericControl fileStatusContainer = new HtmlGenericControl("div"); fileStatusContainer.Attributes.Add("id", ClientID + "_FileStatusContainer"); fileStatusContainer.Style[HtmlTextWriterStyle.Position] = "absolute"; fileStatusContainer.Style["right"] = "0"; fileStatusContainer.Style["top"] = "2px"; fileStatusContainer.Style["height"] = "20px"; fileStatusContainer.Style["line-height"] = "20px"; HideElement(fileStatusContainer); var selectFileContainer = GenerateHtmlSelectFileContainer(inputFileElement, inputFile); parent.Controls.Add(selectFileContainer); parent.Controls.Add(GenerateHtmlTopFileStatus(fileStatusContainer)); var queueContainer = new HtmlGenericControl("div"); queueContainer.Attributes.Add("id", ClientID + "_QueueContainer"); queueContainer.Attributes.Add("class", "ajax__fileupload_queueContainer"); queueContainer.Style[HtmlTextWriterStyle.MarginTop] = "28px"; parent.Controls.Add(queueContainer); HideElement(queueContainer); var progressBar = new HtmlGenericControl("div"); progressBar.Attributes.Add("id", ClientID + "_ProgressBar"); progressBar.Attributes.Add("class", "ajax__fileupload_progressBar"); progressBar.Attributes.Add("style", "width: 100%; display: none; visibility: hidden; overflow:visible;white-space:nowrap; height:20px;"); var uploadButton = GenerateHtmlFooterContainer(progressBar); parent.Controls.Add(uploadButton); return parent.ClientID; } HtmlGenericControl GenerateHtmlFooterContainer(Control progressBar) { var footerContainer = new HtmlGenericControl("div"); footerContainer.Attributes.Add("class", "ajax__fileupload_footer"); footerContainer.Attributes.Add("id", ClientID + "_Footer"); footerContainer.Attributes["align"] = "right"; var uploadOrCancelButton = new HtmlGenericControl("div"); uploadOrCancelButton.Attributes.Add("id", ClientID + "_UploadOrCancelButton"); uploadOrCancelButton.Attributes.Add("class", "ajax__fileupload_uploadbutton"); var progressBarContainer = new HtmlGenericControl("div"); progressBarContainer.Attributes.Add("id", ClientID + "_ProgressBarContainer"); progressBarContainer.Attributes["align"] = "left"; progressBarContainer.Style["float"] = "left"; progressBarContainer.Style["width"] = "100%"; progressBarContainer.Controls.Add(progressBar); HideElement(progressBarContainer); var progressBarHolder = new HtmlGenericControl("div"); progressBarHolder.Attributes.Add("class", "ajax__fileupload_ProgressBarHolder"); progressBarHolder.Controls.Add(progressBarContainer); footerContainer.Controls.Add(progressBarHolder); footerContainer.Controls.Add(uploadOrCancelButton); return footerContainer; } HtmlGenericControl GenerateHtmlSelectFileContainer(Control html5InputFileElement, Control inputFileElement) { // build select file Container that stays on top var htmlSelectFileContainer = new HtmlGenericControl("span"); htmlSelectFileContainer.Attributes.Add("id", ClientID + "_SelectFileContainer"); htmlSelectFileContainer.Attributes.Add("class", "ajax__fileupload_selectFileContainer"); htmlSelectFileContainer.Style["float"] = "left"; // build select file button var htmlSelectFileButton = new HtmlGenericControl("span"); htmlSelectFileButton.Attributes.Add("id", ClientID + "_SelectFileButton"); htmlSelectFileButton.Attributes.Add("class", "ajax__fileupload_selectFileButton"); htmlSelectFileContainer.Controls.Add(htmlSelectFileButton); htmlSelectFileContainer.Controls.Add(inputFileElement); htmlSelectFileContainer.Controls.Add(html5InputFileElement); return htmlSelectFileContainer; } HtmlGenericControl GenerateHtmlTopFileStatus(Control fileStatusContainer) { var htmlTopFileStatus = new HtmlGenericControl("div"); htmlTopFileStatus.Attributes.Add("class", "ajax__fileupload_topFileStatus"); htmlTopFileStatus.Style[HtmlTextWriterStyle.Position] = "relative"; htmlTopFileStatus.Controls.Add(fileStatusContainer); return htmlTopFileStatus; } void HideElement(HtmlControl element) { element.Style["display"] = "none"; element.Style["visibility"] = "hidden"; } protected override void DescribeComponent(ScriptComponentDescriptor descriptor) { base.DescribeComponent(descriptor); if(IsDesignMode) return; descriptor.AddProperty("contextKey", ContextKey); descriptor.AddProperty("postBackUrl", Page.Request.RawUrl); descriptor.AddProperty("serverPollingSupport", ServerPollingSupport); descriptor.AddProperty("enabled", Enabled); if(ThrobberID != String.Empty) { Control control = FindControl(ThrobberID); if(control != null) descriptor.AddElementProperty("throbber", control.ClientID); } descriptor.AddProperty("uploadHandlerPath", ResolveUploadHandlerPath(UploadHandlerPath)); } string ResolveUploadHandlerPath(string uploadHandlerPath) { if(String.IsNullOrWhiteSpace(uploadHandlerPath)) return CombineUrl(Page.Response.ApplyAppPathModifier(Page.Request.ApplicationPath), "AjaxFileUploadHandler.axd"); return uploadHandlerPath; } static string CombineUrl(string part1, string part2) { if(!part1.EndsWith("/")) part1 += "/"; return part1 + part2; } public static void CheckTempFilePath(string tmpFilePath) { if(!IsValidExtension(tmpFilePath) || !IsValidLastFolderName(tmpFilePath) || !IsImmediateFolder(tmpFilePath)) throw new Exception("Insecure operation prevented"); } static bool IsImmediateFolder(string tmpFilePath) { var rootTempFolderFromParam = Path.GetFullPath(GetGrandParentDirectoryName(tmpFilePath)); var rootTempFolder = Path.GetFullPath(GetRootTempFolder()); return String.Compare(rootTempFolder, rootTempFolderFromParam, true) == 0; } static bool IsValidLastFolderName(string tmpFilePath) { var directory = Path.GetFullPath(Path.GetDirectoryName(tmpFilePath)); return Regex.IsMatch(directory, @"[\w-]{36}$", RegexOptions.IgnoreCase); } static bool IsValidExtension(string tmpFilePath) { return String.Compare(Path.GetExtension(tmpFilePath), Constants.UploadTempFileExtension, true) == 0; } static string GetGrandParentDirectoryName(string tmpFilePath) { return Path.GetDirectoryName(Path.GetDirectoryName(tmpFilePath)); } class UploadRequestProcessor { public AjaxFileUpload Control; public EventHandler<AjaxFileUploadStartEventArgs> UploadStart; public EventHandler<AjaxFileUploadEventArgs> UploadComplete; public EventHandler<AjaxFileUploadCompleteAllEventArgs> UploadCompleteAll; public Action<string> SetUploadedFilePath; HttpRequest Request { get { return Control.Context.Request; } } HttpResponse Response { get { return Control.Context.Response; } } public void ProcessRequest() { string fileId; var xhrType = ParseRequest(out fileId); if(xhrType != XhrType.None) { Response.ClearContent(); Response.Cache.SetCacheability(HttpCacheability.NoCache); // Process xhr request switch(xhrType) { case XhrType.Poll: // Upload progress polling request XhrPoll(fileId); break; case XhrType.Cancel: // Cancel upload request XhrCancel(fileId); break; case XhrType.Done: // A file is successfully uploaded XhrDone(fileId); break; case XhrType.Complete: // All files successfully uploaded XhrComplete(); break; case XhrType.Start: XhrStart(); break; } Response.End(); } } XhrType ParseRequest(out string fileId) { fileId = Request.QueryString["guid"]; if(!string.IsNullOrEmpty(fileId)) { if(Request.QueryString["poll"] == "1") return XhrType.Poll; if(Request.QueryString["cancel"] == "1") return XhrType.Cancel; if(Request.QueryString["done"] == "1") return XhrType.Done; } if(Request.QueryString["complete"] == "1") return XhrType.Complete; if(Request.QueryString["start"] == "1") return XhrType.Start; return XhrType.None; } void XhrStart() { var filesInQueue = int.Parse(Request.QueryString["queue"] ?? "0"); var args = new AjaxFileUploadStartEventArgs(filesInQueue); if(UploadStart != null) UploadStart(Control, args); Response.Write(new JavaScriptSerializer().Serialize(args)); } void XhrComplete() { var filesInQueue = int.Parse(Request.QueryString["queue"] ?? "0"); var filesUploaded = int.Parse(Request.QueryString["uploaded"] ?? "0"); var reason = Request.QueryString["reason"]; AjaxFileUploadCompleteAllReason completeReason; switch(reason) { case "done": completeReason = AjaxFileUploadCompleteAllReason.Success; break; case "cancel": completeReason = AjaxFileUploadCompleteAllReason.Canceled; break; default: completeReason = AjaxFileUploadCompleteAllReason.Unknown; break; } var args = new AjaxFileUploadCompleteAllEventArgs(filesInQueue, filesUploaded, completeReason); if(UploadCompleteAll != null) UploadCompleteAll(Control, args); Response.Write(new JavaScriptSerializer().Serialize(args)); } void XhrDone(string fileId) { AjaxFileUploadEventArgs args; var tempFolder = GetTempFolder(fileId); if(!Directory.Exists(tempFolder)) return; var files = Directory.GetFiles(tempFolder); if(files.Length == 0) return; var fileInfo = new FileInfo(files[0]); CheckTempFilePath(fileInfo.FullName); SetUploadedFilePath(fileInfo.FullName); var originalFilename = StripTempFileExtension(fileInfo.Name); args = new AjaxFileUploadEventArgs( fileId, AjaxFileUploadState.Success, "Success", originalFilename, (int)fileInfo.Length, Path.GetExtension(originalFilename)); if(UploadComplete != null) UploadComplete(Control, args); args.DeleteTemporaryData(); Response.Write(new JavaScriptSerializer().Serialize(args)); } static string StripTempFileExtension(string fileName) { return fileName.Substring(0, fileName.Length - Constants.UploadTempFileExtension.Length); } void XhrCancel(string fileId) { AjaxFileUploadHelper.Abort(Control.Context, fileId); } void XhrPoll(string fileId) { Response.Write((new AjaxFileUploadStates(Control.Context, fileId)).Percent.ToString()); } } } }
/* VRActor * MiddleVR * (c) MiddleVR */ using UnityEngine; using System.Collections; using System.Collections.Generic; using MiddleVR_Unity3D; [AddComponentMenu("MiddleVR/Interactions/Actor")] public class VRActor : MonoBehaviour { [SerializeField] private MVRNodesMapper.ENodesSyncDirection m_SyncDirection = MVRNodesMapper.ENodesSyncDirection.NoSynchronization; public MVRNodesMapper.ENodesSyncDirection SyncDirection { get { return m_SyncDirection; } set { _SetSyncDirection(value); } } public string MiddleVRNodeName = ""; public bool Grabable = true; private bool m_SyncDirIsSet = false; private vrNode3D m_MiddleVRNode = null; [HideInInspector] public VRTouch.ETouchParameter TouchEvents = VRTouch.ETouchParameter.ReceiveTouchEvents; private List<VRTouch> m_Touches = new List<VRTouch>(); protected void Start() { if (!m_SyncDirIsSet) { _SetSyncDirection(m_SyncDirection); } if (gameObject.GetComponent<Collider>() == null) { gameObject.AddComponent<BoxCollider>(); } if (gameObject.GetComponent<Collider>() == null) { MVRTools.Log("[X] Actor object '" + gameObject.name + "' has no collider!! Put one or it won't act. "); } } private void _SetSyncDirection(MVRNodesMapper.ENodesSyncDirection iSyncDirection) { m_SyncDirIsSet = true; m_SyncDirection = iSyncDirection; var nodesMapper = MVRNodesMapper.Instance; if (iSyncDirection != MVRNodesMapper.ENodesSyncDirection.NoSynchronization) { // Set new MiddleVR - Unity nodes mapping if needed m_MiddleVRNode = nodesMapper.AddMapping(this.gameObject, MiddleVRNodeName, iSyncDirection); } else if(m_MiddleVRNode != null) { // No synchronization and existing mvrNode: stop node synchronization nodesMapper.RemoveMapping(m_MiddleVRNode.GetName()); m_MiddleVRNode = null; } } public vrNode3D GetMiddleVRNode() { // GetMiddleVRNode() can be called before Start(). In this case, // we need to call '_SetSyncDirection()'. if (m_SyncDirIsSet) { return m_MiddleVRNode; } else { _SetSyncDirection(m_SyncDirection); return m_MiddleVRNode; } } protected void OnDestroy() { foreach (VRTouch touch in m_Touches) { _SendVRTouchEnd(touch,true); } // Stop node synchronization if (MiddleVR.VRKernel != null && m_MiddleVRNode != null) { MVRNodesMapper.Instance.RemoveMapping(m_MiddleVRNode.GetName()); } } public List<VRTouch> GetTouches() { return new List<VRTouch>(m_Touches); } // ***** RECEIVE TOUCH protected void _OnMVRTouchBegin(VRTouch iTouch) { if (TouchEvents == VRTouch.ETouchParameter.ReceiveTouchEvents) { m_Touches.Add(iTouch); //MiddleVRTools.Log(2, "Touch begin: " + iSrc.name + ". NbTouch: " + m_Touches.Count ); SendMessage("OnMVRTouchBegin", iTouch,SendMessageOptions.DontRequireReceiver); } } protected void _OnMVRTouchMoved(VRTouch iTouch) { if (TouchEvents == VRTouch.ETouchParameter.ReceiveTouchEvents) { //MiddleVRTools.Log(2, "Touch end: " + iSrc.name + ".NbTouch: " + m_Touches.Count); SendMessage("OnMVRTouchMoved", iTouch, SendMessageOptions.DontRequireReceiver); } } protected void _OnMVRTouchEnd(VRTouch iTouch) { if (TouchEvents == VRTouch.ETouchParameter.ReceiveTouchEvents) { m_Touches.Remove(iTouch); //MiddleVRTools.Log(2, "Touch end: " + iSrc.name + ".NbTouch: " + m_Touches.Count); SendMessage("OnMVRTouchEnd", iTouch, SendMessageOptions.DontRequireReceiver); } } // ***** SEND TOUCH protected void OnTriggerEnter(Collider collider) { if (TouchEvents == VRTouch.ETouchParameter.SendTouchEvents) { GameObject touchedObject = collider.gameObject; // Other actor VRActor otherActor = touchedObject.GetComponent<VRActor>(); if (otherActor != null) { VRTouch touch = new VRTouch(); touch.TouchedObject = touchedObject; touch.TouchObject = this.gameObject; // Send message to touched object otherActor._OnMVRTouchBegin(touch); // Send message to ourself so attached script can also react this.SendMessage("OnMVRTouchBegin", touch, SendMessageOptions.DontRequireReceiver); m_Touches.Add(touch); } } } protected VRTouch _FindVRTouch(GameObject iTouchedObject) { VRTouch touch = null; // Find existing VRTouch foreach (VRTouch touchInList in m_Touches) { if (touchInList.TouchedObject == iTouchedObject) { touch = touchInList; } } return touch; } protected void OnTriggerStay(Collider collider) { if (TouchEvents == VRTouch.ETouchParameter.SendTouchEvents) { // We are the touch emitter GameObject touchedObject = collider.gameObject; VRActor actor = touchedObject.GetComponent<VRActor>(); if (actor != null) { VRTouch touch = _FindVRTouch(touchedObject); if (touch != null) { // Send message to touched object actor._OnMVRTouchMoved(touch); // Send message to ourself this.SendMessage("OnMVRTouchMoved", touch, SendMessageOptions.DontRequireReceiver); } } } } protected void OnTriggerExit(Collider collider) { if (TouchEvents == VRTouch.ETouchParameter.SendTouchEvents) { // We are the touch emitter GameObject touchedObject = collider.gameObject; VRTouch touch = _FindVRTouch(touchedObject); if (touch != null) { _SendVRTouchEnd(touch, false); } } } protected void _SendVRTouchEnd(VRTouch iTouch,bool iOnDestroy) { // Other actor VRActor actor = iTouch.TouchedObject.GetComponent<VRActor>(); if (actor != null) { // Send message to touched object actor._OnMVRTouchEnd(iTouch); // Send message to ourself this.SendMessage("OnMVRTouchEnd", iTouch, SendMessageOptions.DontRequireReceiver); // XXX Cb: in OnDestroy we are iterating over the m_Touches list // here we are removing an element, so in OnDestroy, foreach // complains that the list has been modified // There is probably a cleaner way to do this !! if (!iOnDestroy) { // Ourself m_Touches.Remove(iTouch); } } } }