Here are the examples of the csharp api System.Uri.TryCreate(string, System.UriKind, out System.Uri) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
628 Examples
19
View Source File : StringExtension.cs
License : MIT License
Project Creator : 3F
License : MIT License
Project Creator : 3F
public static string MakeRelativePath(this string root, string path)
{
if(String.IsNullOrWhiteSpace(root) || String.IsNullOrWhiteSpace(path)) {
return null;
}
if(!Uri.TryCreate(root.DirectoryPathFormat(), UriKind.Absolute, out Uri uriRoot)) {
return null;
}
if(!Uri.TryCreate(path, UriKind.Absolute, out Uri uriPath)) {
uriPath = new Uri(uriRoot, new Uri(path, UriKind.Relative));
}
Uri urirel = uriRoot.MakeRelativeUri(uriPath);
string ret = Uri.UnescapeDataString(urirel.IsAbsoluteUri ? urirel.LocalPath : urirel.ToString());
return ret.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
19
View Source File : Validators.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static bool ServerUrlValidator(string value)
{
try
{
Uri uri;
if (Uri.TryCreate(value, UriKind.Absolute, out uri))
{
if (uri.Scheme.Equals(UriHttpScheme, StringComparison.OrdinalIgnoreCase)
|| uri.Scheme.Equals(UriHttpsScheme, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
}
catch (Exception)
{
return false;
}
return false;
}
19
View Source File : VideoSourceConverter.cs
License : MIT License
Project Creator : adamfisher
License : MIT License
Project Creator : adamfisher
public override object ConvertFromInvariantString(string value)
{
if (value == null)
return null;
Uri result;
if (!Uri.TryCreate(value, UriKind.Absolute, out result) || result.Scheme == "file")
return VideoSource.FromFile(value);
return VideoSource.FromUri(result);
}
19
View Source File : SimpleHtmlFormatter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static string ReplaceUrlsWithLinks(string text)
{
return UrlReplacementRegex.Replace(text, match =>
{
Uri uri;
return Uri.TryCreate(match.Groups["url"].Value, UriKind.Absolute, out uri)
? @"<a href=""{0}"" rel=""nofollow"">{0}</a>".FormatWith(WebUtility.HtmlEncode(uri.ToString()))
: match.Value;
});
}
19
View Source File : UrlFilters.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static string AddQuery(string url, string parameterName, object value)
{
if (url == null)
{
return null;
}
if (string.IsNullOrWhiteSpace(parameterName))
{
return url;
}
Uri uri;
if (!Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out uri))
{
return null;
}
var inputIsAbsolute = uri.IsAbsoluteUri;
try
{
var urlBuilder = new UrlBuilder(inputIsAbsolute ? uri : new Uri(PlaceholderBaseUri, uri));
urlBuilder.QueryString.Set(parameterName, value == null ? string.Empty : value.ToString());
return inputIsAbsolute ? urlBuilder.ToString() : urlBuilder.PathWithQueryString;
}
catch
{
return url;
}
}
19
View Source File : UrlFilters.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static string Base(string url)
{
if (url == null)
{
return null;
}
Uri uri;
return Uri.TryCreate(url, UriKind.Absolute, out uri)
? uri.GetLeftPart(UriPartial.Authority)
: null;
}
19
View Source File : UrlFilters.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static string RemoveQuery(string url, string parameterName)
{
if (url == null)
{
return null;
}
if (string.IsNullOrWhiteSpace(parameterName))
{
return url;
}
Uri uri;
if (!Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out uri))
{
return null;
}
var inputIsAbsolute = uri.IsAbsoluteUri;
try
{
var urlBuilder = new UrlBuilder(inputIsAbsolute ? uri : new Uri(PlaceholderBaseUri, uri));
urlBuilder.QueryString.Remove(parameterName);
return inputIsAbsolute ? urlBuilder.ToString() : urlBuilder.PathWithQueryString;
}
catch
{
return url;
}
}
19
View Source File : CrmSiteMapProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected void AddNode(SiteMapNode node, Action<SiteMapNode> add)
{
if (!(node is CrmSiteMapNode))
{
add(node);
return;
}
Uri absoluteUri;
var encoded = false;
if (Uri.TryCreate(node.Url, UriKind.Absolute, out absoluteUri))
{
node.Url = HttpContext.Current.Server.UrlEncode(node.Url);
encoded = true;
}
add(node);
if (encoded)
{
node.Url = HttpContext.Current.Server.UrlDecode(node.Url);
}
}
19
View Source File : AuthenticationPage.xaml.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private void btnGo_Click(object sender, RoutedEventArgs e)
{
var progress = new ProgressDialog
{
replacedle = "Connect to Microsoft Dynamics CRM Server",
Indeterminate = true,
CaptionText = "Retrieving authentication settings...",
Owner = (NavigationWindow)Parent
};
var worker = new BackgroundWorker { WorkerReportsProgress = true, WorkerSupportsCancellation = true };
progress.Cancel += GetCancel(worker);
worker.DoWork += (s, args) =>
{
Uri uri;
if (Uri.TryCreate(args.Argument as string, UriKind.Absolute, out uri))
{
var config = CreateServiceConfiguration(uri);
if (config != null)
{
Dispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>
{
_connectionData.AuthenticationType = (AuthenticationTypeCode)(int)config.AuthenticationType;
_connectionData.IntegratedEnabled = config.AuthenticationType == AuthenticationProviderType.ActiveDirectory;
_connectionData.Domain = string.Empty;
_connectionData.Username = string.Empty;
_connectionData.FormPreplacedword = string.Empty;
if (config.AuthenticationType == AuthenticationProviderType.LiveId)
{
var deviceCredentials = DeviceIdManager.LoadDeviceCredentials();
if (deviceCredentials != null)
{
var deviceId = deviceCredentials.UserName.UserName ?? string.Empty;
_connectionData.DeviceId = deviceId.StartsWith(DeviceIdManager.DevicePrefix) & deviceId.Length > DeviceIdManager.MaxDeviceNameLength
? deviceId.Substring(DeviceIdManager.DevicePrefix.Length)
: deviceId;
_connectionData.DevicePreplacedword = deviceCredentials.UserName.Preplacedword ?? string.Empty;
}
}
}));
}
}
};
worker.RunWorkerCompleted += GetWorkerCompleted(progress, "Failed to retrieve authentication settings.");
worker.RunWorkerAsync(txtServerUrl.Text);
progress.ShowDialog();
}
19
View Source File : URLChecker.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
public bool Check(string url)
{
Uri uri;
return Uri.TryCreate(url, UriKind.Absolute, out uri) && (uri != null && uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps);
}
19
View Source File : Antis.cs
License : GNU General Public License v3.0
Project Creator : aelariane
License : GNU General Public License v3.0
Project Creator : aelariane
internal static bool IsValidURL(string url, out Uri uri)
{
return Uri.TryCreate(url, UriKind.Absolute, out uri) && (uri != null && uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps);
}
19
View Source File : Association_Helper.cs
License : MIT License
Project Creator : AElfProject
License : MIT License
Project Creator : AElfProject
private bool ValidateDescriptionUrlScheme(string uriString)
{
if (string.IsNullOrEmpty(uriString))
return true;
bool result = Uri.TryCreate(uriString, UriKind.Absolute, out var uriResult)
&& (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
return result;
}
19
View Source File : EntityConverters.cs
License : MIT License
Project Creator : Aiko-IT-Systems
License : MIT License
Project Creator : Aiko-IT-Systems
async Task<Optional<DiscordMessage>> IArgumentConverter<DiscordMessage>.ConvertAsync(string value, CommandContext ctx)
{
if (string.IsNullOrWhiteSpace(value))
return Optional.FromNoValue<DiscordMessage>();
var msguri = value.StartsWith("<") && value.EndsWith(">") ? value.Substring(1, value.Length - 2) : value;
ulong mid;
if (Uri.TryCreate(msguri, UriKind.Absolute, out var uri))
{
if (uri.Host != "discordapp.com" && uri.Host != "discord.com" && !uri.Host.EndsWith(".discordapp.com") && !uri.Host.EndsWith(".discord.com"))
return Optional.FromNoValue<DiscordMessage>();
var uripath = MessagePathRegex.Match(uri.AbsolutePath);
if (!uripath.Success
|| !ulong.TryParse(uripath.Groups["channel"].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var cid)
|| !ulong.TryParse(uripath.Groups["message"].Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out mid))
return Optional.FromNoValue<DiscordMessage>();
var chn = await ctx.Client.GetChannelAsync(cid).ConfigureAwait(false);
if (chn == null)
return Optional.FromNoValue<DiscordMessage>();
var msg = await chn.GetMessageAsync(mid).ConfigureAwait(false);
return msg != null ? Optional.FromValue(msg) : Optional.FromNoValue<DiscordMessage>();
}
if (ulong.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out mid))
{
var result = await ctx.Channel.GetMessageAsync(mid).ConfigureAwait(false);
return result != null ? Optional.FromValue(result) : Optional.FromNoValue<DiscordMessage>();
}
return Optional.FromNoValue<DiscordMessage>();
}
19
View Source File : WindowUrl.cs
License : GNU General Public License v3.0
Project Creator : aiportal
License : GNU General Public License v3.0
Project Creator : aiportal
public static WindowUrl Create(string url)
{
WindowUrl host = null;
Uri uri;
if (Uri.TryCreate(url, UriKind.Absolute, out uri))
{
host = new WindowUrl(uri);
}
else if (Uri.TryCreate("http://" + url, UriKind.Absolute, out uri))
{
if (uri.Host.Contains("."))
host = new WindowUrl(uri);
}
return host;
}
19
View Source File : KIpEndpoint.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
public static KIpEndpoint Parse(string value)
{
if (Uri.TryCreate(value, UriKind.Absolute, out Uri uri))
return new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port < 0 ? 0 : uri.Port);
if (Uri.TryCreate($"tcp://{value}", UriKind.Absolute, out uri))
return new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port < 0 ? 0 : uri.Port);
if (Uri.TryCreate($"tcp://[{value}]", UriKind.Absolute, out uri))
return new IPEndPoint(IPAddress.Parse(uri.Host), uri.Port < 0 ? 0 : uri.Port);
throw new FormatException("Failed to parse text to KIpEndpoint.");
}
19
View Source File : FormatValidation.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
public static bool ValidateIri(string text)
{
if (text.StartsWith("//"))
return false;
if (text.StartsWith("\\\\"))
return false;
return Uri.IsWellFormedUriString(text, UriKind.Absolute) || Uri.TryCreate(text, UriKind.Absolute, out var _);
}
19
View Source File : FormatValidation.cs
License : MIT License
Project Creator : alethic
License : MIT License
Project Creator : alethic
public static bool ValidateIriReference(string text)
{
if (text.StartsWith("\\\\"))
return false;
if (ValidateIri(text))
return true;
if (text.StartsWith("//"))
return Uri.IsWellFormedUriString("scheme:" + text, UriKind.Absolute);
if (text.StartsWith("#"))
return Uri.IsWellFormedUriString("scheme://ƒøø.ßår" + text, UriKind.Absolute);
else
return Uri.IsWellFormedUriString(text, UriKind.RelativeOrAbsolute) || Uri.TryCreate(text, UriKind.Relative, out var _);
}
19
View Source File : Validate.cs
License : MIT License
Project Creator : alfa-laboratory
License : MIT License
Project Creator : alfa-laboratory
public static bool ValidateUrl(string url)
{
return Uri.TryCreate(url, UriKind.Absolute, out _);
}
19
View Source File : Service.Steps.cs
License : MIT License
Project Creator : alfa-laboratory
License : MIT License
Project Creator : alfa-laboratory
[When(@"я вызываю веб-сервис ""(.+)"" по адресу ""(.+)"" с методом ""(.+)"", используя параметры:")]
public void SendToRestServiceWithBody(string name, string url, HTTPMethodType method, RequestDto requestDto)
{
variableController.Variables.Should().NotContainKey($"Данные по сервису с именем \"{name}\" уже существуют");
serviceController.Services.Should().NotContainKey($"Данные по сервису с именем \"{name}\" уже существуют");
url = variableController.ReplaceVariables(url);
if (requestDto.Query.Any())
{
url = url.AddQueryInURL(requestDto.Query);
}
if(!Uri.TryCreate(url, UriKind.Absolute, out _))
{
Log.Logger().LogWarning($"Url {url} is not valid.");
throw new ArgumentException($"Url {url} is not valid.");
}
var request = new RequestInfo
{
Content = requestDto.Content,
Headers = requestDto.Header,
Credential = requestDto.Credentials,
Timeout = requestDto.Timeout,
Method = webMethods[method],
Url = url
};
using var service = new WebService();
var responce = service.SendMessage(request).Result;
if (responce != null)
{
serviceController.Services.TryAdd(name, responce);
}
else
{
Log.Logger().LogInformation($"Сервис с названием \"{name}\" не добавлен. Подробности в логах");
}
}
19
View Source File : WebExtensions.cs
License : MIT License
Project Creator : aljazsim
License : MIT License
Project Creator : aljazsim
private static T ExecuteRequest<T>(this Uri uri, Func<HttpWebResponse, T> getDataFunc, byte[] data = null, string requestContentType = "text/plain", int redirectCount = 0, TimeSpan? timeout = null)
{
HttpWebRequest request;
T responseContent = default(T);
int maxRedirects = 30;
string location = "Location";
uri.CannotBeNull();
getDataFunc.CannotBeNull();
requestContentType.CannotBeNullOrEmpty();
redirectCount.MustBeGreaterThanOrEqualTo(0);
// make request
request = HttpWebRequest.Create(uri) as HttpWebRequest;
request.Method = data == null ? "GET" : "POST";
request.KeepAlive = false;
request.ContentType = requestContentType;
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
request.CookieContainer = new CookieContainer();
request.UserAgent = "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1300.0 Iron/23.0.1300.0 Safari/537.11";
request.AllowAutoRedirect = false;
request.Timeout = (int)(timeout == null ? TimeSpan.FromSeconds(10) : (TimeSpan)timeout).TotalMilliseconds;
// setup request contents
if (data != null)
{
request.ContentLength = data.Length;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(data, 0, data.Length);
}
}
// get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode == HttpStatusCode.Redirect)
{
if (redirectCount <= maxRedirects)
{
if (response.Headers.AllKeys.Contains(location) &&
response.Headers[location].IsNotNullOrEmpty())
{
if (Uri.TryCreate(response.Headers[location], UriKind.Absolute, out uri))
{
responseContent = uri.ExecuteRequest(getDataFunc, data, requestContentType, ++redirectCount);
}
}
}
}
else
{
responseContent = getDataFunc(response);
}
}
return responseContent;
}
19
View Source File : WebFileExtractor.cs
License : MIT License
Project Creator : allisterb
License : MIT License
Project Creator : allisterb
protected override StageResult Init()
{
if (Uri.TryCreate(InputFileUrl, UriKind.RelativeOrAbsolute, out Uri result))
{
InputFileUri = result;
return StageResult.SUCCESS;
}
else
{
Error("The input file Url {0} is not a valid Uri.".F(InputFileUrl));
return StageResult.INPUT_ERROR;
}
}
19
View Source File : AuthenticationController.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
[AllowAnonymous]
[HttpGet("authentication")]
public async Task<ActionResult> AuthenticateUser([FromQuery] string goTo, [FromQuery] bool dontChooseReportee)
{
if (string.IsNullOrEmpty(goTo) && HttpContext.Request.Cookies[_generalSettings.AuthnGotToCookieName] != null)
{
goTo = HttpContext.Request.Cookies[_generalSettings.AuthnGotToCookieName];
}
if (!Uri.TryCreate(goTo, UriKind.Absolute, out Uri goToUri) || !IsValidRedirectUri(goToUri.Host))
{
return Redirect($"{_generalSettings.BaseUrl}");
}
string platformReturnUrl = $"{_generalSettings.PlatformEndpoint}authentication/api/v1/authentication?goto={goTo}";
if (dontChooseReportee)
{
platformReturnUrl += "&DontChooseReportee=true";
}
string encodedGoToUrl = HttpUtility.UrlEncode(platformReturnUrl);
string sblRedirectUrl = $"{_generalSettings.SBLRedirectEndpoint}?goTo={encodedGoToUrl}";
string oidcissuer = Request.Query["iss"];
UserAuthenticationModel userAuthentication;
if (_generalSettings.EnableOidc && (!string.IsNullOrEmpty(oidcissuer) || _generalSettings.ForceOidc))
{
OidcProvider provider = GetOidcProvider(oidcissuer);
string code = Request.Query["code"];
string state = Request.Query["state"];
if (!string.IsNullOrEmpty(code))
{
if (string.IsNullOrEmpty(state))
{
return BadRequest("Missing state param");
}
HttpContext.Request.Headers.Add("X-XSRF-TOKEN", state);
try
{
await _antiforgery.ValidateRequestAsync(HttpContext);
}
catch (Exception ex)
{
_logger.LogInformation("Validateion of state failed", ex.ToString());
return BadRequest("Invalid state param");
}
OidcCodeResponse oidcCodeResponse = await _oidcProvider.GetTokens(code, provider, GetRedirectUri(provider));
JwtSecurityToken jwtSecurityToken = await ValidateAndExtractOidcToken(oidcCodeResponse.IdToken, provider.WellKnownConfigEndpoint);
userAuthentication = GetUserFromToken(jwtSecurityToken, provider);
if (!ValidateNonce(HttpContext, userAuthentication.Nonce))
{
return BadRequest("Invalid nonce");
}
if (userAuthentication.UserID == 0)
{
await IdentifyOrCreateAltinnUser(userAuthentication, provider);
}
}
else
{
// Generates state tokens. One is added to a cookie and another is sent as state parameter to OIDC provider
AntiforgeryTokenSet tokens = _antiforgery.GetAndStoreTokens(HttpContext);
// Create Nonce. One is added to a cookie and another is sent as nonce parameter to OIDC provider
string nonce = CreateNonce(HttpContext);
CreateGoToCookie(HttpContext, goTo);
// Redirect to OIDC Provider
return Redirect(CreateAuthenticationRequest(provider, tokens.RequestToken, nonce));
}
}
else
{
if (Request.Cookies[_generalSettings.SblAuthCookieName] == null)
{
return Redirect(sblRedirectUrl);
}
try
{
string encryptedTicket = Request.Cookies[_generalSettings.SblAuthCookieName];
userAuthentication = await _cookieDecryptionService.DecryptTicket(encryptedTicket);
}
catch (SblBridgeResponseException sblBridgeException)
{
_logger.LogWarning($"SBL Bridge replied with {sblBridgeException.Response.StatusCode} - {sblBridgeException.Response.ReasonPhrase}");
return StatusCode(StatusCodes.Status503ServiceUnavailable);
}
}
if (userAuthentication != null && userAuthentication.IsAuthenticated)
{
await CreateTokenCookie(userAuthentication);
return Redirect(goTo);
}
return Redirect(sblRedirectUrl);
}
19
View Source File : UrlHelper.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn
public static string GetName(string url)
{
if (url.EndsWith("/"))
{
url = url[0..^1];
}
// dummyBase is just to make sure we have an absolute uri to work on
// as the uri.LocalPath property doesn't work on relative url's.
string dummyBase = "https://dummybase";
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
uri = new Uri(new Uri(dummyBase), url);
}
return Path.GetFileNameWithoutExtension(uri.LocalPath);
}
19
View Source File : HandleOmniBoxSuggestJob.cs
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites
License : GNU General Public License v3.0
Project Creator : Amazing-Favorites
private async void OmniboxSuggestTabOpenAsync(string url, OnInputEnteredDisposition disposition)
{
if (!Uri.TryCreate(url, UriKind.Absolute, out _))
{
await _webExtensions.Tabs.ActiveOrOpenManagerAsync();
return;
}
switch (disposition)
{
case OnInputEnteredDisposition.CurrentTab:
await _webExtensions.Tabs.Update(tabId: null, updateProperties: new UpdateProperties { Url = url });
break;
case OnInputEnteredDisposition.NewForegroundTab:
await _webExtensions.Tabs.Create(new CreateProperties { Url = url, Active = true });
break;
case OnInputEnteredDisposition.NewBackgroundTab:
await _webExtensions.Tabs.Create(new CreateProperties { Url = url, Active = false });
break;
}
}
19
View Source File : OpenFromSubversion.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public override void OnExecute(CommandEventArgs e)
{
Uri selectedUri = null;
Uri rootUri = null;
bool addingProject = (e.Command == AnkhCommand.FileFileAddFromSubversion
|| e.Command == AnkhCommand.FileSccAddFromSubversion);
if (e.Argument is string && Uri.TryCreate((string)e.Argument, UriKind.Absolute, out selectedUri))
{ }
else if (e.Argument is SvnOrigin)
{
SvnOrigin origin = (SvnOrigin)e.Argument;
selectedUri = origin.Uri;
rootUri = origin.RepositoryRoot;
}
else if (e.Argument is Uri)
selectedUri = (Uri)e.Argument;
IAnkhSolutionSettings settings = e.GetService<IAnkhSolutionSettings>();
if (e.PromptUser || selectedUri == null)
{
using (RepositoryOpenDialog dlg = new RepositoryOpenDialog())
{
if (addingProject)
dlg.Text = CommandStrings.AddProjectFromSubversion;
dlg.Filter = settings.OpenProjectFilterName + "|" + settings.AllProjectExtensionsFilter + "|All Files (*.*)|*";
if (selectedUri != null)
dlg.SelectedUri = selectedUri;
if (dlg.ShowDialog(e.Context) != DialogResult.OK)
return;
selectedUri = dlg.SelectedUri;
rootUri = dlg.SelectedRepositoryRoot;
}
}
else if (rootUri == null)
{
if (!e.GetService<IProgressRunner>().RunModal(CommandStrings.RetrievingRepositoryRoot,
delegate(object sender, ProgressWorkerArgs a)
{
rootUri = a.Client.GetRepositoryRoot(selectedUri);
}).Succeeded)
{
return;
}
}
string defaultPath = settings.NewProjectLocation;
if (addingProject)
{
IAnkhSolutionSettings ss = e.GetService<IAnkhSolutionSettings>();
if (!string.IsNullOrEmpty(ss.ProjectRoot))
defaultPath = ss.ProjectRoot;
}
string name = Path.GetFileNameWithoutExtension(SvnTools.GetFileName(selectedUri));
string newPath;
int n = 0;
do
{
newPath = Path.Combine(defaultPath, name);
if (n > 0)
newPath += string.Format("({0})", n);
n++;
}
while (File.Exists(newPath) || Directory.Exists(newPath));
using (CheckoutProject dlg = new CheckoutProject())
{
dlg.Context = e.Context;
if (addingProject)
dlg.Text = CommandStrings.AddProjectFromSubversion;
dlg.ProjectUri = selectedUri;
dlg.RepositoryRootUri = rootUri;
dlg.SelectedPath = newPath;
dlg.SvnOrigin = new SvnOrigin(selectedUri, rootUri);
dlg.HandleCreated += delegate
{
FindRoot(e.Context, selectedUri, dlg);
};
if (dlg.ShowDialog(e.Context) != DialogResult.OK)
return;
if (!addingProject)
OpenSolution(e, dlg);
else
CheckOutAndOpenProject(e, dlg.ProjectTop, dlg.Revision, dlg.ProjectTop, dlg.SelectedPath, dlg.ProjectUri);
}
}
19
View Source File : SolutionSettings.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public IEnumerable<Uri> GetRepositoryUris(bool forBrowse)
{
HybridCollection<Uri> uris = new HybridCollection<Uri>();
if (ProjectRootUri != null)
uris.Add(ProjectRootUri);
// Global keys (over all versions)
using (RegistryKey rk = Config.OpenGlobalKey("Repositories"))
{
if (rk != null)
LoadUris(uris, rk);
}
// Per hive
using (RegistryKey rk = Config.OpenInstanceKey("Repositories"))
{
if (rk != null)
LoadUris(uris, rk);
}
// Per user + Per hive
using (RegistryKey rk = Config.OpenUserInstanceKey("Repositories"))
{
if (rk != null)
LoadUris(uris, rk);
}
// Finally add the last used list from TortoiseSVN
try
{
using (RegistryKey rk = Registry.CurrentUser.OpenSubKey(
"SOFTWARE\\TortoiseSVN\\History\\repoURLS", RegistryKeyPermissionCheck.ReadSubTree))
{
if (rk != null)
LoadUris(uris, rk);
}
}
catch (SecurityException)
{ /* Ignore no read only access; stupid sysadmins */ }
IAnkhConfigurationService configSvc = GetService<IAnkhConfigurationService>();
if (configSvc != null)
{
foreach (string u in configSvc.GetRecentReposUrls())
{
Uri uri;
if (u != null && Uri.TryCreate(u, UriKind.Absolute, out uri))
{
if (!uris.Contains(uri))
uris.Add(uri);
}
}
}
return uris;
}
19
View Source File : SolutionSettings.Commit.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public Uri GetIssueTrackerUri(string issueId)
{
if (issueId == null)
throw new ArgumentNullException("issueId");
if (string.IsNullOrEmpty(issueId))
return null;
RefreshIfDirty();
SettingsCache cache = _cache;
if (cache == null || cache.BugTrackUrl == null)
return null;
string url = cache.BugTrackUrl.Replace("%BUGID%", Uri.EscapeDataString(issueId));
if (url.StartsWith("^/"))
{
Uri repositoryRoot = RepositoryRoot;
if (repositoryRoot == null)
return null;
url = repositoryRoot.AbsoluteUri + url.Substring(2);
}
Uri result;
if (Uri.TryCreate(url, UriKind.Absolute, out result))
return result;
return null;
}
19
View Source File : SolutionSettings.Commit.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public Uri GetRevisionUri(string revisionText)
{
if (revisionText == null)
throw new ArgumentNullException("revisionText");
if (string.IsNullOrEmpty(revisionText))
return null;
RefreshIfDirty();
SettingsCache cache = _cache;
if (cache == null || cache.RevisionUrl == null)
return null;
string url = cache.RevisionUrl.Replace("%REVISION%", Uri.EscapeDataString(revisionText));
if (url.StartsWith("^/"))
{
Uri repositoryRoot = RepositoryRoot;
if (repositoryRoot == null)
return null;
url = repositoryRoot.AbsoluteUri + url.Substring(2);
}
Uri result;
if (Uri.TryCreate(url, UriKind.Absolute, out result))
return result;
return null;
}
19
View Source File : SolutionSettings.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
void SetProjectRootValue(string value)
{
if (SolutionFilename == null)
return;
string sd = SvnTools.PathToRelativeUri(SvnTools.GetNormalizedDirectoryName(SolutionFilename).TrimEnd('\\') + '\\').ToString();
string v = SvnTools.PathToRelativeUri(SvnTools.GetNormalizedFullPath(value)).ToString();
if (!v.EndsWith("/"))
v += "/";
if (!sd.StartsWith(v, StringComparison.OrdinalIgnoreCase))
return;
Uri solUri;
Uri resUri;
if (!Uri.TryCreate("file:///" + sd.Replace('\\', '/'), UriKind.Absolute, out solUri)
|| !Uri.TryCreate("file:///" + v.Replace('\\', '/'), UriKind.Absolute, out resUri))
return;
using (SvnClient client = GetService<ISvnClientPool>().GetNoUIClient())
{
SvnSetPropertyArgs ps = new SvnSetPropertyArgs();
ps.ThrowOnError = false;
client.SetProperty(SolutionFilename, AnkhSccPropertyNames.ProjectRoot, solUri.MakeRelativeUri(resUri).ToString(), ps);
GetService<ISvnStatusCache>().MarkDirty(SolutionFilename);
// The getter will reload the settings for us
}
_cache = null;
}
19
View Source File : SolutionSettings.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
static void LoadUris(HybridCollection<Uri> uris, RegistryKey rk)
{
foreach (string name in rk.GetValueNames())
{
string value = rk.GetValue(name) as string;
if (value != null && !value.EndsWith("/"))
value += "/";
Uri uri;
if (value != null && Uri.TryCreate(value, UriKind.Absolute, out uri))
{
if (!uris.Contains(uri))
uris.Add(uri);
}
}
}
19
View Source File : RepositoryOpenDialog.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (urlBox == null)
return;
// Add current project root (if available) first
if (SolutionSettings != null && SolutionSettings.ProjectRootUri != null)
{
if (!urlBox.Items.Contains(SolutionSettings.ProjectRootUri))
urlBox.Items.Add(SolutionSettings.ProjectRootUri);
}
if (Config != null)
{
// Add last used url
using (RegistryKey rk = Config.OpenUserInstanceKey("Dialogs"))
{
if (rk != null)
{
string value = rk.GetValue("Last Repository") as string;
Uri uri;
if (value != null && Uri.TryCreate(value, UriKind.Absolute, out uri))
{
if (!urlBox.Items.Contains(uri))
urlBox.Items.Add(uri);
}
}
}
foreach (string value in Config.GetRecentReposUrls())
{
Uri uri;
if (value != null && Uri.TryCreate(value, UriKind.Absolute, out uri))
{
if (!urlBox.Items.Contains(uri))
urlBox.Items.Add(uri);
}
}
}
if (SolutionSettings != null)
foreach (Uri uri in SolutionSettings.GetRepositoryUris(true))
{
if (!urlBox.Items.Contains(uri))
urlBox.Items.Add(uri);
}
if (urlBox.Items.Count > 0 && string.IsNullOrEmpty(urlBox.Text.Trim()))
{
urlBox.SelectedIndex = 0;
UpdateDirectories();
}
if (string.IsNullOrEmpty(fileTypeBox.Text) && fileTypeBox.Items.Count > 0)
fileTypeBox.SelectedItem = fileTypeBox.Items[0];
}
19
View Source File : RepositoryOpenDialog.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
void UpdateDirectories()
{
Uri nameUri;
Uri dirUri;
string urlBoxText = urlBox.Text; // Url's can not contain whitespace
if (string.IsNullOrEmpty(urlBoxText) || !Uri.TryCreate(urlBoxText, UriKind.Absolute, out dirUri))
{
dirUri = null;
urlBox.Text = "";
}
string name = fileNameBox.Text.Trim();
if (!string.IsNullOrEmpty(name) && Uri.TryCreate(name, UriKind.RelativeOrAbsolute, out nameUri))
{
if (dirUri != null && !nameUri.IsAbsoluteUri && nameUri.ToString().Contains("/") || (nameUri.ToString() == ".."))
nameUri = SvnTools.AppendPathSuffix(dirUri, name);
if (nameUri.IsAbsoluteUri)
{
// We have an absolute url. Split it in file and directory
string path = nameUri.GetComponents(UriComponents.PathAndQuery, UriFormat.SafeUnescaped);
int dirEnd = path.LastIndexOf('/');
if (dirEnd >= 0)
{
path = path.Substring(0, dirEnd + 1);
string v = nameUri.GetComponents(UriComponents.StrongAuthority | UriComponents.SchemeAndServer, UriFormat.SafeUnescaped);
Uri uriRoot = new Uri(v);
if (uriRoot.IsFile)
path = path.TrimStart('/'); // Fixup for UNC paths
Uri dir = new Uri(uriRoot, path);
if (dir != nameUri)
nameUri = dir.MakeRelativeUri(nameUri);
else
nameUri = new Uri("", UriKind.Relative);
SetDirectory(dir);
fileNameBox.Text = nameUri.ToString();
RefreshBox(dir);
}
}
else if (dirUri == null)
return;
}
}
19
View Source File : AddToSubversion.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
private void timer1_Tick(object sender, EventArgs e)
{
Uri u;
if (previousUrl != repositoryUrl.Text)
{
previousUrl = repositoryUrl.Text;
}
else if (!string.IsNullOrEmpty(previousUrl) && Uri.TryCreate(previousUrl, UriKind.Absolute, out u))
{
timer1.Enabled = false;
repositoryTree.BrowseTo(u);
}
}
19
View Source File : UpdateAvailableDialog.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
private void linkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
Uri uri; // Just some minor precautions
if (Uri.TryCreate((string)e.Link.LinkData, UriKind.Absolute, out uri) && !uri.IsFile && !uri.IsUnc)
{
try
{
System.Diagnostics.Process.Start((string)e.Link.LinkData);
}
catch
{ }
}
}
19
View Source File : UIUtils.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public static Uri DisplayBrowseDialogAndGetResult(WizardPage page, SvnItem target, string baseUri)
{
Uri u;
if(Uri.TryCreate(baseUri, UriKind.Absolute, out u))
return DisplayBrowseDialogAndGetResult(page, target, u);
page.Message = MergeUtils.INVALID_FROM_URL;
return null;
}
19
View Source File : ExternalsPropertyEditor.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
private static bool TryCreateItemFromRow(DataGridViewRow r, out SvnExternalItem item)
{
if (r == null)
throw new ArgumentNullException("r");
string url = r.Cells[0].Value as string;
string target = r.Cells[4].Value as string;
string rev = r.Cells[2].Value as string;
SvnRevision rr = string.IsNullOrEmpty(rev) ? SvnRevision.None : long.Parse(rev);
if (url.Contains("://"))
{
Uri uri;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri))
{
item = null;
return false;
}
url = uri.AbsoluteUri;
}
SvnExternalItem ei = new SvnExternalItem(target, url, rr, rr);
SvnExternalItem p;
if (!SvnExternalItem.TryParse(ei.ToString(), out p) || !p.Equals(ei))
{
item = null;
return false;
}
item = ei;
return true;
}
19
View Source File : ExternalsPropertyEditor.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
private void SelectRepositoryFolder(DataGridViewRow row)
{
IAnkhServiceProvider context = Context;
if (context != null)
{
using (RepositoryExplorer.RepositoryFolderBrowserDialog rfbd = new RepositoryExplorer.RepositoryFolderBrowserDialog())
{
// do not show files in repo browser
rfbd.ShowFiles = false;
string selectedUriString = row.Cells[0].Value as string;
// set the current URL value as the initial selection
Uri selectedUri;
if (!string.IsNullOrEmpty(selectedUriString)
&& Uri.TryCreate(selectedUriString, UriKind.Absolute, out selectedUri)
)
{
rfbd.SelectedUri = selectedUri;
}
if (DialogResult.OK == rfbd.ShowDialog(context))
{
Uri uri = rfbd.SelectedUri;
// set the Url cell value to the selected Url
row.Cells[0].Value = uri == null ? string.Empty : uri.AbsoluteUri;
}
}
}
}
19
View Source File : ExternalsPropertyEditor.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
private void SelectRevision(DataGridViewRow row)
{
IAnkhServiceProvider context = Context;
if (context != null)
{
string selectedUriString = row.Cells[0].Value as string;
Uri selectedUri;
if (!string.IsNullOrEmpty(selectedUriString)
&& Uri.TryCreate(selectedUriString, UriKind.Absolute, out selectedUri)
)
{
Uri repoRoot = string.Equals(_lastUsedUriString, selectedUriString) ? _lastRepositoryRoot : null;
if (repoRoot == null)
{
if (context.GetService<IProgressRunner>().RunModal(
PropertyEditStrings.RetrievingRepositoryRoot,
delegate(object sender, ProgressWorkerArgs a)
{
repoRoot = a.Client.GetRepositoryRoot(selectedUri);
}).Succeeded)
{
//cache the last used repo uri string and the fetched repository root uri
_lastRepositoryRoot = repoRoot;
_lastUsedUriString = selectedUriString;
}
}
if (repoRoot != null)
{
try
{
// set the current revision value as the initial selection
string rev = row.Cells[2].Value as string;
SvnRevision rr = string.IsNullOrEmpty(rev) ? SvnRevision.None : long.Parse(rev);
SvnUriTarget svnTarget = new SvnUriTarget(selectedUri, rr);
Ankh.Scc.SvnOrigin origin = new Ankh.Scc.SvnOrigin(svnTarget, repoRoot);
using (Ankh.UI.SvnLog.LogViewerDialog dlg = new Ankh.UI.SvnLog.LogViewerDialog(origin))
{
if (dlg.ShowDialog(Context) == DialogResult.OK)
{
Ankh.Scc.ISvnLogItem li = EnumTools.GetSingle(dlg.SelectedItems);
rev = li == null ? null : li.Revision.ToString();
//set the revision cell value to the selection revision
row.Cells[2].Value = rev ?? string.Empty;
}
}
}
catch
{
// clear cache in case of error
_lastUsedUriString = null;
_lastRepositoryRoot = null;
}
}
}
}
}
19
View Source File : RepositoryOpenDialog.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
void ProcessOk()
{
UpdateDirectories();
string fileText = fileNameBox.Text;
if (string.IsNullOrEmpty(fileText))
return;
Uri dirUri;
Uri fileUri;
if (Uri.TryCreate(urlBox.Text, UriKind.Absolute, out dirUri) && Uri.TryCreate(fileText, UriKind.Relative, out fileUri))
{
Uri combined = SvnTools.AppendPathSuffix(dirUri, SvnTools.UriPartToPath(fileText));
AnkhAction fill = delegate()
{
CheckResult(combined);
};
fill.BeginInvoke(null, null);
}
}
19
View Source File : RepositoryOpenDialog.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
void OnDirChanged()
{
string txt = urlBox.Text;
if (!txt.EndsWith("/"))
txt += '/';
Uri uri;
if (!Uri.TryCreate(txt, UriKind.Absolute, out uri))
RefreshBox(null);
RefreshBox(uri);
}
19
View Source File : RepositoryOpenDialog.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
private void dirUpButton_Click(object sender, EventArgs e)
{
Uri uri;
if (Uri.TryCreate(urlBox.Text.Trim(), UriKind.Absolute, out uri))
{
Uri parentUri = new Uri(uri, "../");
if (parentUri == uri || _repositoryRoots.Contains(uri))
return;
Uri fileUri;
string fileText = fileNameBox.Text.Trim();
if (!string.IsNullOrEmpty(fileText) &&
Uri.TryCreate(fileText.Trim(), UriKind.Relative, out fileUri))
{
fileUri = parentUri.MakeRelativeUri(SvnTools.AppendPathSuffix(uri, fileText.Trim()));
fileNameBox.Text = fileUri.ToString();
}
SetDirectory(parentUri);
RefreshBox(parentUri);
}
}
19
View Source File : NativeMethods.cs
License : Apache License 2.0
Project Creator : AmpScm
License : Apache License 2.0
Project Creator : AmpScm
public static bool IsSamePath(string file1, string file2)
{
if (file1 == null || file1.Length == 0)
{
return (file2 == null || file2.Length == 0);
}
Uri uri1 = null;
Uri uri2 = null;
try
{
if (!Uri.TryCreate(file1, UriKind.Absolute, out uri1) || !Uri.TryCreate(file2, UriKind.Absolute, out uri2))
{
return false;
}
if (uri1 != null && uri1.IsFile && uri2 != null && uri2.IsFile)
{
return 0 == String.Compare(uri1.LocalPath, uri2.LocalPath, StringComparison.OrdinalIgnoreCase);
}
return file1 == file2;
}
catch (UriFormatException e)
{
System.Diagnostics.Trace.WriteLine("Exception " + e.Message);
}
return false;
}
19
View Source File : IconElement.cs
License : MIT License
Project Creator : amwx
License : MIT License
Project Creator : amwx
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is Symbol symbol)
{
return new SymbolIcon { Symbol = symbol };
}
else if (value is IconSource ico)
{
if (ico is FontIconSource fis)
{
return IconHelpers.CreateFontIconFromFontIconSource(fis);
}
else if (ico is SymbolIconSource sis)
{
return IconHelpers.CreateSymbolIconFromSymbolIconSource(sis);
}
else if (ico is PathIconSource pis)
{
return IconHelpers.CreatePathIconFromPathIconSource(pis);
}
else if (ico is BitmapIconSource bis)
{
return IconHelpers.CreateBitmapIconFromBitmapIconSource(bis);
}
}
else if (value is IImage img)
{
return new ImageIcon { Source = img };
}
else if (value is string val)
{
//First we try if the text is a valid Symbol
if (Enum.TryParse(typeof(Symbol), val, out object sym))
{
return new SymbolIcon() { Symbol = (Symbol)sym };
}
//Try a PathIcon
if (PathIcon.IsDataValid(val, out Geometry g))
{
return new PathIcon() { Data = g };
}
try
{
if (Uri.TryCreate(val, UriKind.RelativeOrAbsolute, out Uri result))
{
return new BitmapIcon() { UriSource = result };
}
}
catch { }
//If we've reached this point, we'll make a FontIcon
//Glyph can be anything (sort of), so we don't need to Try/Catch
return new FontIconSource() { Glyph = val };
}
return base.ConvertFrom(context, culture, value);
}
19
View Source File : IconSource.cs
License : MIT License
Project Creator : amwx
License : MIT License
Project Creator : amwx
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if (value is Symbol symbol)
{
return new SymbolIconSource { Symbol = symbol };
}
else if (value is IImage img)
{
return new ImageIconSource { Source = img };
}
else if (value is string val)
{
//First we try if the text is a valid Symbol
if (Enum.TryParse(typeof(Symbol), val, out object sym))
{
return new SymbolIconSource() { Symbol = (Symbol)sym };
}
//Try a PathIcon
if (PathIcon.IsDataValid(val, out Geometry g))
{
return new PathIconSource() { Data = g };
}
try
{
if (Uri.TryCreate(val, UriKind.RelativeOrAbsolute, out Uri result))
{
return new BitmapIconSource() { UriSource = result };
}
}
catch { }
//If we've reached this point, we'll make a FontIcon
//Glyph can be anything (sort of), so we don't need to Try/Catch
return new FontIconSource() { Glyph = val };
}
return base.ConvertFrom(context, culture, value);
}
19
View Source File : UriUtils.cs
License : Apache License 2.0
Project Creator : AndcultureCode
License : Apache License 2.0
Project Creator : AndcultureCode
public static bool IsValidHttpUrl(string source)
{
if (string.IsNullOrWhiteSpace(source))
{
return false;
}
Uri uriResult;
return Uri.TryCreate(source, UriKind.Absolute, out uriResult) && (uriResult.Scheme == Uri.UriSchemeHttp || uriResult.Scheme == Uri.UriSchemeHttps);
}
19
View Source File : StringExtensions.cs
License : Apache License 2.0
Project Creator : AndcultureCode
License : Apache License 2.0
Project Creator : AndcultureCode
public static bool IsValidHttpUrl(this string source)
{
if (string.IsNullOrWhiteSpace(source))
{
return false;
}
var validUriSchemes = new[]
{
Uri.UriSchemeHttp,
Uri.UriSchemeHttps
};
return Uri.TryCreate(source, UriKind.Absolute, out var uriResult) && validUriSchemes.Contains(uriResult.Scheme);
}
19
View Source File : CrmWorkflowBase.cs
License : MIT License
Project Creator : AndrewButenko
License : MIT License
Project Creator : AndrewButenko
public EnreplacedyReference ConvertToEnreplacedyReference(string recordReference)
{
Uri uriResult;
if (Uri.TryCreate(recordReference, UriKind.Absolute, out uriResult))
{
return ParseUrlToEnreplacedyReference(recordReference);
}
try
{
var jsonEnreplacedyReference = JsonConvert.DeserializeObject<JsonEnreplacedyReference>(recordReference);
return new EnreplacedyReference(jsonEnreplacedyReference.LogicName, jsonEnreplacedyReference.Id);
}
catch (Exception e)
{
throw new Exception($"Error converting string '{recordReference}' to EnreplacedyReference - {e.Message}", e);
}
}
19
View Source File : HttpListenerResponse.cs
License : MIT License
Project Creator : andruzzzhka
License : MIT License
Project Creator : andruzzzhka
public void Redirect (string url)
{
checkDisposedOrHeadersSent ();
if (url == null)
throw new ArgumentNullException ("url");
Uri uri = null;
if (!url.MaybeUri () || !Uri.TryCreate (url, UriKind.Absolute, out uri))
throw new ArgumentException ("Not an absolute URL.", "url");
_location = url;
_statusCode = 302;
_statusDescription = "Found";
}
19
View Source File : HttpUtility.cs
License : MIT License
Project Creator : andruzzzhka
License : MIT License
Project Creator : andruzzzhka
internal static Uri CreateRequestUrl (
string requestUri, string host, bool websocketRequest, bool secure)
{
if (requestUri == null || requestUri.Length == 0 || host == null || host.Length == 0)
return null;
string schm = null;
string path = null;
if (requestUri.StartsWith ("/")) {
path = requestUri;
}
else if (requestUri.MaybeUri ()) {
Uri uri;
var valid = Uri.TryCreate (requestUri, UriKind.Absolute, out uri) &&
(((schm = uri.Scheme).StartsWith ("http") && !websocketRequest) ||
(schm.StartsWith ("ws") && websocketRequest));
if (!valid)
return null;
host = uri.Authority;
path = uri.PathAndQuery;
}
else if (requestUri == "*") {
}
else {
// As authority form
host = requestUri;
}
if (schm == null)
schm = (websocketRequest ? "ws" : "http") + (secure ? "s" : String.Empty);
var colon = host.IndexOf (':');
if (colon == -1)
host = String.Format ("{0}:{1}", host, schm == "http" || schm == "ws" ? 80 : 443);
var url = String.Format ("{0}://{1}{2}", schm, host, path);
Uri res;
if (!Uri.TryCreate (url, UriKind.Absolute, out res))
return null;
return res;
}
19
View Source File : StreamProviderUtil.cs
License : MIT License
Project Creator : angelobreuer
License : MIT License
Project Creator : angelobreuer
public static StreamProvider GetStreamProvider(string uri)
{
if (string.IsNullOrWhiteSpace(uri))
{
throw new ArgumentException("The specified uri is blank.", nameof(uri));
}
if (Uri.TryCreate(uri, UriKind.Absolute, out var result))
{
// local file stream
if (result.IsFile)
{
return StreamProvider.Local;
}
// get stream provider
return GetStreamProvider(result.Host, result.AbsolutePath);
}
// uri can not be parsed
return StreamProvider.Unknown;
}
See More Examples