Пример #1
0
            public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
            {
                // Resolve the node if not already
                if (_http._node != null)
                {
                    var name = binder.Name.ToLower();
                    _inner = new UrlSegment(_http, name);
                }

                // A single nameless parameter means a POST entity
                dynamic body = null;

                if (binder.CallInfo.ArgumentCount == 1 && binder.CallInfo.ArgumentNames.Count == 0)
                {
                    body = args[0];
                }
                var url    = BuildUrl();
                var method = "GET";

                if (body != null)
                {
                    method = "POST";
                }
                var names = binder.CallInfo.ArgumentNames.Select(n => n.ToLowerInvariant()).ToList();

                method = GetMethodOverride(method, args, names);
                var queryString = BuildQueryString(names, args);

                result = _http.Execute(url, queryString, method, body);
                return(true);
            }
Пример #2
0
        // Single segment with parameters
        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            var name = binder.Name.ToLowerInvariant();
            var node = new UrlSegment(this, name);

            return(node.TryInvokeMember(binder, args, out result));
        }
Пример #3
0
        private static PageReference CreateOrganisationalUnitFolderPage(IContentRepository contentRepository, ContentReference parent)
        {
            OrganisationalUnitFolderPage defaultPageData = contentRepository.GetDefault <OrganisationalUnitFolderPage>(parent, typeof(OrganisationalUnitFolderPage).GetPageType().ID, LanguageSelector.AutoDetect().Language);

            defaultPageData.PageName   = ORGANISATIONAL_UNIT_FOLDER_NAME;
            defaultPageData.URLSegment = UrlSegment.CreateUrlSegment(defaultPageData);
            return(contentRepository.Save(defaultPageData, SaveAction.Publish, AccessLevel.Publish).ToPageReference());
        }
Пример #4
0
 public RouteMatchTree(Route route, string path, IPomonaSession session)
 {
     Session = session;
     Root = new UrlSegment(route,
                           path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries)
                               .Select(HttpUtility.UrlDecode)
                               .ToArray(), this);
 }
Пример #5
0
        private void TransformPage(PageData sourcePage, bool clearPropertyValues = true)
        {
            MigrationHook.Invoke(new BeforePageTransformEvent(sourcePage), Logger);

            _currentConvertablePageData.Properties = sourcePage.Property;
            _currentConvertablePageData.TypeName   = sourcePage.PageTypeName;

            var pTRepo         = ServiceLocator.Current.GetInstance <PageTypeRepository>();
            var sourcePageType = pTRepo.Load(sourcePage.PageTypeID);
            var targetPageType = pTRepo.Load(_mapper.GetTargetPageType(sourcePage));

            string result;

            //Convert The Page
            if (clearPropertyValues)
            {
                var keys       = new List <KeyValuePair <int, int> >();
                var properties = sourcePage.Property.Select(p => p.PropertyDefinitionID).Where(p => p > 0);
                foreach (var propertyId in properties)
                {
                    keys.Add(new KeyValuePair <int, int>(propertyId, 0));
                }

                //Convert The Page
                result = PageTypeConverter.Convert(sourcePage.PageLink, sourcePageType, targetPageType,
                                                   keys, false, false, _repo);
            }
            else
            {
                result = PageTypeConverter.Convert(sourcePage.PageLink, sourcePageType, targetPageType,
                                                   new List <KeyValuePair <int, int> >(), false, false, _repo);
            }
            Logger.Log(result);

            var transformedPage = _repo.Get <PageData>(sourcePage.PageLink).CreateWritableClone();

            _mapper.SetPropertyValues(transformedPage, _currentConvertablePageData);

            transformedPage.URLSegment = UrlSegment.GetUrlFriendlySegment(transformedPage.URLSegment);
            var oldPrincipal = PrincipalInfo.CurrentPrincipal;

            try {
                PrincipalInfo.CurrentPrincipal =
                    PrincipalInfo.CreatePrincipal(sourcePage.ChangedBy);
                global::EPiServer.BaseLibrary.Context.Current["PageSaveDB:PageSaved"] = true;
                var savedPage = _repo.Save(transformedPage,
                                           SaveAction.ForceCurrentVersion | SaveAction.Publish | SaveAction.SkipValidation,
                                           AccessLevel.NoAccess);

                MigrationHook.Invoke(new AfterPageTransformEvent(savedPage), Logger);
            }
            finally {
                global::EPiServer.BaseLibrary.Context.Current["PageSaveDB:PageSaved"] = null;
                PrincipalInfo.CurrentPrincipal = oldPrincipal;
            }
        }
Пример #6
0
        private PageReference CreateDatePage(IContentRepository contentRepository, ContentReference parent, string name, DateTime startPublish)
        {
            BlogListPage defaultPageData = contentRepository.GetDefault <BlogListPage>(parent, typeof(BlogListPage).GetPageType().ID, LanguageSelector.AutoDetect().Language);

            defaultPageData.PageName     = name;
            defaultPageData.Heading      = name;
            defaultPageData.StartPublish = startPublish;
            defaultPageData.URLSegment   = UrlSegment.CreateUrlSegment(defaultPageData);
            return(contentRepository.Save(defaultPageData, SaveAction.Publish, AccessLevel.Publish).ToPageReference());
        }
        public void TestParameterSegmentDoesTransform()
        {
            const string paramName  = "paramName";
            const string paramValue = "paramValue";
            var          param      = new RestParam(paramName, paramValue);

            var segment = UrlSegment.Parameter(paramName);

            Assert.That(segment.Transform(param.Yield()), Is.EqualTo(paramValue));
        }
Пример #8
0
        private static PageReference CreateOrganisationalUnitFolderPage(IContentRepository contentRepository, ContentReference parent)
        {
            OrganisationalUnitFolderPage defaultPageData = contentRepository.GetDefault <OrganisationalUnitFolderPage>(parent, typeof(OrganisationalUnitFolderPage).GetPageType().ID, LanguageSelector.AutoDetect().Language);

            defaultPageData.PageName        = ORGANISATIONAL_UNIT_FOLDER_NAME;
            defaultPageData.URLSegment      = UrlSegment.CreateUrlSegment(defaultPageData);
            defaultPageData.MenuDescription = "Containing all the organisational units for the compare service";
            defaultPageData.MenuTitle       = "Organisational units for the compare service";
            defaultPageData.VisibleInMenu   = false;
            return(contentRepository.Save(defaultPageData, SaveAction.Publish, AccessLevel.Publish).ToPageReference());
        }
Пример #9
0
        internal static IQueryable Query(this IPomonaSession session,
                                         UrlSegment urlSegment)
        {
            if (session == null)
                throw new ArgumentNullException(nameof(session));
            if (urlSegment == null)
                throw new ArgumentNullException(nameof(urlSegment));

            var request = new PomonaContext(urlSegment, acceptType : typeof(IQueryable), handleException : false);
            return (IQueryable)session.Dispatch(request).Entity;
        }
        public void TestParameterSegmentWithNoMatchThrows()
        {
            const string paramName   = "paramName";
            const string paramValue  = "paramValue";
            const string segmentName = "segmentName";
            var          param       = new RestParam(paramName, paramValue);

            var segment = UrlSegment.Parameter(segmentName);

            Assert.That(() => segment.Transform(param.Yield()), Throws.InvalidOperationException);
        }
        public void TestParameterSegmentWithMultipleMatchesThrows()
        {
            const string paramName  = "paramName";
            const string paramValue = "paramValue";

            var param = new RestParam(paramName, paramValue);

            var segment = UrlSegment.Parameter(paramName);

            Assert.That(() => segment.Transform(param.ConcatWith(param)), Throws.InvalidOperationException);
        }
Пример #12
0
        internal static object Get(this IPomonaSession session,
                                   UrlSegment urlSegment)
        {
            if (session == null)
                throw new ArgumentNullException(nameof(session));
            if (urlSegment == null)
                throw new ArgumentNullException(nameof(urlSegment));

            var request = new PomonaContext(urlSegment, executeQueryable : true, handleException : false);
            return session.Dispatch(request).Entity;
        }
Пример #13
0
            public override bool TryGetMember(GetMemberBinder binder, out object result)
            {
                var name = binder.Name.ToLower();

                if (_inner != null)
                {
                    return(_inner.TryGetMember(binder, out result));
                }
                _inner = new UrlSegment(_http, name);
                result = _inner;
                return(true);
            }
Пример #14
0
 // Опис: Метод за креирање на MIM порака за повик
 // Влезни параметри: UrlSegment urlSegments, податочни вредности transactionID
 // Излезни параметри: SoapMessage модел
 public SoapMessage CreateMimRequestMsg(UrlSegment urlSegments, string transactionID)
 {
     return(new SoapMessage
     {
         Header = new Header
         {
             MimHeader = new MimHeader
             {
                 id = "MIMHeader",
                 Consumer = urlSegments.Consumer,
                 Provider = String.Empty,
                 RoutingToken = urlSegments.RoutingToken,
                 Service = urlSegments.Service,
                 ServiceMethod = string.Empty,
                 //TransactionId = Guid.NewGuid().ToString(),
                 TransactionId = transactionID,
                 Dir = "Request",
                 PublicKey = string.Empty,
                 MimeType = String.Empty,
                 //TimeStamp = datetimeTS,
                 CorrelationID = String.Empty,
                 CallType = urlSegments.Async ? MimHeaderCallType.asynchronous : MimHeaderCallType.synchronous,
                 //Signature = new MimSignature()
             },
             MimAdditionalHeader = new MimAdditionalHeader()
             {
                 Status = String.Empty,
                 StatusMessage = String.Empty,
                 ProviderEndpointUrl = String.Empty,
                 ExternalEndpointUrl = String.Empty,
                 WebServiceUrl = String.Empty,
                 IsInteropTestCommunicationCall = urlSegments.IsInteropTestCommunicationCall,
                 ConsumerBusCode = "" // AppSettings.Get<string>("KingExternalBusCode"),
                                      //TimeStampToken = resultGenerateTS
             },
             CryptoHeader = new CryptoHeader()
             {
                 Key = string.Empty,
                 InitializationVector = string.Empty,
                 FormatValue = "AES"
             }
         },
         Body = new Body()
         {
             MimBody = new MimBody()
             {
                 id = "MIMBody",
                 Message = string.Empty
             }
         }
     });
 }
Пример #15
0
        private static PomonaResponse ValidateResourceEtag(string ifMatch, UrlSegment node)
        {
            var resourceType = node.ResultType as ResourceType;
            if (resourceType == null)
                return null;
            var etagProp = resourceType.ETagProperty;
            if (etagProp == null)
                throw new InvalidOperationException("Unable to perform If-Match on entity with no etag.");

            if ((string)etagProp.GetValue(node.Value) != ifMatch)
                throw new ResourcePreconditionFailedException("Etag of entity did not match If-Match header.");
            return null;
        }
Пример #16
0
 public SoapMessage CreateMimRequestMsg(UrlSegment urlSegments, string transactionID, string soapAction, string soapBody, string sessionKey, string iVector, string soapMethodName, OwnCertificate ownCert)
 {
     return(new SoapMessage()
     {
         Header = new Header()
         {
             MimHeader = new MimHeader()
             {
                 id = "Header",
                 Consumer = urlSegments.Consumer,
                 Provider = String.Empty,
                 RoutingToken = urlSegments.RoutingToken,
                 Service = urlSegments.Service,
                 ServiceMethod = soapMethodName,
                 //TransactionId = Guid.NewGuid().ToString(),
                 TransactionId = transactionID,
                 Dir = "Request",
                 PublicKey = ownCert.PublicKey,
                 MimeType = String.Empty,
                 TimeStamp = DateTime.Now,
                 CorrelationID = String.Empty,
                 CallType = urlSegments.Async ? MimHeaderCallType.asynchronous : MimHeaderCallType.synchronous,
                 Signature = new MimSignature()
             },
             MimAdditionalHeader = new MimAdditionalHeader()
             {
                 Status = String.Empty,
                 StatusMessage = String.Empty,
                 ProviderEndpointUrl = String.Empty,
                 ExternalEndpointUrl = String.Empty,
                 WebServiceUrl = String.Empty
             },
             CryptoHeader = new CryptoHeader()
             {
                 Key = sessionKey,
                 InitializationVector = iVector,
                 FormatValue = "AES"
             }
         },
         Body = new Body()
         {
             MimBody = new MimBody()
             {
                 id = "Body",
                 Message = soapBody
             }
         }
     });
 }
Пример #17
0
 private static void WalkSegments(ICollection <string> segments, UrlSegment node, ref int count, ref bool skipSeparator)
 {
     if (node._inner == null)
     {
         return;
     }
     if (!skipSeparator)
     {
         segments.Add(node._inner.Separator);
     }
     skipSeparator = node._inner.Separator.Equals(".");
     segments.Add(node._inner.Name);
     count++;
     WalkSegments(segments, node._inner, ref count, ref skipSeparator);
 }
Пример #18
0
        static List <UrlSegment> ParsePathSegments(Uri templateUri)
        {
            var passedSegments   = new List <UrlSegment>();
            var originalSegments = templateUri.Segments;

            foreach (var segmentText in originalSegments)
            {
                UrlSegment parsedSegment;
                var        unescapedSegment = Uri.UnescapeDataString(segmentText);
                //  TODO: Check we don't double decode the wrong / here, potential issue
                var    sanitizedSegment  = unescapedSegment.Replace("/", string.Empty);
                var    trailingSeparator = unescapedSegment.Length - sanitizedSegment.Length > 0;
                string variableName;
                if (sanitizedSegment == string.Empty) // this is the '/' returned by Uri which we don't care much for
                {
                    continue;
                }
                if ((variableName = GetVariableName(unescapedSegment)) != null)
                {
                    parsedSegment = new UrlSegment
                    {
                        Text = variableName, OriginalText = sanitizedSegment, Type = SegmentType.Variable,
                        TrailingSeparator = trailingSeparator
                    }
                }
                ;
                else if (string.Compare(unescapedSegment, WILDCARD_TEXT, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    parsedSegment = new UrlSegment
                    {
                        Text = WILDCARD_TEXT, OriginalText = sanitizedSegment, Type = SegmentType.Wildcard
                    }
                }
                ;
                else
                {
                    parsedSegment = new UrlSegment
                    {
                        Text = sanitizedSegment, OriginalText = sanitizedSegment, Type = SegmentType.Literal,
                        TrailingSeparator = trailingSeparator
                    }
                };

                passedSegments.Add(parsedSegment);
            }

            return(passedSegments);
        }
Пример #19
0
        /// <summary>
        /// Set statistics to the tag pages. Adds a tag page if required.
        /// Also deletes any tag pages if the corresponding category has been deleted manually.
        /// </summary>
        /// <param name="tagStats">The usage statistics collection.</param>
        /// <param name="startPage">The start page for the blog.</param>
        /// <param name="isTeamLevel">If set to <c>true</c> we are on a team level blog.</param>
        private static void SetStatsToPages(Dictionary <string, int> tagStats, PageData startPage, bool isTeamLevel)
        {
            if (startPage[BlogUtility.TagContainerPropertyName] == null)
            {
                return;
            }

            PageData                 tagContainer = DataFactory.Instance.GetPage((PageReference)startPage[BlogUtility.TagContainerPropertyName]);
            PageDataCollection       tagPages     = DataFactory.Instance.GetChildren(tagContainer.PageLink);
            PageData                 tagPage;
            Dictionary <string, int> tagCloudValues = CreateTagCloudValues(tagStats);

            foreach (string key in tagStats.Keys)
            {
                if (FindPageByName(key, tagPages, out tagPage))
                {
                    if (tagStats[key] > 0)
                    {
                        tagPage = tagPage.CreateWritableClone();
                        tagPage[BlogUtility.UsageStatisticsPropertyName] = tagStats[key];
                        tagPage[BlogUtility.TagCloudValuePropertyName]   = tagCloudValues[key];
                        DataFactory.Instance.Save(tagPage, SaveAction.Publish, AccessLevel.NoAccess);
                    }
                    else
                    {
                        DataFactory.Instance.Delete(tagPage.PageLink, true, AccessLevel.NoAccess);
                    }
                }
                else if (tagStats[key] > 0)
                {
                    //Create tag Page
                    tagPage            = DataFactory.Instance.GetDefaultPageData(tagContainer.PageLink, BlogUtility.ListPageTypeName);
                    tagPage.PageName   = key;
                    tagPage.URLSegment = UrlSegment.CreateUrlSegment(tagPage);
                    tagPage[BlogUtility.IsTagListingPropertyName]    = true;
                    tagPage[BlogUtility.IsTeamLevelPropertyName]     = isTeamLevel;
                    tagPage[BlogUtility.UsageStatisticsPropertyName] = tagStats[key];
                    tagPage[BlogUtility.TagCloudValuePropertyName]   = tagCloudValues[key];
                    DataFactory.Instance.Save(tagPage, SaveAction.Publish, AccessLevel.NoAccess);
                }
            }

            //If a category has been deleted we should remove its corresponding tag page.
            foreach (PageData page in tagPages.Where(p => !tagStats.ContainsKey(p.PageName)))
            {
                DataFactory.Instance.Delete(page.PageLink, true, AccessLevel.NoAccess);
            }
        }
Пример #20
0
 public PomonaContext(UrlSegment node,
                      PomonaRequest request = null,
                      string expandedPaths = null,
                      bool executeQueryable = false,
                      bool handleException = true,
                      Type acceptType = null)
 {
     if (node == null)
         throw new ArgumentNullException(nameof(node));
     Node = node;
     Request = request ?? new PomonaRequest(node.RelativePath, node.RelativePath);
     ExpandedPaths = expandedPaths ?? GetExpandedPathsFromRequest(Request.Headers, Query);
     ExecuteQueryable = executeQueryable;
     HandleException = handleException;
     AcceptType = acceptType;
 }
Пример #21
0
        internal static object Get(this IPomonaSession session,
                                   UrlSegment urlSegment)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (urlSegment == null)
            {
                throw new ArgumentNullException(nameof(urlSegment));
            }

            var request = new PomonaContext(urlSegment, executeQueryable: true, handleException: false);

            return(session.Dispatch(request).Entity);
        }
Пример #22
0
        internal static IQueryable Query(this IPomonaSession session,
                                         UrlSegment urlSegment)
        {
            if (session == null)
            {
                throw new ArgumentNullException(nameof(session));
            }
            if (urlSegment == null)
            {
                throw new ArgumentNullException(nameof(urlSegment));
            }

            var request = new PomonaContext(urlSegment, acceptType: typeof(IQueryable), handleException: false);

            return((IQueryable)session.Dispatch(request).Entity);
        }
Пример #23
0
        /// <summary>
        /// Copies the selected workroom template to create an active workrooms.
        /// Sets up the name of the new workroom.
        /// </summary>
        /// <param name="templateRef">A reference to the selected workroom template</param>
        /// <returns>The new workroom startpage.</returns>
        private PageData CopyAndSetUpWorkroomPage(PageReference templateRef)
        {
            //Copy page structure wihout access check of source pages since the user might not have read access to the template pages.
            PageReference newWorkroomRef = DataFactory.Instance.Copy(templateRef, CurrentPageLink, AccessLevel.NoAccess, AccessLevel.Publish, true, false);
            PageData      newWorkroom    = DataFactory.Instance.GetPage(newWorkroomRef).CreateWritableClone();

            newWorkroom.PageName = NewWorkroomName.Text.ToSafeString();
            newWorkroom[_mainBodyPropertyName] = NewWorkroomDescription.Text.ToSafeString();
            newWorkroom.URLSegment             = String.Empty;

            newWorkroom.URLSegment          = UrlSegment.CreateUrlSegment(newWorkroom);
            newWorkroom["WorkroomTemplate"] = templateRef;
            newWorkroom.VisibleInMenu       = true;
            DataFactory.Instance.Save(newWorkroom, SaveAction.Publish);

            return(newWorkroom);
        }
Пример #24
0
        public bool IsEquivalentTo(UriTemplate other)
        {
            if (other == null)
            {
                return(false);
            }
            if (_segments.Count != other._segments.Count)
            {
                return(false);
            }
            if (_queryStringVariables.Count != other._queryStringVariables.Count)
            {
                return(false);
            }
            for (int i = 0; i < _segments.Count; i++)
            {
                UrlSegment thisSegment  = _segments[i];
                UrlSegment otherSegment = other._segments[i];
                if (thisSegment.Type != otherSegment.Type)
                {
                    return(false);
                }
                if (thisSegment.Type == SegmentType.Literal && thisSegment.Text != otherSegment.Text)
                {
                    return(false);
                }
            }
            foreach (var thisSegment in _queryStringVariables)
            {
                if (!other._queryStringVariables.ContainsKey(thisSegment.Key))
                {
                    return(false);
                }
                QuerySegment otherSegment = other._queryStringVariables[thisSegment.Key];

                if (thisSegment.Value.Type != otherSegment.Type)
                {
                    return(false);
                }
                if (thisSegment.Value.Type == SegmentType.Literal && thisSegment.Value.Value != otherSegment.Value)
                {
                    return(false);
                }
            }
            return(true);
        }
        public void TestLiteralSegmentDoesNotThrow()
        {
            const string paramName   = "paramName";
            const string paramValue  = "paramValue";
            const string segmentName = "segmentName";
            var          param       = new RestParam(paramName, paramValue);

            var segment = UrlSegment.Literal(segmentName);

            //check that passing in parameters where none match is okay
            Assert.That(segment.Transform(param.Yield()), Is.EqualTo(segmentName));

            var conflictingParam = new RestParam(segmentName, paramValue);

            //check that multiple matching params are okay
            Assert.That(segment.Transform(conflictingParam.ConcatWith(conflictingParam)), Is.EqualTo(segmentName));
        }
Пример #26
0
        private IContent CreateAndAssignIdentity(MappedIdentity mappedIdentity, Type modelType, string name)
        {
            // Find parent
            var parentLink = EntryPoint;

            if (modelType == typeof(YouTubeVideo))
            {
                parentLink = SearchResultNode;
            }
            else if (modelType != typeof(YouTubeFolder))
            {
                parentLink = new ContentReference(int.Parse(RemoveEndingSlash(mappedIdentity.ExternalIdentifier.Segments[2])), ProviderKey);
            }

            // Set content type and content type Id.
            var contentType = ContentTypeRepository.Load(modelType);
            var content     = ContentFactory.CreateContent(contentType);

            content.ContentTypeID = contentType.ID;
            content.ParentLink    = parentLink;
            content.ContentGuid   = mappedIdentity.ContentGuid;
            content.ContentLink   = mappedIdentity.ContentLink;
            content.Name          = name;
            (content as IRoutable).RouteSegment = UrlSegment.GetUrlFriendlySegment(content.Name);

            var securable = content as IContentSecurable;

            securable.GetContentSecurityDescriptor().AddEntry(new AccessControlEntry(EveryoneRole.RoleName, AccessLevel.Read));

            var versionable = content as IVersionable;

            if (versionable != null)
            {
                versionable.Status = VersionStatus.Published;
            }

            var changeTrackable = content as IChangeTrackable;

            if (changeTrackable != null)
            {
                changeTrackable.Changed = DateTime.Now;
            }

            return(content);
        }
Пример #27
0
        static List <UrlSegment> ParseSegments(Uri _templateUri)
        {
            var pasedSegments = new List <UrlSegment>();

#if !SILVERLIGHT
            string[] originalSegments = _templateUri.Segments;
#else
            var originalSegments = _templateUri.AbsolutePath.Split('/');
#endif
            foreach (string segmentText in originalSegments)
            {
                UrlSegment parsedSegment;
                string     unescapedSegment  = Uri.UnescapeDataString(segmentText);
                string     sanitizedSegment  = unescapedSegment.Replace("/", string.Empty);
                bool       trailingSeparator = unescapedSegment.Length - sanitizedSegment.Length > 0;
                string     variableName;
                if (sanitizedSegment == string.Empty) // this is the '/' returned by Uri which we don't care much for
                {
                    continue;
                }
                if ((variableName = GetVariableName(unescapedSegment)) != null)
                {
                    parsedSegment = new UrlSegment {
                        Text = variableName, OriginalText = sanitizedSegment, Type = SegmentType.Variable, TrailingSeparator = trailingSeparator
                    }
                }
                ;
                else if (string.Compare(unescapedSegment, WILDCARD_TEXT, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    parsedSegment = new UrlSegment {
                        Text = WILDCARD_TEXT, OriginalText = sanitizedSegment, Type = SegmentType.Wildcard
                    }
                }
                ;
                else
                {
                    parsedSegment = new UrlSegment {
                        Text = sanitizedSegment, OriginalText = sanitizedSegment, Type = SegmentType.Literal, TrailingSeparator = trailingSeparator
                    }
                };

                pasedSegments.Add(parsedSegment);
            }
            return(pasedSegments);
        }
Пример #28
0
 public PomonaContext(UrlSegment node,
                      PomonaRequest request = null,
                      string expandedPaths  = null,
                      bool executeQueryable = false,
                      bool handleException  = true,
                      Type acceptType       = null)
 {
     if (node == null)
     {
         throw new ArgumentNullException(nameof(node));
     }
     Node             = node;
     Request          = request ?? new PomonaRequest(node.RelativePath, node.RelativePath);
     ExpandedPaths    = expandedPaths ?? GetExpandedPathsFromRequest(Request.Headers, Query);
     ExecuteQueryable = executeQueryable;
     HandleException  = handleException;
     AcceptType       = acceptType;
 }
Пример #29
0
        private static PomonaResponse ValidateResourceEtag(string ifMatch, UrlSegment node)
        {
            var resourceType = node.ResultType as ResourceType;

            if (resourceType == null)
            {
                return(null);
            }
            var etagProp = resourceType.ETagProperty;

            if (etagProp == null)
            {
                throw new InvalidOperationException("Unable to perform If-Match on entity with no etag.");
            }

            if ((string)etagProp.GetValue(node.Value) != ifMatch)
            {
                throw new ResourcePreconditionFailedException("Etag of entity did not match If-Match header.");
            }
            return(null);
        }
Пример #30
0
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            var name = binder.Name.ToLowerInvariant();

            if (name.Equals("headers"))
            {
                result = _headers;
                return(true);
            }
            if (name.Equals("auth"))
            {
                result = _auth;
                return(true);
            }
            if (_node != null)
            {
                return(_node.TryGetMember(binder, out result));
            }
            _node  = new UrlSegment(this, name);
            result = _node;
            return(true);
        }
Пример #31
0
        public void AssertSegmentIsCorrect(string scheme, string host, int port, string path, int uriMatchPart, string expectedResult)
        {
            // Arrange
            var httpContext = new DefaultHttpContext();

            httpContext.Request.Scheme = scheme;
            httpContext.Request.Host   = new HostString(host, port);
            httpContext.Request.Path   = new PathString(path);

            var context = new RewriteContext {
                HttpContext = httpContext
            };

            context.HttpContext = httpContext;

            // Act
            var segment = new UrlSegment((UriMatchPart)uriMatchPart);
            var results = segment.Evaluate(context, null, null);

            // Assert
            Assert.Equal(expectedResult, results);
        }
Пример #32
0
        private static List<UrlSegment> ParseSegments(Uri templateUri)
        {
            var pasedSegments = new List<UrlSegment>();
            string[] originalSegments = templateUri.Segments;
     
            foreach (string segmentText in originalSegments)
            {
                UrlSegment parsedSegment;
                string unescapedSegment = Uri.UnescapeDataString(segmentText);
                string sanitizedSegment = unescapedSegment.Replace("/", string.Empty);
                bool trailingSeparator = unescapedSegment.Length - sanitizedSegment.Length > 0;
                string variableName;

                // this is the '/' returned by Uri which we don't care much for
                if (sanitizedSegment == string.Empty) 
                {
                    continue;
                }

                if ((variableName = GetVariableName(unescapedSegment)) != null)
                {
                    parsedSegment = new UrlSegment
                        {
                            Text = variableName,
                            OriginalText = sanitizedSegment,
                            Type = SegmentType.Variable,
                            TrailingSeparator = trailingSeparator
                        };
                }
                else if (string.Compare(unescapedSegment, WildcardText, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    parsedSegment = new UrlSegment
                        {
                            Text = WildcardText, OriginalText = sanitizedSegment, Type = SegmentType.Wildcard
                        };
                }
                else
                {
                    parsedSegment = new UrlSegment
                        {
                            Text = sanitizedSegment,
                            OriginalText = sanitizedSegment,
                            Type = SegmentType.Literal,
                            TrailingSeparator = trailingSeparator
                        };
                }

                pasedSegments.Add(parsedSegment);
            }

            return pasedSegments;
        }
Пример #33
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (string.IsNullOrEmpty(_commaSeparatedVersions))
            {
                return;
            }

            var props = context.ActionDescriptor.Properties;
            var url   = context.HttpContext.Request.GetUrl();

            var headerVersion = context.HttpContext.Request.Headers.Count(x => string.Equals(x.Key, Header.Trim(), StringComparison.InvariantCultureIgnoreCase));
            var routeVersion  = context.RouteData.Values[UrlSegment.Trim()];
            var queryVersion  = context.HttpContext.Request.QueryString.Value?.Trim();
            var matchedQuery  = queryVersion?.Replace("?", "").Split('&').FirstOrDefault(x => x.StartsWith($"{QueryString}="));

            var isSkippable = routeVersion == null && headerVersion == 0 && string.IsNullOrEmpty(matchedQuery);

            if (isSkippable)
            {
                return;
            }

            var version = "";

            if (routeVersion != null)
            {
                version = routeVersion.ToString();
            }

            if (headerVersion > 0)
            {
                version = context.HttpContext.Request.Headers["x-api-version"].ToString();
            }

            if (!string.IsNullOrEmpty(matchedQuery))
            {
                version = matchedQuery.Replace($"{QueryString}=", "");
            }

            version = FixVersion(version);
            var unavailableVersions  = _commaSeparatedVersions.Split(',').Select(x => FixVersion(x.Trim()));
            var isUnavailableVersion = unavailableVersions.Contains(version);

            foreach (var prop in props)
            {
                if (prop.Value is ApiVersionModel apiVersionModel)
                {
                    if (apiVersionModel.IsApiVersionNeutral)
                    {
                        return;
                    }

                    var deprecated = apiVersionModel.DeprecatedApiVersions.Select(x => x.ToString());
                    var supported  = apiVersionModel.SupportedApiVersions.Select(x => x.ToString());

                    if (isUnavailableVersion)
                    {
                        context.Result = new JsonResult(new UnavailableApiVersion
                        {
                            Code = "UnavailableApiVersion",
                            AvailableVersions  = supported,
                            DeprecatedVersions = deprecated,
                            Message            = $"The HTTP resource that matches the request URI '{url}' does not available via the API version '{version}'."
                        });
                        context.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    }
                }
            }
        }
Пример #34
0
        static List<UrlSegment> ParseSegments(Uri _templateUri)
        {
            var pasedSegments = new List<UrlSegment>();
            #if !SILVERLIGHT
            string[] originalSegments = _templateUri.Segments;
            #else
            var originalSegments = _templateUri.AbsolutePath.Split('/');
            #endif
            foreach (string segmentText in originalSegments)
            {
                UrlSegment parsedSegment;
                string unescapedSegment = Uri.UnescapeDataString(segmentText);
                string sanitizedSegment = unescapedSegment.Replace("/", string.Empty);
                bool trailingSeparator = unescapedSegment.Length - sanitizedSegment.Length > 0;
                string variableName;
                if (sanitizedSegment == string.Empty) // this is the '/' returned by Uri which we don't care much for
                    continue;
                if ((variableName = GetVariableName(unescapedSegment)) != null)
                    parsedSegment = new UrlSegment {Text = variableName, OriginalText = sanitizedSegment, Type = SegmentType.Variable, TrailingSeparator = trailingSeparator};
                else if (string.Compare(unescapedSegment, WILDCARD_TEXT, StringComparison.OrdinalIgnoreCase) == 0)
                    parsedSegment = new UrlSegment {Text = WILDCARD_TEXT, OriginalText = sanitizedSegment, Type = SegmentType.Wildcard};
                else
                    parsedSegment = new UrlSegment {Text = sanitizedSegment, OriginalText = sanitizedSegment, Type = SegmentType.Literal, TrailingSeparator = trailingSeparator};

                pasedSegments.Add(parsedSegment);
            }
            return pasedSegments;
        }