GetComponents() public method

public GetComponents ( UriComponents components, UriFormat format ) : string
components UriComponents
format UriFormat
return string
        public override Stream GetFileStream(Uri path)
        {
            string modFile = path.GetComponents(UriComponents.Host, UriFormat.UriEscaped);
            string filePath = path.GetComponents(UriComponents.Path, UriFormat.UriEscaped);

            return GetFileStream(directory + modFile + "/", filePath);
        }
Beispiel #2
0
		private string GetFilepath(string url)
		{
			var asUri = new Uri(url);
			string cleanUrl;
			if(asUri.Scheme != "file") {
#if UNITY_EDITOR
			cleanUrl = asUri.GetComponents(UriComponents.Path, UriFormat.Unescaped);
			// Read resources from the project folder
			var uiResources = PlayerPrefs.GetString("CoherentUIResources");
			if (uiResources == string.Empty)
			{
				Debug.LogError("Missing path for Coherent UI resources. Please select path to your resources via Edit -> Project Settings -> Coherent UI -> Select UI Folder");
			}
			cleanUrl = cleanUrl.Insert(0, uiResources + '/');
#else
			cleanUrl = asUri.GetComponents(UriComponents.Host | UriComponents.Path, UriFormat.Unescaped);
			// Read resources from the <executable>_Data folder
			cleanUrl = Application.dataPath + '/' + cleanUrl;
#endif
			}
			else {
				cleanUrl = asUri.GetComponents(UriComponents.Path, UriFormat.Unescaped);
			}
			return cleanUrl;
		}
        public override bool ExistsInPath(Uri path)
        {
            string modFile = path.GetComponents(UriComponents.Host, UriFormat.UriEscaped);
            string filePath = path.GetComponents(UriComponents.Path, UriFormat.UriEscaped);

            return ExistsInPath(directory + modFile + "/", filePath);
        }
		private string GetFilepath(string url)
		{
			var asUri = new Uri(url);
			string cleanUrl;
			if(asUri.Scheme != "file") {
#if UNITY_EDITOR
			cleanUrl = asUri.GetComponents(UriComponents.Path, UriFormat.Unescaped);
			// Read resources from the project folder
			var uiResources = PlayerPrefs.GetString("CoherentUIResources");
			if (uiResources == string.Empty)
			{
				Debug.LogError("Missing path for Coherent UI resources. Please select path to your resources via Edit -> Project Settings -> Coherent UI -> Select UI Folder");
				// Try to fall back to the default location
				uiResources = Path.Combine(Path.Combine(Application.dataPath, "WebPlayerTemplates"), "uiresources");
				Debug.LogWarning("Falling back to the default location of the UI Resources in the Unity Editor: " + uiResources);
                PlayerPrefs.SetString("CoherentUIResources", "WebPlayerTemplates/uiresources");
			} else {
				uiResources = Path.Combine(Application.dataPath, uiResources);
			}
			cleanUrl = cleanUrl.Insert(0, uiResources + '/');
#else
			cleanUrl = asUri.GetComponents(UriComponents.Host | UriComponents.Path, UriFormat.Unescaped);
			// Read resources from the <executable>_Data folder
			cleanUrl = Application.dataPath + '/' + cleanUrl;
#endif
			}
			else {
				cleanUrl = asUri.GetComponents(UriComponents.Path, UriFormat.Unescaped);
			}
			return cleanUrl;
		}
Beispiel #5
0
        static string GenerateSignature(string consumerSecret, Uri uri, HttpMethod method, Token token, IEnumerable<KeyValuePair<string, string>> parameters)
        {
            if (ComputeHash == null)
            {
                throw new InvalidOperationException("ComputeHash is null, must initialize before call OAuthUtility.HashFunction = /* your computeHash code */ at once.");
            }

            var hmacKeyBase = consumerSecret.UrlEncode() + "&" + ((token == null) ? "" : token.Secret).UrlEncode();

            // escaped => unescaped[]
            var queryParams = Utility.ParseQueryString(uri.GetComponents(UriComponents.Query | UriComponents.KeepDelimiter, UriFormat.UriEscaped));

            var stringParameter = parameters
                .Where(x => x.Key.ToLower() != "realm")
                .Concat(queryParams)
                .Select(p => new { Key = p.Key.UrlEncode(), Value = p.Value.UrlEncode() })
                .OrderBy(p => p.Key, StringComparer.Ordinal)
                .ThenBy(p => p.Value, StringComparer.Ordinal)
                .Select(p => p.Key + "=" + p.Value)
                .ToString("&");
            var signatureBase = method.ToString() +
                "&" + uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped).UrlEncode() +
                "&" + stringParameter.UrlEncode();

            var hash = ComputeHash(Encoding.UTF8.GetBytes(hmacKeyBase), Encoding.UTF8.GetBytes(signatureBase));
            return Convert.ToBase64String(hash).UrlEncode();
        }
        /// <summary>
        /// Create a HttpWebRequest using the HTTP POST method.
        /// </summary>
        /// <param name="requestUri">URI to request.</param>
        /// <param name="writeBody">Whether it should write the contents of the body.</param>
        /// <returns>HttpWebRequest for this URI.</returns>
        private static HttpWebRequest CreatePostRequest(Uri requestUri, bool writeBody)
        {
            var uriWithoutQuery = new Uri(requestUri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped));
            var postRequest = WebRequest.CreateHttp(uriWithoutQuery);
            postRequest.Method = "POST";
            
            var bodyWithQuery = requestUri.GetComponents(UriComponents.Query, UriFormat.UriEscaped);
            var bodyBytes = Encoding.UTF8.GetBytes(bodyWithQuery);
#if !WINDOWS_PHONE_APP
            postRequest.ContentLength = bodyBytes.Length;
#endif

            if (writeBody)
            {
#if WINDOWS_PHONE_APP
                var stream = postRequest.GetRequestStreamAsync().Result;
#else
                var stream = postRequest.GetRequestStream();
#endif
                stream.Write(bodyBytes, 0, bodyBytes.Length);

#if WINDOWS_PHONE_APP
                stream.Flush();
                stream.Dispose();
#else
                stream.Close();      
#endif
            }

            return postRequest;
        }
        public static Uri BindUri(this ISession session, Uri url, object parameters = null)
        {
            Uri baseUri = new Uri(url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped));
              UriTemplate template = new UriTemplate(url.GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped));

              return BindTemplate(baseUri, template, parameters);
        }
Beispiel #8
0
        /// <summary>
        /// Creates the HttpRequestMessage for a URI taking into consideration the length.
        /// For URIs over 2000 bytes it will be a GET otherwise it will become a POST
        /// with the query payload moved to the POST body.
        /// </summary>
        /// <param name="uri">URI to request.</param>
        /// <returns>HttpRequestMessage for this URI.</returns>
        internal static HttpRequestMessage CreateRequest(Uri uri)
        {
            if (!uri.ShouldUsePostForRequest())
                return new HttpRequestMessage(HttpMethod.Get, uri);

            var uriWithoutQuery = new Uri(uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped));
            return new HttpRequestMessage(HttpMethod.Post, uriWithoutQuery) { Content = new StringContent(uri.GetComponents(UriComponents.Query, UriFormat.UriEscaped)) };
        }
Beispiel #9
0
        /// <summary>
        /// Resolve absolute string URI template and create request with implicit session.
        /// </summary>
        /// <param name="url"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static Request Bind(this string url, object parameters = null)
        {
            Condition.Requires(url, "url").IsNotNull();

              Uri uri = new Uri(url);
              Uri baseUri = new Uri(uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped));
              UriTemplate template = new UriTemplate(uri.GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped));

              Uri boundUrl = BindTemplate(baseUri, template, parameters);
              return new Request(boundUrl);
        }
        /// <summary>
        /// Creates a new factory parameter by splitting the specified service URI into ServerUrl and BasePath
        /// </summary>
        public FactoryParameters(Uri serviceUri)
        {
            serviceUri.ThrowIfNull("serviceUri");

            // Retrieve Scheme and Host
            ServerUrl = serviceUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped);
            ServerUrl.ThrowIfNullOrEmpty("ServerUrl");

            // Retrieve the remaining right part
            BasePath = serviceUri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped);
            ServerUrl.ThrowIfNullOrEmpty("BasePath");
        }
Beispiel #11
0
 public async Task<ImageInfo[]> GetImages(Match match)
 {
     var id = match.Groups[1].Value;
     var uri = new Uri(
         match.Groups[2].Success
         ? match.Value
         : await this._memoryCache.GetOrSet("gyazo-" + id, () => this.Fetch(id)).ConfigureAwait(false)
     );
     var full = uri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped);
     var thumb = uri.GetComponents(UriComponents.SchemeAndServer, UriFormat.UriEscaped)
         + "/thumb/180" + uri.AbsolutePath;
     return new[] { new ImageInfo(full, full, thumb) };
 }
Beispiel #12
0
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            FormMain f = new FormMain();
            f.Text += " by chall3ng3r.com - v" + Application.ProductVersion;

            foreach (string s in args)
            {
                try
                {
                    // make http URI
                    Uri uri = new Uri(s);

                    string strURL = "http://";
                    strURL += uri.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped);
                    strURL += "/" + uri.GetComponents(UriComponents.Path, UriFormat.UriEscaped);

                    // window size from querystring
                    NameValueCollection queryVars = ParseQueryString(uri.GetComponents(UriComponents.Query, UriFormat.Unescaped));
                    string size = queryVars.Get("size");

                    if(!string.IsNullOrEmpty(size))
                    {
                        // maximize
                        if (size.ToLower() == "fullscreen")
                        {
                            f.WindowState = FormWindowState.Maximized;
                        }
                        // resize window to specified width,height
                        else
                        {
                            int w = Convert.ToInt32(size.Split(',')[0]);
                            int h = Convert.ToInt32(size.Split(',')[1]);

                            f.Width = w;
                            f.Height = h;
                        }
                    }

                    f.initUnity(strURL);
                }
                catch (Exception exp)
                {
                    MessageBox.Show(exp.Message);
                }
            }

            Application.Run(f);
        }
        public static string ChangeUrlCountryCodePart(Uri uri, Language language)
        {
            var path = uri.GetComponents(UriComponents.Path, UriFormat.Unescaped);

            string pathCountryCode;
            GetPathCountryCodeParts(path, out pathCountryCode);
            if (LanguageMappingHelper.CountryCodeIsSupported(pathCountryCode))
            {
                path = path.Substring(2);
                if (path == String.Empty)
                    path = "/";
            }

            var countryCode = LanguageMappingHelper.GetCountryCodeByLanguage(language);

            var uriBuilder = new UriBuilder(uri);
            if (path == String.Empty)
                uriBuilder.Path = countryCode;
            else
            {
                if (!path.StartsWith("/"))
                    path = "/" + path;
                uriBuilder.Path = String.Format("{0}{1}", countryCode, path);
            }

            return uriBuilder.Uri.ToString();
        }
        public void RepeatsQueryInResponse()
        {
            var uri = new Uri(new Application().Url(), "/parrot?hello");
            var expectedResponse = uri.GetComponents(UriComponents.Query,UriFormat.UriEscaped);

            Assert.That(new HttpLessWebSite(_parrot).Response(uri).Body, Is.EqualTo(expectedResponse));
        }
        /// <summary>
        /// Makes the safe folder location.
        /// </summary>
        /// <param name="location">
        /// The location.
        /// </param>
        /// <returns>
        /// A <see cref="Uri"/> value.
        /// </returns>
        private Uri MakeSafeFolderLocation(Uri location)
        {
            var path = location.GetComponents(UriComponents.Path, CompareFormat);

            if (string.IsNullOrEmpty(path))
            {
                return location;
            }

            if (path.EndsWith("/", StringComparison.OrdinalIgnoreCase))
            {
                return location;
            }

            // Check for a file name
            var folderIndex = path.LastIndexOf("/", StringComparison.OrdinalIgnoreCase);

            if (folderIndex > -1)
            {
                var finalPart = path.Substring(folderIndex + 1);

                if (finalPart.IndexOf(".", StringComparison.OrdinalIgnoreCase) > -1)
                {
                    // This looks like a file so this location should not be converted
                    return location;
                }
            }

            var originalLocation = location.ToString();
            var updatedLocation = originalLocation.Replace(path, path + "/");

            return new Uri(updatedLocation);
        }
Beispiel #16
0
        /// <summary>
        /// Create a HttpWebRequest using the HTTP POST method.
        /// </summary>
        /// <param name="requestUri">URI to request.</param>
        /// <param name="writeBody">Whether it should write the contents of the body.</param>
        /// <returns>HttpWebRequest for this URI.</returns>
        private static HttpWebRequest CreatePostRequest(Uri requestUri, bool writeBody)
        {
            var uriWithoutQuery = new Uri(requestUri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.Unescaped));

            //LC - Version adjust
            //var postRequest = WebRequest.CreateHttp(uriWithoutQuery);
            var postRequest = WebRequest.Create(uriWithoutQuery);

            postRequest.Method = "POST";
            
            var bodyWithQuery = requestUri.GetComponents(UriComponents.Query, UriFormat.UriEscaped);
            var bodyBytes = Encoding.UTF8.GetBytes(bodyWithQuery);

            postRequest.ContentLength = bodyBytes.Length;

            if (writeBody)
            {
                var stream = postRequest.GetRequestStream();
                stream.Write(bodyBytes, 0, bodyBytes.Length);
                stream.Close();
            }

            //LC: Add explicit cast
            return (System.Net.HttpWebRequest)postRequest;
        }
Beispiel #17
0
        internal static string GetNameFromAtomLinkRelationAttribute(string value)
        {
            string name = null;
            if (!string.IsNullOrEmpty(value))
            {
                Uri uri = null;
                try
                {
                    uri = new Uri(value, UriKind.RelativeOrAbsolute);
                }
                catch (UriFormatException)
                {
                }

                if ((null != uri) && uri.IsAbsoluteUri)
                {
                    string unescaped = uri.GetComponents(UriComponents.AbsoluteUri, UriFormat.SafeUnescaped);
                    if (unescaped.StartsWith(XmlConstants.DataWebRelatedNamespace, StringComparison.Ordinal))
                    {
                        name = unescaped.Substring(XmlConstants.DataWebRelatedNamespace.Length);
                    }
                }
            }

            return name;
        }
        // Send a HTTP/1.1 upgrade request, expect a 101 response.
        // TODO: Failing a 101 response, we could fall back to HTTP/1.1, but
        // that is currently out of scope for this project.
        public static async Task<HandshakeResponse> DoHandshakeAsync(Stream stream, Uri uri, string method, string version,
            IEnumerable<KeyValuePair<string, IEnumerable<string>>> headers, CancellationToken cancel)
        {
            // TODO: Verify session state, handshake needed.

            // Build the request
            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("{0} {1} {2}\r\n", method, uri.PathAndQuery, version);
            builder.AppendFormat("Host: {0}\r\n", uri.GetComponents(UriComponents.Host | UriComponents.StrongPort, UriFormat.UriEscaped));
            builder.Append("Connection: Upgrade\r\n");
            builder.Append("Upgrade: HTTP/2.0\r\n");
            foreach (KeyValuePair<string, IEnumerable<string>> headerPair in headers)
            {
                foreach (string value in headerPair.Value)
                {
                    builder.AppendFormat("{0}: {1}\r\n", headerPair.Key, value);
                }
            }
            builder.Append("\r\n");

            byte[] requestBytes = Encoding.ASCII.GetBytes(builder.ToString());
            await stream.WriteAsync(requestBytes, 0, requestBytes.Length, cancel);

            // Read response headers
            return await Read11ResponseHeadersAsync(stream, cancel);
        }
		public void ForceHostToUseWww()
		{
			var target = CreateRuleSet(@"
RewriteCond %{HTTP_HOST} !^(www).*$ [NC]
RewriteRule ^(.*)$ http://www.%1$1 [R=301]");

			var url = new Uri("http://somesite.com/pass");
			var context = HttpHelpers.MockHttpContext(url);
			context.Request.SetServerVariables(new Dictionary<string, string> { 
				{ "HTTP_HOST", url.GetComponents(UriComponents.Host, UriFormat.SafeUnescaped) } 
			});

			string expected = "http://www.somesite.com/pass";
			Uri resultUrl = target.RunRules(context, url);
			string result = context.Response.RedirectLocation;

			Assert.IsNull(resultUrl);
			Assert.AreEqual(expected, result);

			url = new Uri("http://www.somesite.com/fail");
			context = HttpHelpers.MockHttpContext(url);
			context.Request.SetServerVariables(new Dictionary<string, string> { 
				{ "HTTP_HOST", url.GetComponents(UriComponents.Host, UriFormat.SafeUnescaped) } 
			});

			resultUrl = target.RunRules(context, url);
			result = context.Response.RedirectLocation;

			Assert.IsNull(resultUrl);
			Assert.IsNull(result);
		}
        /// <summary>
        /// Takes the arguments in the form of a <see cref="Uri"/> and
        /// converts them to a <see cref="VersionControlArguments"/>.
        /// </summary>
        /// <param name="uri">The URI specifying the arguments.</param>
        /// <returns></returns>
        public static VersionControlArguments FromUri(Uri uri)
        {
            if (uri == null) throw new ArgumentNullException("uri");

            var args = new VersionControlArguments
            {
                Provider = uri.Scheme,
                Server = uri.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped)
            };

            if (!uri.UserInfo.IsNullOrEmpty())
            {
                var parts = uri.UserInfo.Split(new[] { ':' });
                var userName = parts[0];
                var password = parts[1];

                args.Credentials = new NetworkCredential(userName, password);
            }

            // The project name is the first part of the path
            args.Project = Uri.UnescapeDataString(uri.Segments[1]).Trim('/', '\\');

            // Query string arguments
            var queryStringArgs = ParseQueryStringArgs(uri);

            if( queryStringArgs.ContainsKey("label")) args.Label = Uri.UnescapeDataString(queryStringArgs["label"]);
            if (queryStringArgs.ContainsKey("destinationpath")) args.DestinationPath = Uri.UnescapeDataString(queryStringArgs["destinationpath"]);

            return args;
        }
Beispiel #21
0
        internal static bool UriEquals(System.Uri u1, System.Uri u2, bool ignoreCase, bool includeHostInComparison, bool includePortInComparison)
        {
            if (u1.Equals(u2))
            {
                return(true);
            }
            if (u1.Scheme != u2.Scheme)
            {
                return(false);
            }
            if (includePortInComparison && (u1.Port != u2.Port))
            {
                return(false);
            }
            if (includeHostInComparison && (string.Compare(u1.Host, u2.Host, StringComparison.OrdinalIgnoreCase) != 0))
            {
                return(false);
            }
            if (string.Compare(u1.AbsolutePath, u2.AbsolutePath, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0)
            {
                return(true);
            }
            string components = u1.GetComponents(UriComponents.Path, UriFormat.Unescaped);
            string strB       = u2.GetComponents(UriComponents.Path, UriFormat.Unescaped);
            int    length     = ((components.Length > 0) && (components[components.Length - 1] == '/')) ? (components.Length - 1) : components.Length;
            int    num2       = ((strB.Length > 0) && (strB[strB.Length - 1] == '/')) ? (strB.Length - 1) : strB.Length;

            if (num2 != length)
            {
                return(false);
            }
            return(string.Compare(components, 0, strB, 0, length, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) == 0);
        }
 /// <summary>
 /// Extract the query string parameters from a URI into a dictionary of keys and values.
 /// </summary>
 /// <param name="uri">URI to extract the parameters from.</param>
 /// <returns>Dictionary of keys and values representing the parameters.</returns>
 private static Dictionary<string, string> ExtractParameters(Uri uri)
 {
     return uri.GetComponents(UriComponents.Query, UriFormat.SafeUnescaped)
         .Split('&')
         .Select(kv => kv.Split('='))
         .ToDictionary(k => k[0], v => Uri.UnescapeDataString(v[1]));
 }
        public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
        {
            if (absoluteUri == null) throw new ArgumentNullException("absoluteUri");
             if (absoluteUri.AbsolutePath.Length <= 1) throw new ArgumentException("The embedded resource name must be specified in the AbsolutePath portion of the supplied Uri.");

             string host = absoluteUri.Host;

             if (String.IsNullOrEmpty(host)) {
            host = null;
             }

             string resourceName = ((host != null) ?
            absoluteUri.GetComponents(UriComponents.Host | UriComponents.Path, UriFormat.Unescaped)
            : absoluteUri.AbsolutePath)
            .Replace("/", ".");

             Assembly assembly = null;

             NameValueCollection query = QueryStringUtil.ParseQueryString(
            (absoluteUri.Query ?? "").Replace(';', '&')
             );

             string asm = host ?? query["asm"];
             string ver = query["ver"];
             string loc = query["loc"];
             string sn = query["sn"];
             string from = query["from"];

             if (!String.IsNullOrEmpty(from)) {
            assembly = Assembly.ReflectionOnlyLoadFrom(from);

             } else if (!String.IsNullOrEmpty(asm)) {

            var longNameBuilder = new StringBuilder(asm);

            if (!String.IsNullOrEmpty(ver)) {
               longNameBuilder.Append(", Version=").Append(ver);
            }

            if (!String.IsNullOrEmpty(loc)) {
               longNameBuilder.Append(", Culture=").Append(loc);
            }

            if (!String.IsNullOrEmpty(sn)) {
               longNameBuilder.Append(", PublicKeyToken=").Append(sn);
            }

            assembly = Assembly.ReflectionOnlyLoad(longNameBuilder.ToString());

             } else if (this.DefaultAssembly != null) {
            assembly = this.DefaultAssembly;
             }

             if (assembly != null) {
            return assembly.GetManifestResourceStream(resourceName);
             }

             throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, "Could not determine the assembly of the resource identified by \"{0}\".", absoluteUri));
        }
Beispiel #24
0
 private static string GetBaseAddress()
 {
     var uri = new Uri(ConfigurationManager.AppSettings["situatorWebApiUrl"], UriKind.Absolute);
     //remove segments
     var noLastSegment = uri.GetComponents(UriComponents.SchemeAndServer,
         UriFormat.SafeUnescaped);
     return noLastSegment;
 }
Beispiel #25
0
 public static string GetBoardName(string URL)
 {
     Uri test = new Uri(URL);
     String threadURL = test.GetComponents(UriComponents.HttpRequestUrl, UriFormat.SafeUnescaped);
     int startindex = threadURL.IndexOf("boards.4chan.org") + 16;
     int endindex = threadURL.IndexOf('/', startindex + 1);
     return threadURL.Substring(startindex, (endindex - startindex) + 1);
 }
        private Uri GetAbsoluteUri(Uri uriFromCaller)
        {
            UriBuilder builder = new UriBuilder(Uri.UriSchemeHttps, uriFromCaller.Host);
            builder.Path = uriFromCaller.GetComponents(UriComponents.Path, UriFormat.Unescaped);

            string query = uriFromCaller.GetComponents(UriComponents.Query, UriFormat.UriEscaped);
            if (query.Length > 0)
            {
                string uriWithoutQuery = builder.Uri.AbsoluteUri;
                string absoluteUri = string.Format("{0}?{1}", uriWithoutQuery, query);
                return new Uri(absoluteUri, UriKind.Absolute);
            }
            else
            {
                return builder.Uri;
            }
        }
 private static string GetNormalizedUrl(Uri url)
 {
     return url.GetComponents(
         UriComponents.HostAndPort |
         UriComponents.UserInfo |
         UriComponents.Path,
         UriFormat.SafeUnescaped);
 }
 private static void BuildRequestFromUri(OwinRequest request, Uri uri)
 {
     request.Host = uri.GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped);
     request.PathBase = String.Empty;
     request.Path = uri.LocalPath;
     request.Scheme = uri.Scheme;
     request.QueryString = uri.Query.Length > 0 ? uri.Query.Substring(1) : String.Empty;
 }
		static ICredentials GetExistingCredentials (Uri uri, CredentialType credentialType)
		{
			var rootUri = new Uri (uri.GetComponents (UriComponents.SchemeAndServer, UriFormat.SafeUnescaped));
			var existing =
				PasswordService.GetWebUserNameAndPassword (uri) ??
				PasswordService.GetWebUserNameAndPassword (rootUri);

			return existing != null ? new NetworkCredential (existing.Item1, existing.Item2) : null;
		}
Beispiel #30
0
        public static bool IsCrossDomain(Uri requestUri)
        {
            if (!requestUri.IsAbsoluteUri)
                return false;

            string requestDomain = requestUri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Port, UriFormat.Unescaped);
            string currentDomain = HtmlPage.Document.DocumentUri.GetComponents(UriComponents.SchemeAndServer | UriComponents.Port, UriFormat.Unescaped);
            return !requestDomain.Equals(currentDomain);
        }
Beispiel #31
0
 public static string ToFilePath(Uri uri)
 {
     if (!uri.IsAbsoluteUri)
     {
         return uri.ToString();
     }
     else if (!uri.IsFile)
     {
         throw new ArgumentException("Uri is not a local or UNC file.", "uri");
     }
     else if (uri.IsUnc)
     {
         return String.Format("//{0}/{1}", uri.Host, uri.GetComponents(UriComponents.Path, UriFormat.Unescaped));
     }
     else
     {
         return uri.GetComponents(UriComponents.Path, UriFormat.Unescaped);
     }
 }
        /// <summary>
        /// Extract the base URL from a much larger without the scheme, so http//localhost:4200/api/config would return localhost:4200
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string BaseUrlNoScheme(this string url)
        {
            if (url == null)
            {
                return(null);
            }
            System.Uri uri      = new System.Uri(url);
            int        port     = uri.Port;
            string     host     = uri.Host;
            string     protocol = uri.Scheme;

            if (port == 80)
            {
                return(uri.GetComponents(UriComponents.Host, UriFormat.UriEscaped));
            }
            else
            {
                return(uri.GetComponents(UriComponents.HostAndPort, UriFormat.UriEscaped));
            }
        }
Beispiel #33
0
        /// <summary>
        /// Returns the filename component of the Uri.
        /// </summary>
        /// <param name="uri">A URI in the form 't4://extension/{id}/{relative-path-to-t4-file}'</param>
        public static string ParseFileName(System.Uri uri)
        {
            var segments = uri.GetComponents(UriComponents.Path, UriFormat.Unescaped).Split(Path.AltDirectorySeparatorChar);

            if (segments.Length < 2)
            {
                return(null);
            }

            return(segments.Last());
        }
Beispiel #34
0
        internal string GetRawUri(string uri)
        {
            try
            {
                System.Uri ri = new System.Uri(uri);
                return(ri.GetComponents(UriComponents.HttpRequestUrl, UriFormat.Unescaped));
            }
            catch (UriFormatException)
            {
            }

            return(null);
        }
Beispiel #35
0
 internal string GetRawUri()
 {
     try
     {
         if (!string.IsNullOrEmpty(Uri))
         {
             System.Uri uri = new System.Uri(Uri);
             return(uri.GetComponents(UriComponents.HttpRequestUrl, UriFormat.Unescaped));
         }
     }
     catch (UriFormatException)
     {
     }
     return(Uri);
 }
Beispiel #36
0
 static public int GetComponents(IntPtr l)
 {
     try {
         System.Uri           self = (System.Uri)checkSelf(l);
         System.UriComponents a1;
         checkEnum(l, 2, out a1);
         System.UriFormat a2;
         checkEnum(l, 3, out a2);
         var ret = self.GetComponents(a1, a2);
         pushValue(l, true);
         pushValue(l, ret);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Beispiel #37
0
 static int GetComponents(IntPtr L)
 {
     try
     {
         ToLua.CheckArgsCount(L, 3);
         System.Uri           obj  = (System.Uri)ToLua.CheckObject <System.Uri>(L, 1);
         System.UriComponents arg0 = (System.UriComponents)ToLua.CheckObject(L, 2, typeof(System.UriComponents));
         System.UriFormat     arg1 = (System.UriFormat)ToLua.CheckObject(L, 3, typeof(System.UriFormat));
         string o = obj.GetComponents(arg0, arg1);
         LuaDLL.lua_pushstring(L, o);
         return(1);
     }
     catch (Exception e)
     {
         return(LuaDLL.toluaL_exception(L, e));
     }
 }
Beispiel #38
0
        internal static int UriGetHashCode(System.Uri uri, bool includeHostInComparison, bool includePortInComparison)
        {
            UriComponents components = UriComponents.Path | UriComponents.Scheme;

            if (includePortInComparison)
            {
                components |= UriComponents.Port;
            }
            if (includeHostInComparison)
            {
                components |= UriComponents.Host;
            }
            string str = uri.GetComponents(components, UriFormat.Unescaped);

            if ((str.Length > 0) && (str[str.Length - 1] != '/'))
            {
                str = str + "/";
            }
            return(StringComparer.OrdinalIgnoreCase.GetHashCode(str));
        }
Beispiel #39
0
        public UriTemplateMatch Match(Uri baseAddress, Uri candidate)
        {
            CheckBaseAddress(baseAddress);
            if (candidate == null)
            {
                throw new ArgumentNullException("candidate");
            }

            var us = baseAddress.LocalPath;

            if (us [us.Length - 1] != '/')
            {
                baseAddress = new Uri(
                    baseAddress.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped) + '/' + baseAddress.Query,
                    baseAddress.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute
                    );
            }
            if (IgnoreTrailingSlash)
            {
                us = candidate.LocalPath;
                if (us.Length > 0 && us [us.Length - 1] != '/')
                {
                    candidate = new Uri(
                        candidate.GetComponents(UriComponents.SchemeAndServer | UriComponents.Path, UriFormat.UriEscaped) + '/' + candidate.Query,
                        candidate.IsAbsoluteUri ? UriKind.Absolute : UriKind.RelativeOrAbsolute
                        );
                }
            }

            int i = 0, c = 0;
            UriTemplateMatch m = new UriTemplateMatch();

            m.BaseUri    = baseAddress;
            m.Template   = this;
            m.RequestUri = candidate;
            var vc             = m.BoundVariables;

            string cp = baseAddress.MakeRelativeUri(new Uri(
                                                        baseAddress,
                                                        candidate.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped)
                                                        ))
                        .ToString();

            if (IgnoreTrailingSlash && cp [cp.Length - 1] == '/')
            {
                cp = cp.Substring(0, cp.Length - 1);
            }

            int tEndCp = cp.IndexOf('?');

            if (tEndCp >= 0)
            {
                cp = cp.Substring(0, tEndCp);
            }

            if (template.Length > 0 && template [0] == '/')
            {
                i++;
            }
            if (cp.Length > 0 && cp [0] == '/')
            {
                c++;
            }

            foreach (string name in path)
            {
                if (name == wild_path_name)
                {
                    vc [name] = Uri.UnescapeDataString(cp.Substring(c));                       // all remaining paths.
                    continue;
                }
                int n = StringIndexOf(template, '{' + name + '}', i);
                if (String.CompareOrdinal(cp, c, template, i, n - i) != 0)
                {
                    return(null);                    // doesn't match before current template part.
                }
                c += n - i;
                i  = n + 2 + name.Length;
                int ce = cp.IndexOf('/', c);
                if (ce < 0)
                {
                    ce = cp.Length;
                }
                string value          = cp.Substring(c, ce - c);
                string unescapedVaule = Uri.UnescapeDataString(value);
                if (value.Length == 0)
                {
                    return(null);                    // empty => mismatch
                }
                vc [name] = unescapedVaule;
                m.RelativePathSegments.Add(unescapedVaule);
                c += value.Length;
            }
            int  tEnd    = template.IndexOf('?');
            int  wildIdx = template.IndexOf('*');
            bool wild    = wildIdx >= 0;

            if (tEnd < 0)
            {
                tEnd = template.Length;
            }
            if (wild)
            {
                tEnd = Math.Max(wildIdx - 1, 0);
            }
            if (!wild && (cp.Length - c) != (tEnd - i) ||
                String.CompareOrdinal(cp, c, template, i, tEnd - i) != 0)
            {
                return(null);                // suffix doesn't match
            }
            if (wild)
            {
                c += tEnd - i;
                foreach (var pe in cp.Substring(c).Split(slashSep, StringSplitOptions.RemoveEmptyEntries))
                {
                    m.WildcardPathSegments.Add(pe);
                }
            }
            if (candidate.Query.Length == 0)
            {
                return(m);
            }


            string [] parameters = Uri.UnescapeDataString(candidate.Query.Substring(1)).Split('&');                // chop first '?'
            foreach (string parameter in parameters)
            {
                string [] pair = parameter.Split('=');
                m.QueryParameters.Add(pair [0], pair [1]);
                if (!query_params.ContainsKey(pair [0]))
                {
                    continue;
                }
                string templateName = query_params [pair [0]];
                vc.Add(templateName, pair [1]);
            }

            return(m);
        }
Beispiel #40
0
 public static string GetUriPath(Uri uri)
 {
     return(uri.GetComponents(UriComponents.KeepDelimiter | UriComponents.Path, UriFormat.Unescaped));
 }