当前位置: 首页>>代码示例>>C#>>正文


C# Uri.IsBaseOf方法代码示例

本文整理汇总了C#中System.Uri.IsBaseOf方法的典型用法代码示例。如果您正苦于以下问题:C# Uri.IsBaseOf方法的具体用法?C# Uri.IsBaseOf怎么用?C# Uri.IsBaseOf使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在System.Uri的用法示例。


在下文中一共展示了Uri.IsBaseOf方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: AppendPathToUri

        /// <summary>Append a relative path to a Uri, handling traling slashes appropiately.</summary>
        /// <param name="uri">The base Uri. </param>
        /// <param name="relativeOrAbslouteUri">The relative or absloute URI. </param>
        /// <param name="sep">The seperator. </param>
        /// <returns>The appended Uri. </returns>
        internal static Uri AppendPathToUri(Uri uri, string relativeOrAbslouteUri, string sep)
        {
            Uri relativeUri;

            // Because of URI's Scheme, URI.TryCreate() can't differentiate a string with colon from an absolute URI.
            // A workaround is added here to verify if a given string is an absolute URI.
            if (Uri.TryCreate(relativeOrAbslouteUri, UriKind.Absolute, out relativeUri)
                && (relativeUri.Scheme == "http" || relativeUri.Scheme == "https"))
            {
                // Handle case if relPath is an absolute Uri
                if (uri.IsBaseOf(relativeUri))
                {
                    return relativeUri;
                }

                // Happens when using fiddler, DNS aliases, or potentially NATs
                var absoluteUri = new Uri(relativeOrAbslouteUri);
                return new Uri(uri, absoluteUri.AbsolutePath);
            }

            var ub = new UriBuilder(uri);
            var appendString = ub.Path.EndsWith(sep) ? relativeOrAbslouteUri : sep + relativeOrAbslouteUri;

            var escapedRelativeOrAbslouteUri = Uri.EscapeUriString(appendString);
            ub.Path += escapedRelativeOrAbslouteUri;

            return ub.Uri;
        }
开发者ID:wforney,项目名称:azure-sdk-for-net,代码行数:33,代码来源:NavigationHelper.cs

示例2: CreateRequestUsesBaseUri

        public void CreateRequestUsesBaseUri()
        {
            var baseUri = new Uri("http://www.example.com");
            var factory = new RequestFactory(baseUri, "apiKey");

            var request = factory.CreateRequest("test");

            Assert.IsTrue(baseUri.IsBaseOf(request.RequestUri), "Request does not have expected base URI.");
        }
开发者ID:RestfulMonad,项目名称:MetroMetro,代码行数:9,代码来源:RequestFactoryTests.cs

示例3: ToRemote

 public string ToRemote(string localPath)
 {
     foreach (var mapping in localRemote) {
         var localBase = new Uri(mapping.Item1, UriKind.RelativeOrAbsolute);
         var localUrl = new Uri(localPath, UriKind.RelativeOrAbsolute);
         if (localBase.IsBaseOf(localUrl))
             return mapping.Item2 + localBase.MakeRelativeUri(localUrl).OriginalString;
     }
     return null;
 }
开发者ID:bagobor,项目名称:NodeVsDebugger,代码行数:10,代码来源:ScriptMapping.cs

示例4: ReadToken

        /// <summary>
        /// Reads a token from the current user's Visual Studio hive in the Windows Registry.
        /// </summary>
        /// <param name="targetUri">Key used to select the token.</param>
        /// <param name="token">If successful, the token from the registry; otherwise `null`.</param>
        /// <returns>True if successful; otherwise false.</returns>
        public bool ReadToken(TargetUri targetUri, out Token token)
        {
            BaseSecureStore.ValidateTargetUri(targetUri);

            Trace.WriteLine("TokenRegistry::ReadToken");

            foreach (var key in EnumerateKeys(false))
            {
                if (key == null)
                    continue;

                string url;
                string type;
                string value;

                if (KeyIsValid(key, out url, out type, out value))
                {
                    try
                    {
                        Uri tokenUri = new Uri(url);
                        if (tokenUri.IsBaseOf(targetUri.ActualUri))
                        {
                            byte[] data = Convert.FromBase64String(value);

                            data = ProtectedData.Unprotect(data, null, DataProtectionScope.CurrentUser);

                            value = Encoding.UTF8.GetString(data);

                            TokenType tokenType;
                            if (String.Equals(type, "Federated", StringComparison.OrdinalIgnoreCase))
                            {
                                tokenType = TokenType.Federated;
                            }
                            else
                            {
                                throw new InvalidOperationException("Unexpected token type encountered");
                            }

                            token = new Token(value, tokenType);

                            return true;
                        }
                    }
                    catch
                    {
                        Trace.WriteLine("   token read from registry was corrupt");
                    }
                }
            }

            token = null;
            return false;
        }
开发者ID:digitalinfinity,项目名称:Git-Credential-Manager-for-Windows,代码行数:59,代码来源:TokenRegistry.cs

示例5: GetBaseUriToWrite

 internal static Uri GetBaseUriToWrite(Uri rootBase, Uri currentBase)
 {
     if ((rootBase == currentBase) || (currentBase == null))
     {
         return null;
     }
     if ((rootBase != null) && ((rootBase.IsAbsoluteUri && currentBase.IsAbsoluteUri) && rootBase.IsBaseOf(currentBase)))
     {
         return rootBase.MakeRelativeUri(currentBase);
     }
     return currentBase;
 }
开发者ID:amirhalatzi,项目名称:MediaRssSharp,代码行数:12,代码来源:MediaRssFeedFormatter.cs

示例6: Show

        public void Show(string account, Uri authenticationUri, Uri redirectUri)
        {
            if (window == null) {
                waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset);
                var uiThread = new Thread(() => {
                    window = new Window() { Title = account };
                    window.Closing += (s, e) => {
                        window.Hide();
                        waitHandle.Set();
                        e.Cancel = true;
                    };

                    browser = new WebBrowser();
                    browser.Loaded += (s, e) => {
                        browser.Navigate(authenticationUri);
                    };
                    browser.Navigating += (s, e) => {
                        if (redirectUri.IsBaseOf(e.Uri) && redirectUri.AbsolutePath == e.Uri.AbsolutePath) {
                            var parameters = new NameValueCollection();
                            foreach (var parameter in e.Uri.Query.TrimStart('?').Split('&')) {
                                var nameValue = parameter.Split('=');
                                parameters.Add(nameValue[0], nameValue[1]);
                            }
                            var handler = Authenticated;
                            handler?.Invoke(this, new AuthenticatedEventArgs(parameters));
                            e.Cancel = true;
                        }
                    };
                    browser.Navigated += (s, e) => {
                        if (authenticationUri.IsBaseOf(e.Uri))
                            SetForegroundWindow(new WindowInteropHelper(window).Handle);
                    };

                    window.Content = browser;
                    window.Show();

                    System.Windows.Threading.Dispatcher.Run();
                });
                uiThread.SetApartmentState(ApartmentState.STA);
                uiThread.Start();
            } else {
                window.Dispatcher.Invoke(() => {
                    browser.Source = authenticationUri;
                    window.Title = account;
                    window.Show();
                });
            }

            waitHandle.WaitOne();
        }
开发者ID:viciousviper,项目名称:PowerShellCloudProvider,代码行数:50,代码来源:BrowserWindow.cs

示例7: GetOriginalContentFilePath

        /// <summary>
        /// Evaluates whether the specified path is beneath the specified root content directory, and if so, attempts to
        /// determine the path of the project file which produced it. 
        /// </summary>
        /// <param name="root">The root content directory.</param>
        /// <param name="path">The path for which to find the original content path.</param>
        /// <returns>The original content path, if it was found; otherwise, <paramref name="path"/>.</returns>
        public static String GetOriginalContentFilePath(String root, String path)
        {
            Contract.Require(root, "root");
            Contract.RequireNotEmpty(path, "path");

            var entryAssembly = Assembly.GetEntryAssembly();
            if (entryAssembly == null)
                return path;

            // Produce a URI which is relative to the directory that contains our application executable.
            var uriExe = GetDirectoryUri(Path.GetDirectoryName(entryAssembly.Location));
            var uriRoot = new Uri(uriExe, root);
            var uriPathAbs = new Uri(Path.GetFullPath(path), UriKind.Absolute);

            if (!uriRoot.IsBaseOf(uriPathAbs))
                return path;            

            var uriPathRel = uriExe.MakeRelativeUri(uriPathAbs);

            // Get out of "Debug" (or "Release", etc.)...
            var dir = new DirectoryInfo(uriExe.LocalPath);
            if (dir.Parent == null)
                return path;

            dir = dir.Parent;

            // Get out of "bin"...
            if (dir.Parent == null)
                return path;

            dir = dir.Parent;

            // If we found a valid file, return its path, otherwise return the original path.
            var uriOriginalContentDir = GetDirectoryUri(dir.FullName);
            var uriOriginalContentFile = new Uri(uriOriginalContentDir, uriPathRel);
            return File.Exists(uriOriginalContentFile.LocalPath) ? uriOriginalContentFile.LocalPath : path;
        }
开发者ID:prshreshtha,项目名称:ultraviolet,代码行数:44,代码来源:UltravioletDebugUtil.cs

示例8: IsEndpointFor

        public bool IsEndpointFor(string other)
        {
            var baseAddress = this.Uri.ToString();

            // HACK! To support Fiddler2 on Win8, localhost needs to be spelled out as localhost.fiddler, but still functions as localhost
            baseAddress = baseAddress.Replace("localhost.fiddler", "localhost");
            var baseUri = new Uri(delimit(baseAddress));

            other = delimit(other.Replace("localhost.fiddler", "localhost"));

            return baseUri.IsBaseOf(new Uri(other,UriKind.RelativeOrAbsolute));
        }
开发者ID:ranjancse26,项目名称:fhir-net-api,代码行数:12,代码来源:RestUrl.cs

示例9: GetOperationsInEntry

        /// <summary>
        /// Returns a hash set of operation imports (actions and functions) in the given entry.
        /// </summary>
        /// <param name="entry">The entry in question.</param>
        /// <param name="model">The edm model to resolve operation imports.</param>
        /// <param name="metadataDocumentUri">The metadata document uri.</param>
        /// <returns>The hash set of operation imports (actions and functions) in the given entry.</returns>
        private static HashSet<IEdmOperation> GetOperationsInEntry(ODataEntry entry, IEdmModel model, Uri metadataDocumentUri)
        {
            Debug.Assert(entry != null, "entry != null");
            Debug.Assert(model != null, "model != null");
            Debug.Assert(metadataDocumentUri != null && metadataDocumentUri.IsAbsoluteUri, "metadataDocumentUri != null && metadataDocumentUri.IsAbsoluteUri");

            HashSet<IEdmOperation> edmOperationImportsInEntry = new HashSet<IEdmOperation>(EqualityComparer<IEdmOperation>.Default);
            IEnumerable<ODataOperation> operations = ODataUtilsInternal.ConcatEnumerables((IEnumerable<ODataOperation>)entry.NonComputedActions, (IEnumerable<ODataOperation>)entry.NonComputedFunctions);
            if (operations != null)
            {
                foreach (ODataOperation operation in operations)
                {
                    Debug.Assert(operation.Metadata != null, "operation.Metadata != null");
                    string operationMetadataString = UriUtils.UriToString(operation.Metadata);
                    Debug.Assert(
                        ODataJsonLightUtils.IsMetadataReferenceProperty(operationMetadataString),
                        "ODataJsonLightUtils.IsMetadataReferenceProperty(operationMetadataString)");
                    Debug.Assert(
                        operationMetadataString[0] == ODataConstants.ContextUriFragmentIndicator || metadataDocumentUri.IsBaseOf(operation.Metadata),
                        "operationMetadataString[0] == JsonLightConstants.ContextUriFragmentIndicator || metadataDocumentUri.IsBaseOf(operation.Metadata)");

                    string fullyQualifiedOperationName = ODataJsonLightUtils.GetUriFragmentFromMetadataReferencePropertyName(metadataDocumentUri, operationMetadataString);
                    IEnumerable<IEdmOperation> edmOperations = model.ResolveOperations(fullyQualifiedOperationName);
                    if (edmOperations != null)
                    {
                        foreach (IEdmOperation edmOperation in edmOperations)
                        {
                            edmOperationImportsInEntry.Add(edmOperation);
                        }
                    }
                }
            }

            return edmOperationImportsInEntry;
        }
开发者ID:larsenjo,项目名称:odata.net,代码行数:42,代码来源:ODataMissingOperationGenerator.cs

示例10: GetGraph

        public static WebGraph GetGraph(Uri urlRoot)
        {
            var graph = new WebGraph();
            var queue = new Queue<Uri>();
            var allSiteUrls = new HashSet<Uri>();

            queue.Enqueue(urlRoot);
            allSiteUrls.Add(urlRoot);

            while (queue.Count > 0)
            {
                Uri url = queue.Dequeue();

                HttpWebRequest oReq = (HttpWebRequest)WebRequest.Create(url);
                oReq.UserAgent = @"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5";

                var httpResponse = (HttpWebResponse)oReq.GetResponse();

                WebPage result;

                if (httpResponse.ContentType.StartsWith("text/html", StringComparison.InvariantCultureIgnoreCase))
                {
                    var htmlDocument = new HtmlDocument();
                    try
                    {
                        var resultStream = httpResponse.GetResponseStream();
                        htmlDocument.Load(resultStream); // The HtmlAgilityPack
                        result = new Internal() { Url = url, HtmlDocument = htmlDocument };
                    }
                    catch (WebException ex)
                    {
                        result = new WebPage.Error() { Url = url, Exception = ex };
                    }
                    catch (Exception ex)
                    {
                        ex.Data.Add("Url", url);
                        throw;
                    }

                    string vertexUrl = url.ToString().Replace(urlRoot.ToString(), "/").Replace("//", "/");
                    WebVertex v1 = graph.Vertices.SingleOrDefault(v => v.Url == vertexUrl);
                    if (v1 == null)
                    {
                        v1 = new WebVertex(vertexUrl);
                        graph.AddVertex(v1);
                    }

                    var links = htmlDocument.DocumentNode.SelectNodes(@"//a[@href]");
                    if (links != null)
                    {
                        foreach (HtmlNode link in links)
                        {
                            HtmlAttribute att = link.Attributes["href"];
                            if (att == null) continue;
                            string href = att.Value;
                            if (href.StartsWith("javascript", StringComparison.InvariantCultureIgnoreCase)) continue; // ignore javascript on buttons using a tags

                            Uri urlNext = new Uri(href, UriKind.RelativeOrAbsolute);
                            Uri urlNext2 = new Uri(href, UriKind.RelativeOrAbsolute);

                            // Make it absolute if it's relative
                            if (!urlNext.IsAbsoluteUri)
                            {
                                urlNext = new Uri(Path.Combine(urlRoot.AbsoluteUri, urlNext.ToString()));
                            }

                            if (!allSiteUrls.Contains(urlNext))
                            {
                                allSiteUrls.Add(urlNext); // keep track of every page we've handed off

                                if (urlRoot.IsBaseOf(urlNext))
                                {
                                    queue.Enqueue(urlNext);
                                }

                                string vertexUrl2 = urlNext2.ToString();
                                if (!vertexUrl2.StartsWith("http://") && !vertexUrl2.StartsWith("/"))
                                {
                                    vertexUrl2 = "/" + vertexUrl2;
                                }

                                WebVertex v2 = graph.Vertices.SingleOrDefault(v => v.Url == vertexUrl2);
                                if (v2 == null)
                                {
                                    v2 = new WebVertex(vertexUrl2);
                                    graph.AddVertex(v2);
                                }
                                graph.AddEdge(new WebEdge(v1, v2));
                            }
                        }
                    }
                }
            }

            return graph;
        }
开发者ID:piotrosz,项目名称:WebSiteGraph,代码行数:96,代码来源:WebsiteCrawler.cs

示例11: workerCrawler_DoWork

        void workerCrawler_DoWork(ref int progress,
           ref string result, ref List<string> array, params object[] args)
        {
            array = new List<string>();
            List<string> invalidLinks = new List<string>();
            // Get the value which passed to this operation.

            string urlToCheck = string.Empty;
            Uri startingUri = new Uri(args[0].ToString());

            result = "Crawling Links started.....";
            Thread.Sleep(100);
            var queue = new Queue<Uri>();

            queue.Enqueue(startingUri);
            array.Add(startingUri.ToString());

            //get the base url
            Uri uri = new Uri(startingUri.ToString());
            string baseUrl = uri.GetLeftPart(UriPartial.Authority);
            string hostName = uri.Host;

            string Rstring;

            #region queue
            while (queue.Count > 0)
            {
                string sUrl = queue.Dequeue().ToString();
                try
                {
                    string html = new WebClient().DownloadString(sUrl);

                    //if html file is empty if (html.Length == 0) { continue; }

                    MatchCollection matches = Regex.Matches(html, "href[ ]*=[ ]*['|\"][^\"'\r\n]*['|\"]");
                    //MatchCollection matches = Regex.Matches(html, "(?<=<a\\s*?href=(?:'|\"))[^'\"]*?(?=(?:'|\"))");
                    foreach (Match match in matches)
                    {
                        string value = match.Value;
                        value = Regex.Replace(value, "(href[ ]*=[ ]*')|(href[ ]*=[ ]*\")", string.Empty);
                        if (value.EndsWith("\"") || value.EndsWith("'"))
                            value = value.Remove(value.Length - 1, 1);
                        if (!Regex.Match(value, @"\((.*)\)").Success)
                        {
                            try
                            {
                                Uri tempUrl = new Uri(value, UriKind.RelativeOrAbsolute);
                                if (startingUri.IsBaseOf(tempUrl)) //If URL of that site
                                {
                                    if (!value.Contains("http:"))
                                    {
                                        Uri baseUri = new Uri(startingUri.ToString());
                                        Uri absoluteUri = new Uri(baseUri, value);
                                        value = absoluteUri.ToString();
                                    }
                                    //}
                                    //Uri urlNext = new Uri(value, UriKind.RelativeOrAbsolute);
                                    if (array.Contains(value)) continue;
                                    if (invalidLinks.Contains(value)) continue;

                                    //Discard following types of files
                                    Regex invalidType = new Regex(@"(css|jpg|gif|pdf|doc|docx|ppt|pptx|js|png|ico|zip|xls|txt|exe)");
                                    Match matchResult = invalidType.Match(value);
                                    if (!matchResult.Success)
                                    {
                                        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(value);
                                        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                                        {
                                            if (response.StatusCode == HttpStatusCode.OK)
                                            {
                                                queue.Enqueue(new Uri(value));
                                                array.Add(value);
                                                result = "Link found: " + value;
                                                Thread.Sleep(100);
                                                urlNum++;
                                            }
                                            else
                                            {
                                                result = response.StatusDescription;
                                                invalidLinks.Add(value);
                                            }
                                        }

                                        Session["linksCrawled"] = array;
                                    }

                                    /*
                                        var thread = new Thread(ProcessWebRequests);
                                        threadList.Add(thread);
                                        thread.Start();
                                    */
                                    //ThreadFunction(value);
                                }

                            }

                            catch (Exception)//UriFormatException
                            {
                                result = "Invalid Uri";
                            }
//.........这里部分代码省略.........
开发者ID:shubra-deb,项目名称:Web-Application-Vulnerabilities-Detection-System,代码行数:101,代码来源:Default.aspx.cs

示例12: IsBaseOf

 internal static bool IsBaseOf(Uri baseUriWithSlash, Uri requestUri)
 {
     return baseUriWithSlash.IsBaseOf(requestUri);
 }
开发者ID:nickchal,项目名称:pash,代码行数:4,代码来源:UriUtil.cs

示例13: IsLink

        public static bool IsLink(this string url,
            Uri baseUri, LinkKind kind, UriFilter filter = UriFilter.None)
        {
            Contract.Requires(baseUri.IsBaseUri());

            if (string.IsNullOrWhiteSpace(url))
                return false;

            url = url.Trim().ToLower();

            if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))
                return false;

            if (url.StartsWith("#"))
                return false;

            Uri uri;

            if (!Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out uri))
                return false;

            if (!uri.IsAbsoluteUri)
            {
                if (!Uri.TryCreate(baseUri, uri, out uri))
                    return false;
            }

            if (uri.Scheme != "http")
                return false;

            switch (filter)
            {
                case UriFilter.LocalPath:
                    if (!baseUri.IsBaseOf(uri))
                        return false;
                    break;
                case UriFilter.Authority:
                    if (uri.Authority != baseUri.Authority)
                        return false;
                    break;
            }

            if (kind == LinkKind.HTML)
                return true;

            if (!string.IsNullOrWhiteSpace(uri.Query))
                return false;

            string localPath;

            try
            {
                localPath = Path.GetFileName(uri.LocalPath);
            }
            catch
            {
                return false;
            }

            switch (Path.GetExtension(localPath))
            {
                case ".jpg":
                case ".jpeg":
                case ".png":
                case ".gif":
                case ".bmp":
                case ".tiff":
                    return true;
                default:
                    return false;
            }
        }
开发者ID:squideyes,项目名称:Gulp,代码行数:72,代码来源:Extenders.cs

示例14: Ldapx_Methods

		public void Ldapx_Methods ()
		{
			Uri uri = new Uri ("ldapx://www.mono-project.com/");
			Assert.AreEqual (String.Empty, uri.GetComponents (UriComponents.Path, UriFormat.SafeUnescaped), "GetComponents");
			Assert.IsTrue (uri.IsBaseOf (uri), "IsBaseOf");
			Assert.IsTrue (uri.IsWellFormedOriginalString (), "IsWellFormedOriginalString");
			// ??? our parser doesn't seems to be called :(
		}
开发者ID:calumjiao,项目名称:Mono-Class-Libraries,代码行数:8,代码来源:LdapStyleUriParserTest.cs

示例15: GetSourceFiles

        private IEnumerable<KeyValuePair<string, string>> GetSourceFiles(string pdbFile, string toolPath)
        {
            var projectBaseUrl = new Uri (Path.GetFullPath (ProjectBaseDirectory + "\\"));

              int exitCode;
              string extractedCommandOutput = Execute (Path.Combine (toolPath, "srctool.exe"), "-r " + pdbFile, true, out exitCode);

              using (var reader = new StringReader (extractedCommandOutput))
              {
            while (true)
            {
              var line = reader.ReadLine();
              if (line == null)
            yield break;

              if (string.IsNullOrWhiteSpace (line))
            continue;

              // last line is srctool.exe summary.
              Uri sourceFileUrl;
              if (!Uri.TryCreate (line, UriKind.Absolute, out sourceFileUrl))
            continue;

              if (!projectBaseUrl.IsBaseOf (sourceFileUrl))
            continue;

              var relativeSourceFileUrl = projectBaseUrl.MakeRelativeUri (sourceFileUrl);
              yield return new KeyValuePair<string, string> (line, relativeSourceFileUrl.ToString());
            }
              }
        }
开发者ID:re-motion,项目名称:BuildTools,代码行数:31,代码来源:InsertSourceLinks.cs


注:本文中的System.Uri.IsBaseOf方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。