Here are the examples of the csharp api System.Uri.ToString() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2663 Examples
19
Source : BuildInFormatters.cs
with MIT License
from 1996v
with MIT License
from 1996v
public void Serialize(ref BssomWriter writer, ref BssomSerializeContext context, Uri value)
{
if (value == null)
{
writer.WriteNull();
return;
}
writer.Write(value.ToString());
}
19
Source : BuildInFormatters.cs
with MIT License
from 1996v
with MIT License
from 1996v
public int Size(ref BssomSizeContext context, Uri value)
{
if (value == null)
{
return BssomBinaryPrimitives.NullSize;
}
return BssomBinaryPrimitives.StringSize(value.ToString()) + BssomBinaryPrimitives.BuildInTypeCodeSize;
}
19
Source : UpdateHandle.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
private async void CheckUpdateAsync(string type)
{
try
{
Utils.SetSecurityProtocol();
WebRequestHandler webRequestHandler = new WebRequestHandler
{
AllowAutoRedirect = false
};
if (httpProxyTest() > 0)
{
int httpPort = _config.GetLocalPort(Global.InboundHttp);
WebProxy webProxy = new WebProxy(Global.Loopback, httpPort);
webRequestHandler.Proxy = webProxy;
}
HttpClient httpClient = new HttpClient(webRequestHandler);
string url;
if (type == "v2fly")
{
url = v2flyCoreLatestUrl;
}
else if (type == "xray")
{
url = xrayCoreLatestUrl;
}
else if (type == "v2rayN")
{
url = nLatestUrl;
}
else
{
throw new ArgumentException("Type");
}
HttpResponseMessage response = await httpClient.GetAsync(url);
if (response.StatusCode.ToString() == "Redirect")
{
responseHandler(type, response.Headers.Location.ToString());
}
else
{
Utils.SaveLog("StatusCode error: " + url);
return;
}
}
catch (Exception ex)
{
Utils.SaveLog(ex.Message, ex);
_updateFunc(false, ex.Message);
}
}
19
Source : StringExtension.cs
with MIT License
from 3F
with MIT License
from 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
Source : HTTP.cs
with MIT License
from 944095635
with MIT License
from 944095635
private void GetData(HttpItem item, HttpResult result)
{
if (response == null)
{
return;
}
#region base
//获取StatusCode
result.StatusCode = response.StatusCode;
//获取StatusDescription
result.StatusDescription = response.StatusDescription;
//获取Headers
result.Header = response.Headers;
//获取最后访问的URl
result.ResponseUri = response.ResponseUri.ToString();
//获取CookieCollection
if (response.Cookies != null) result.CookieCollection = response.Cookies;
//获取set-cookie
if (response.Headers["set-cookie"] != null) result.Cookie = response.Headers["set-cookie"];
#endregion base
#region byte
//处理网页Byte
byte[] ResponseByte = GetByte();
#endregion byte
#region Html
if (ResponseByte != null && ResponseByte.Length > 0)
{
//设置编码
SetEncoding(item, result, ResponseByte);
//得到返回的HTML
result.Html = encoding.GetString(ResponseByte);
}
else
{
//没有返回任何Html代码
result.Html = string.Empty;
}
#endregion Html
}
19
Source : FrmBrowser.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
private void Browser_DoreplacedentCompleted(object sender, WebBrowserDoreplacedentCompletedEventArgs e)
{
if (gfxBrowser.Url == null) return;
switch (cmboSource.SelectedItem.ToString().ToLower())
{
case "mangadex":
if (gfxBrowser.Url.ToString().StartsWith(MangaDexHelper.MANGADEX_URL + "/replacedle/"))
btnAdd.Enabled = true;
else
btnAdd.Enabled = false;
break;
case "kissmanga":
if(gfxBrowser.Url.ToString().StartsWith(KissMangaHelper.KISS_URL + "/manga/"))
btnAdd.Enabled = true;
else
btnAdd.Enabled = false;
break;
case "nhentai":
if (gfxBrowser.Url.ToString().StartsWith("https://nhentai.net/g/"))
btnAdd.Enabled = true;
else
btnAdd.Enabled = false;
break;
default:
break;
}
}
19
Source : FrmBrowser.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
private void BtnAdd_Click(object sender, EventArgs e)
{
string url = gfxBrowser.Url.ToString();
string name = string.Empty;
string num = string.Empty;
switch (cmboSource.SelectedItem.ToString().ToLower())
{
case "mangadex":
name = url.Split('/')[5];
num = url.Split('/')[4];
url = MangaDexHelper.MANGADEX_URL + "/api/manga/" + num;
Manga m = new MangaDex(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, num)), url);
FrmEdit editor = new FrmEdit(m, false);
DialogResult result = editor.ShowDialog();
if (result == DialogResult.OK)
{
// cleanup
foreach (Chapter ch in m.GetChapters())
{
try
{
string s = ch.GetChapterRoot().ToString();
Directory.Delete(ch.GetChapterRoot().ToString());
} catch (Exception) { }
}
WFClient.dbm.GetMangaDB().Add(m);
String[] dls = m.GetDLChapters();
if (dls == null || dls[0].Equals("-1"))
{
foreach (Chapter c in m.GetSetPrunedChapters(false))
{
WFClient.dlm.AddToQueue(new MangaDexDownload(c));
}
} else
{ // Only download selected chapters
foreach (Chapter c in m.GetSetPrunedChapters(false))
{
if (dls.Contains(c.GetNum()))
{
WFClient.dlm.AddToQueue(new MangaDexDownload(c));
}
}
}
// Start downloading the first one
WFClient.dlm.DownloadNext();
} else
{
}
break;
case "kissmanga":
// MessageBox.Show("Sorry, can't do this yet! ;(\n\n(ignore the download started box)");
// break;
// TODO
string kName = KissMangaHelper.GetName(url);
string kHash = KissMangaHelper.GetHash(url);
// Manga km = new Manga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, num)), url);
Manga km = new KissManga(FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, kHash)), url);
FrmEdit editor1 = new FrmEdit(km, false);
DialogResult result1 = editor1.ShowDialog();
if (result1 == DialogResult.OK)
{
// cleanup
foreach (Chapter ch in km.GetChapters())
{
try
{
string s = ch.GetChapterRoot().ToString();
Directory.Delete(ch.GetChapterRoot().ToString());
}
catch (Exception) { }
}
WFClient.dbm.GetMangaDB().Add(km);
String[] dls = km.GetDLChapters();
if (dls == null || dls[0].Equals("-1"))
{
foreach (Chapter c in km.GetSetPrunedChapters(false))
{
WFClient.dlm.AddToQueue(new KissMangaDownload(c));
}
}
else
{ // Only download selected chapters
foreach (Chapter c in km.GetSetPrunedChapters(false))
{
if (dls.Contains(c.GetNum()))
{
WFClient.dlm.AddToQueue(new KissMangaDownload(c));
}
}
}
// Start downloading the first one
WFClient.dlm.DownloadNext();
}
else
{
}
break;
case "nhentai":
num = url.Split('/')[4];
name = gfxBrowser.Doreplacedentreplacedle.Substring(0, gfxBrowser.Doreplacedentreplacedle.IndexOf("nhentai:") - 3);
JObject hJson = new JObject(
new JProperty("hentai",
new JObject(
new JProperty("replacedle", name),
new JProperty("num", num),
new JProperty("url", url))));
DirectoryInfo hDir = FileHelper.CreateDI(Path.Combine(FileHelper.APP_ROOT.FullName, "h" + num));
Hentai h = new Nhentai(hDir, hJson.ToString());
FrmEdit edit = new FrmEdit(h, false);
DialogResult rezult = edit.ShowDialog();
if (rezult == DialogResult.OK)
{
WFClient.dbm.GetMangaDB().Add(h);
Chapter ch = h.GetChapters()[0];
WFClient.dlm.AddToQueue(new NhentaiDownload(ch));
// Start downloading the first one
WFClient.dlm.DownloadNext();
}
break;
}
MessageBox.Show("Download started! You may close the browser at any time, but please keep MikuReader open until the download has completed.");
}
19
Source : FrmHentaiBrowser.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
private void AddThisreplacedleToolStripMenuItem_Click(object sender, EventArgs e)
{
if (browser.Url != null)
{
string api = browser.Url.ToString();
string num = string.Empty;
if (api.StartsWith("https://nhentai.net/g/"))
{
num = api.Split('/')[4];
startPage.AddHentai(num, Getreplacedle());
}
else
{
MessageBox.Show("Error: Not a valid nHentai URL");
}
}
}
19
Source : FrmHentaiBrowser.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
private void Browser_DoreplacedentCompleted(object sender, GeckoDoreplacedentCompletedEventArgs e)
{
if (browser.Url != null)
{
string url = browser.Url.ToString();
if (url.StartsWith("https://nhentai.net/g/"))
{
addThisreplacedleToolStripMenuItem.Enabled = true;
}
else
{
addThisreplacedleToolStripMenuItem.Enabled = false;
}
}
}
19
Source : HTTP.cs
with MIT License
from 944095635
with MIT License
from 944095635
public HttpResult GetResponseUri(HttpItem item)
{
//返回参数
HttpResult result = new HttpResult();
try
{
//准备参数
SetRequest(item);
}
catch (Exception ex)
{
//配置参数时出错
return new HttpResult() { Cookie = string.Empty, Header = null, Html = ex.Message, StatusDescription = "配置参数时出错:" + ex.Message };
}
try
{
//请求数据
using (response = (HttpWebResponse)request.GetResponse())
{
result.ResponseUri = response.ResponseUri.ToString();
}
}
catch (Exception ex)
{
result.Html = ex.Message;
}
return result;
}
19
Source : FrmMangaBrowser.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
private void AddThisreplacedleToolStripMenuItem_Click(object sender, EventArgs e)
{
if (browser.Url != null)
{
string api = browser.Url.ToString();
string name = string.Empty;
string num = string.Empty;
if (api.StartsWith("https://mangadex.org/replacedle/"))
{
name = api.Split('/')[5];
num = api.Split('/')[4];
api = "https://mangadex.org/api/manga/" + num;
startPage.AddManga(api, num, false);
}
else
{
MessageBox.Show("Error: Not a valid MangaDex URL");
}
}
}
19
Source : FrmMangaBrowser.cs
with GNU General Public License v3.0
from 9vult
with GNU General Public License v3.0
from 9vult
private void Browser_DoreplacedentCompleted(object sender, GeckoDoreplacedentCompletedEventArgs e)
{
if (browser.Url != null)
{
string url = browser.Url.ToString();
if (url.StartsWith("https://mangadex.org/replacedle/"))
{
addThisreplacedleToolStripMenuItem.Enabled = true;
}
else
{
addThisreplacedleToolStripMenuItem.Enabled = false;
}
}
}
19
Source : VisualLineLinkText.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
[System.Diagnostics.Codereplacedysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "I've seen Process.Start throw undoreplacedented exceptions when the mail client / web browser is installed incorrectly")]
protected internal override void OnMouseDown(MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left && !e.Handled && LinkIsClickable()) {
RequestNavigateEventArgs args = new RequestNavigateEventArgs(this.NavigateUri, this.TargetName);
args.RoutedEvent = Hyperlink.RequestNavigateEvent;
FrameworkElement element = e.Source as FrameworkElement;
if (element != null) {
// allow user code to handle the navigation request
element.RaiseEvent(args);
}
if (!args.Handled) {
try {
Process.Start(new ProcessStartInfo { FileName = this.NavigateUri.ToString(), UseShellExecute = true });
} catch {
// ignore all kinds of errors during web browser start
}
}
e.Handled = true;
}
}
19
Source : HtmlRichTextWriter.cs
with MIT License
from Abdesol
with MIT License
from Abdesol
public override void BeginHyperlinkSpan(Uri uri)
{
WriteIndentationAndSpace();
string link = WebUtility.HtmlEncode(uri.ToString());
htmlWriter.Write("<a href=\"" + link + "\">");
endTagStack.Push("</a>");
}
19
Source : OVRGradleGeneration.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public void PatchAndroidManifest(string path)
{
string manifestFolder = Path.Combine(path, "src/main");
string file = manifestFolder + "/AndroidManifest.xml";
bool patchedSecurityConfig = false;
// If Enable NSC Config, copy XML file into gradle project
OVRProjectConfig projectConfig = OVRProjectConfig.GetProjectConfig();
if (projectConfig != null)
{
if (projectConfig.enableNSCConfig)
{
// If no custom xml security path is specified, look for the default location in the integrations package.
string securityConfigFile = projectConfig.securityXmlPath;
if (string.IsNullOrEmpty(securityConfigFile))
{
securityConfigFile = GetOculusProjectNetworkSecConfigPath();
}
else
{
Uri configUri = new Uri(Path.GetFullPath(securityConfigFile));
Uri projectUri = new Uri(Application.dataPath);
Uri relativeUri = projectUri.MakeRelativeUri(configUri);
securityConfigFile = relativeUri.ToString();
}
string xmlDirectory = Path.Combine(path, "src/main/res/xml");
try
{
if (!Directory.Exists(xmlDirectory))
{
Directory.CreateDirectory(xmlDirectory);
}
File.Copy(securityConfigFile, Path.Combine(xmlDirectory, "network_sec_config.xml"), true);
patchedSecurityConfig = true;
}
catch (Exception e)
{
UnityEngine.Debug.LogError(e.Message);
}
}
}
OVRManifestPreprocessor.PatchAndroidManifest(file, enableSecurity: patchedSecurityConfig);
}
19
Source : PathHelper.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
public static string MakeRelativePath(string fromPath, string toPath)
{
var fromUri = new Uri(Path.GetFullPath(fromPath));
var toUri = new Uri(Path.GetFullPath(toPath));
if (fromUri.Scheme != toUri.Scheme)
{
return toPath;
}
var relativeUri = fromUri.MakeRelativeUri(toUri);
var relativePath = Uri.UnescapeDataString(relativeUri.ToString());
if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath;
}
19
Source : OVRGradleGeneration.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private static string GetOculusProjectNetworkSecConfigPath()
{
var so = ScriptableObject.CreateInstance(typeof(OVRPluginUpdaterStub));
var script = MonoScript.FromScriptableObject(so);
string replacedetPath = replacedetDatabase.GetreplacedetPath(script);
string editorDir = Directory.GetParent(replacedetPath).FullName;
string configreplacedetPath = Path.GetFullPath(Path.Combine(editorDir, "network_sec_config.xml"));
Uri configUri = new Uri(configreplacedetPath);
Uri projectUri = new Uri(Application.dataPath);
Uri relativeUri = projectUri.MakeRelativeUri(configUri);
return relativeUri.ToString();
}
19
Source : OVRProjectConfig.cs
with MIT License
from absurd-joy
with MIT License
from absurd-joy
private static string GetOculusProjectConfigreplacedetPath()
{
var so = ScriptableObject.CreateInstance(typeof(OVRPluginUpdaterStub));
var script = MonoScript.FromScriptableObject(so);
string replacedetPath = replacedetDatabase.GetreplacedetPath(script);
string editorDir = Directory.GetParent(replacedetPath).FullName;
string ovrDir = Directory.GetParent(editorDir).FullName;
string oculusDir = Directory.GetParent(ovrDir).FullName;
string configreplacedetPath = Path.GetFullPath(Path.Combine(oculusDir, "OculusProjectConfig.replacedet"));
Uri configUri = new Uri(configreplacedetPath);
Uri projectUri = new Uri(Application.dataPath);
Uri relativeUri = projectUri.MakeRelativeUri(configUri);
return relativeUri.ToString();
}
19
Source : MarkdownRenderService.cs
with Apache License 2.0
from acblog
with Apache License 2.0
from acblog
static string? MediaLink(Uri uri)
{
try
{
string url = uri.ToString();
url = url[(uri.Scheme.Length + 3)..]; // ://
string pre = "music.163.com/#/";
if (url.StartsWith(pre))
{
var items = url[pre.Length..].Split('?');
var id = items[1].Split("&", StringSplitOptions.RemoveEmptyEntries).First(p => p.StartsWith("id="))?[3..];
int type = (items[0]) switch
{
"song" => 2,
"playlist" => 0,
"album" => 1,
_ => 0,
};
return $"//music.163.com/outchain/player?type={type}&id={id}&auto=0";
}
}
19
Source : ProjectFileExtensions.cs
with MIT License
from action-bi-toolkit
with MIT License
from action-bi-toolkit
public static string GetRelativePath(this IProjectFile file, IProjectFolder folder)
=> new Uri(folder.BasePath + @"\")
.MakeRelativeUri(new Uri(file.Path))
.ToString();
19
Source : JobNotification.cs
with MIT License
from actions
with MIT License
from actions
private void StartMonitor(Guid jobId, string accessToken, Uri serverUri)
{
if(String.IsNullOrEmpty(accessToken))
{
Trace.Info("No access token could be retrieved to start the monitor.");
return;
}
try
{
Trace.Info("Entering StartMonitor");
if (_isMonitorConfigured)
{
String message = $"Start {jobId.ToString()} {accessToken} {serverUri.ToString()} {System.Diagnostics.Process.GetCurrentProcess().Id}";
Trace.Info("Writing StartMonitor to socket");
_monitorSocket.Send(Encoding.UTF8.GetBytes(message));
Trace.Info("Finished StartMonitor writing to socket");
}
}
catch (SocketException e)
{
Trace.Error($"Failed sending StartMonitor message on socket!");
Trace.Error(e);
}
catch (Exception e)
{
Trace.Error($"Unexpected error occurred while sending StartMonitor message on socket!");
Trace.Error(e);
}
}
19
Source : ResourcesSerializer.cs
with MIT License
from action-bi-toolkit
with MIT License
from action-bi-toolkit
public bool TryDeserialize(out IDictionary<string, byte[]> part)
{
var result = new Dictionary<string, byte[]>();
var baseUri = new Uri(BasePath + "/" /* Need trailing slash for MakeRelativeUri() below */);
foreach (var file in _folder.GetFiles("*", SearchOption.AllDirectories))
{
if (file.TryReadFile(out var stream))
using (var buffer = new MemoryStream())
{
var relResourcePath = baseUri.MakeRelativeUri(new Uri(file.Path)).ToString();
stream.CopyTo(buffer);
Log.Debug("Deserializing resource at {BasePath} - {Uri}", this.BasePath, relResourcePath);
result.Add(relResourcePath, buffer.ToArray());
}
}
if (result.Count > 0)
{
part = result;
return true;
}
else
{
part = null;
return false;
}
}
19
Source : UriExtensions.cs
with MIT License
from actions
with MIT License
from actions
public static string AbsoluteUri(this Uri uri)
{
return uri.IsAbsoluteUri ? uri.AbsoluteUri : uri.ToString();
}
19
Source : LocationHttpClient.cs
with MIT License
from actions
with MIT License
from actions
public async Task<ConnectionData> GetConnectionDataAsync(ConnectOptions connectOptions, Int64 lastChangeId, CancellationToken cancellationToken = default(CancellationToken), Object userState = null)
{
using (new OperationScope(LocationResourceIds.LocationServiceArea, "GetConnectionData"))
{
var uri = new Uri(PathUtility.Combine(BaseAddress.GetLeftPart(UriPartial.Path), connectSubUrl));
var uriBuilder = new UriBuilder(uri) { Query = BaseAddress.Query };
var query = new List<KeyValuePair<String, String>>
{
new KeyValuePair<String, String>("connectOptions", ((Int32)connectOptions).ToString(CultureInfo.InvariantCulture)),
new KeyValuePair<String, String>("lastChangeId", ((Int32)lastChangeId).ToString(CultureInfo.InvariantCulture)),
new KeyValuePair<String, String>("lastChangeId64", lastChangeId.ToString(CultureInfo.InvariantCulture))
};
uri = uriBuilder.Uri.AppendQuery(query);
var message = new HttpRequestMessage(HttpMethod.Get, uri.ToString());
message.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
return await SendAsync<ConnectionData>(message, userState, cancellationToken).ConfigureAwait(false);
}
}
19
Source : LocationCacheManager.cs
with MIT License
from actions
with MIT License
from actions
private void DetermineClientAndDefaultZones(String defaultAccessMappingMoniker)
{
Debug.replacedert(m_accessLock.IsWriteLockHeld);
m_defaultAccessMapping = null;
m_clientAccessMapping = null;
// For comparisons below we MUST use .ToString() here instead of .AbsoluteUri. .AbsoluteUri will return the path
// portion of the query string as encoded if it contains characters that are unicode, .ToString()
// will not return them encoded. We must not have them encoded so that the comparison below works
// correctly. Also, we do not need to worry about the downfalls of using ToString() instead of AbsoluteUri
// here because any urls that are generated with the generated access point will be placed back into a
// Uri object before they are used in a web request.
String relativeDirectoryTrimmed = (WebApplicationRelativeDirectory != null) ? WebApplicationRelativeDirectory.TrimEnd('/') : String.Empty;
foreach (AccessMapping accessMapping in m_accessMappings.Values)
{
if (VssStringComparer.ServerUrl.StartsWith(m_connectionBaseUrl.ToString(), accessMapping.AccessPoint.TrimEnd('/')) &&
(accessMapping.VirtualDirectory == null ||
VssStringComparer.UrlPath.Equals(accessMapping.VirtualDirectory, relativeDirectoryTrimmed)))
{
m_clientAccessMapping = accessMapping;
}
}
m_defaultAccessMapping = m_accessMappings[defaultAccessMappingMoniker];
if (m_clientAccessMapping == null)
{
String accessPoint = m_connectionBaseUrl.ToString().TrimEnd('/');
String virtualDirectory = String.Empty;
if (!String.IsNullOrEmpty(WebApplicationRelativeDirectory))
{
if (VssStringComparer.ServerUrl.EndsWith(accessPoint, relativeDirectoryTrimmed))
{
accessPoint = accessPoint.Substring(0, accessPoint.Length - relativeDirectoryTrimmed.Length);
virtualDirectory = relativeDirectoryTrimmed;
}
}
// Looks like we are in an unregistered zone, make up our own.
m_clientAccessMapping = new AccessMapping()
{
Moniker = accessPoint,
DisplayName = accessPoint,
AccessPoint = accessPoint,
VirtualDirectory = virtualDirectory
};
}
}
19
Source : MainControl.xaml.cs
with MIT License
from Actipro
with MIT License
from Actipro
private void UpdateUrlAndreplacedle(WebBrowser browser) {
try {
urlTextBox.Text = (browser.Source != null ? browser.Source.ToString() : string.Empty);
var window = (DoreplacedentWindow)browser.Parent;
window.replacedle = urlTextBox.Text;
window.FileName = urlTextBox.Text;
}
catch {}
}
19
Source : App.xaml.cs
with MIT License
from adenearnshaw
with MIT License
from adenearnshaw
protected override void OnAppLinkRequestReceived(System.Uri uri)
{
var shortcutId = uri.ToString().Replace(DeepLinkUriBase, "");
MainPage.Navigation.PushAsync(new AddShortcutPage(shortcutId));
//base.OnAppLinkRequestReceived(uri);
}
19
Source : App.xaml.cs
with MIT License
from adenearnshaw
with MIT License
from adenearnshaw
protected override void OnAppLinkRequestReceived(Uri uri)
{
var monkeyId = uri.ToString().Replace(AppShortcutUriBase, "");
var monkey = MonkeyStore.Instance.Monkeys.FirstOrDefault(m => m.Id.Equals(monkeyId));
if (monkey != null)
MainPage.Navigation.PushAsync(new DetailsPage(monkey));
else
base.OnAppLinkRequestReceived(uri);
}
19
Source : ObjectCacheExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static Dictionary<string, object> GetCacheFootprintJson(this ObjectCache cache, bool expanded, Uri requestUrl)
{
var alternateLink = new Uri(requestUrl.GetLeftPart(UriPartial.Path));
var enreplacedies = new List<Dictionary<string, object>>();
var footprint = GetCacheFootprint(cache, alternateLink);
foreach (var enreplacedyType in footprint)
{
var enreplacedy = new Dictionary<string, object>
{
{ "Name", enreplacedyType.Name },
{ "Count", enreplacedyType.GetCount() },
{ "Size", enreplacedyType.GetSize() }
};
if (expanded)
{
var records = new Collection<Dictionary<string, object>>();
foreach (var item in enreplacedyType.Items)
{
var record = new Dictionary<string, object>
{
{ "LogicalName", item.Enreplacedy.LogicalName },
{ "Name", item.Enreplacedy.GetAttributeValueOrDefault("adx_name", string.Empty) },
{ "Id", item.Enreplacedy.Id }
};
var recordCache = new Dictionary<string, object>
{
{ "Id", item.CacheItemKey },
{ "Type", item.CacheItemType },
{ "Link", item.Link.ToString() },
{ "Size", GetEnreplacedySizeInMemory(item.Enreplacedy) }
};
record.Add("Cache", recordCache);
records.Add(record);
}
enreplacedy.Add("Items", records);
}
enreplacedies.Add(enreplacedy);
}
var enreplacediesWrapper = new Dictionary<string, object>();
if (!expanded)
{
// Add link to the Expanded view with enreplacedy record details
var query = System.Web.HttpUtility.ParseQueryString(requestUrl.Query);
query[Web.Handlers.CacheFeedHandler.QueryKeys.Expanded] = bool.TrueString;
var uriBuilder = new UriBuilder(requestUrl.ToString()) { Query = query.ToString() };
enreplacediesWrapper.Add("ExpandedView", uriBuilder.ToString());
}
enreplacediesWrapper.Add("Enreplacedies", enreplacedies.OrderByDescending(e => e["Size"]));
var retval = new Dictionary<string, object> { { "CacheFootprint", enreplacediesWrapper } };
return retval;
}
19
Source : ObjectCacheExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static XmlDoreplacedent GetCacheFootprintXml(this ObjectCache cache, bool expanded, Uri requestUrl)
{
var alternateLink = new Uri(requestUrl.GetLeftPart(UriPartial.Path));
var doc = new XmlDoreplacedent();
var rootElement = doc.CreateElement("CacheFootprint");
var enreplacedyElements = new List<XmlElement>();
var footprint = GetCacheFootprint(cache, alternateLink);
foreach (var enreplacedyType in footprint)
{
var enreplacedyElement = doc.CreateElement("Enreplacedy");
enreplacedyElement.SetAttribute("Name", enreplacedyType.Name);
enreplacedyElement.SetAttribute("Count", enreplacedyType.GetCount().ToString());
enreplacedyElement.SetAttribute("Size", enreplacedyType.GetSize().ToString());
if (expanded)
{
foreach (var item in enreplacedyType.Items)
{
var itemElement = doc.CreateElement("Item");
itemElement.SetAttribute("LogicalName", item.Enreplacedy.LogicalName);
itemElement.SetAttribute("Name", item.Enreplacedy.GetAttributeValueOrDefault("adx_name", string.Empty));
itemElement.SetAttribute("Id", item.Enreplacedy.Id.ToString());
var cacheElement = doc.CreateElement("Cache");
cacheElement.SetAttribute("Id", item.CacheItemKey);
cacheElement.SetAttribute("Type", item.CacheItemType.ToString());
cacheElement.SetAttribute("Link", item.Link.ToString());
cacheElement.SetAttribute("Size", GetEnreplacedySizeInMemory(item.Enreplacedy).ToString());
itemElement.AppendChild(cacheElement);
enreplacedyElement.AppendChild(itemElement);
}
}
enreplacedyElements.Add(enreplacedyElement);
}
// Sort the enreplacedies by descending size
enreplacedyElements = enreplacedyElements.OrderByDescending(el => int.Parse(el.GetAttribute("Size"))).ToList();
var enreplacediesElement = doc.CreateElement("Enreplacedies");
foreach (var enreplacedyElement in enreplacedyElements)
{
enreplacediesElement.AppendChild(enreplacedyElement);
}
if (!expanded)
{
// Add link to the Expanded view with enreplacedy record details
var query = System.Web.HttpUtility.ParseQueryString(requestUrl.Query);
query[Web.Handlers.CacheFeedHandler.QueryKeys.Expanded] = bool.TrueString;
var uriBuilder = new UriBuilder(requestUrl.ToString()) { Query = query.ToString() };
var expandedView = doc.CreateElement("expandedView");
expandedView.InnerText = uriBuilder.ToString();
rootElement.AppendChild(expandedView);
}
rootElement.AppendChild(enreplacediesElement);
doc.AppendChild(rootElement);
return doc;
}
19
Source : SimpleHtmlFormatter.cs
with MIT License
from Adoxio
with MIT License
from 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
Source : OrganizationServiceContextExtensions.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static Enreplacedy GetSharePointSiteFromUrl(this OrganizationServiceContext context, Uri absoluteUrl)
{
var sharePointSites = context.CreateQuery("sharepointsite").Where(site => site.GetAttributeValue<int?>("statecode") == 0).ToArray(); // all active sites
var siteUrls = new Dictionary<Guid, string>();
foreach (var sharePointSite in sharePointSites)
{
var siteUrl = sharePointSite.GetAttributeValue<string>("absoluteurl") ?? string.Empty;
var parentSiteReference = sharePointSite.GetAttributeValue<EnreplacedyReference>("parentsite");
if (parentSiteReference != null)
{
var parentSite = sharePointSites.FirstOrDefault(site => site.Id == parentSiteReference.Id);
if (parentSite != null)
{
siteUrl = "{0}/{1}".FormatWith(parentSite.GetAttributeValue<string>("absoluteurl").TrimEnd('/'), sharePointSite.GetAttributeValue<string>("relativeurl"));
}
}
siteUrls.Add(sharePointSite.Id, siteUrl);
}
var siteKeyAndUrl = siteUrls.Select(pair => pair as KeyValuePair<Guid, string>?)
.FirstOrDefault(pair => string.Equals(pair.Value.Value.TrimEnd('/'), absoluteUrl.ToString().TrimEnd('/'), StringComparison.InvariantCultureIgnoreCase));
if (siteKeyAndUrl == null)
{
throw new ApplicationException("Couldn't find an active SharePoint site with the URL {0}.".FormatWith(absoluteUrl));
}
return sharePointSites.First(site => site.Id == siteKeyAndUrl.Value.Key);
}
19
Source : LocalFileSystem.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
private static string GetTemplateFileName(Uri rootUri, FileInfo file)
{
var fileUri = new Uri(Path.Combine(file.DirectoryName, Path.GetFileNameWithoutExtension(file.Name)));
return rootUri.MakeRelativeUri(fileUri).ToString();
}
19
Source : PackageRepositoryHelpers.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static string PackageInstallUrl(this HtmlHelper html, UrlHelper url, string packageUniqueName)
{
Guid websiteId;
Guid enreplacedyListId;
Guid viewId;
if (!TryGetRepositoryInfo(html, out websiteId, out enreplacedyListId, out viewId))
{
return null;
}
var href = url.Action("Index", "PackageRepository", new
{
__portalScopeId__ = websiteId,
enreplacedyListId,
viewId,
area = "EnreplacedyList"
});
if (string.IsNullOrEmpty(href))
{
return null;
}
var urlBuilder = new UrlBuilder(href)
{
Fragment = packageUniqueName
};
return new Uri("web+adxstudioinstaller:{0}".FormatWith(Uri.EscapeDataString(Uri.EscapeDataString(urlBuilder)))).ToString();
}
19
Source : PackageRepositoryHelpers.cs
with MIT License
from Adoxio
with MIT License
from Adoxio
public static string PackageRepositoryInstallUrl(this HtmlHelper html, UrlHelper url)
{
Guid websiteId;
Guid enreplacedyListId;
Guid viewId;
if (!TryGetRepositoryInfo(html, out websiteId, out enreplacedyListId, out viewId))
{
return null;
}
var href = url.Action("Index", "PackageRepository", new
{
__portalScopeId__ = websiteId,
enreplacedyListId,
viewId,
area = "EnreplacedyList"
});
if (string.IsNullOrEmpty(href))
{
return null;
}
var urlBuilder = new UrlBuilder(href);
return new Uri("web+adxstudioinstaller:{0}".FormatWith(Uri.EscapeDataString(Uri.EscapeDataString(urlBuilder)))).ToString();
}
19
Source : ExternalReviewStore.cs
with Apache License 2.0
from advanced-cms
with Apache License 2.0
from advanced-cms
private async Task<bool> SendMail(ExternalReviewLink externalReviewLink, string email, string subject,
string message)
{
var linkUrl = new Uri(_siteUriResolver.GetUri(externalReviewLink.ContentLink), externalReviewLink.LinkUrl);
message = message.Replace("[#link#]", linkUrl.ToString());
var providerNotificationMessages = new List<ProviderNotificationMessage>
{
new ProviderNotificationMessage
{
Content = message,
RecipientAddresses = new[] {email},
SenderAddress = _notificationOptions.NotificationEmailAddress,
Subject = subject,
SenderDisplayName = _notificationOptions.NotificationEmailDisplayName
}
};
var result = true;
await _emailNotificationProvider.SendAsync(providerNotificationMessages, msg => { result = true; },
(msg, exception) => { result = false; }).ConfigureAwait(true);
return result;
}
19
Source : TestUtils.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
public static IConfigurationRoot CreateApplicationConfiguration(HttpClient httpClient)
{
var appConfigurationDictionary = new Dictionary<string, string>
{
["AdministratorEmail"] = "[email protected]",
["ApiBaseUrl"] = new Uri(httpClient.BaseAddress, "api").ToString(),
["ProviderOptions:Authority"] = httpClient.BaseAddress.ToString(),
["ProviderOptions:ClientId"] = "theidserveradmin",
["ProviderOptions:DefaultScopes[0]"] = "openid",
["ProviderOptions:DefaultScopes[1]"] = "profile",
["ProviderOptions:DefaultScopes[2]"] = "theidserveradminapi",
["ProviderOptions:PostLogoutRedirectUri"] = new Uri(httpClient.BaseAddress, "authentication/logout-callback").ToString(),
["ProviderOptions:RedirectUri"] = new Uri(httpClient.BaseAddress, "authentication/login-callback").ToString(),
["ProviderOptions:ResponseType"] = "code",
["WelcomeContenUrl"] = "/welcome-fragment.html"
};
var appConfiguration = new ConfigurationBuilder().AddInMemoryCollection(appConfigurationDictionary).Build();
return appConfiguration;
}
19
Source : M3U8Downloader.cs
with MIT License
from aguang-xyz
with MIT License
from aguang-xyz
public async Task DownloadAsync(Uri uri, string fileName)
{
using var client = new HttpClient();
var content = await client.GetStringAsync(uri);
var lines = content
.AsLines()
.Select(line =>
{
if (string.IsNullOrWhiteSpace(line))
{
return line;
}
// Media encryption key may contain URI, see RFC8216 for more details.
// Link: https://datatracker.ietf.org/doc/html/rfc8216#section-4.3.2.4
if (line.StartsWith("#EXT-X-KEY:"))
{
var match = Regex.Match(line, "URI=\"([^\"]+)\"");
// Replace URI field if exists.
if (match.Groups.Count == 2)
{
var replacingUri = match.Groups[1].Value;
string replacedUri;
if (replacingUri.StartsWith("http:") || replacingUri.StartsWith("https:"))
{
replacedUri = replacingUri;
}
else
{
replacedUri = new Uri(uri, replacingUri).ToString();
}
line = line.Replace(replacingUri, ProxyService.GetProxyUrl(replacedUri));
}
return line;
}
if (line.StartsWith("#"))
{
return line;
}
if (!line.StartsWith("http:") && !line.StartsWith("https:"))
{
line = new Uri(uri, line).ToString();
}
return ProxyService.GetProxyUrl(line);
});
await File.WriteAllLinesAsync(fileName, lines);
}
19
Source : CarterUrlExtensions.cs
with MIT License
from ai-traders
with MIT License
from ai-traders
public static string AbsoluteUrl(this HttpRequest request, string relativePath)
{
return new Uri(new Uri(request.Scheme + "://" + request.Host.Value), relativePath).ToString();
}
19
Source : QueryUriBuilder.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public override string ToString() => this.Build().ToString();
19
Source : DiscordWebhookClient.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public Task<DiscordWebhook> AddWebhookAsync(Uri url)
{
if (url == null)
throw new ArgumentNullException(nameof(url));
var m = WebhookRegex.Match(url.ToString());
if (!m.Success)
throw new ArgumentException("Invalid webhook URL supplied.", nameof(url));
var idraw = m.Groups["id"];
var tokenraw = m.Groups["token"];
if (!ulong.TryParse(idraw.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var id))
throw new ArgumentException("Invalid webhook URL supplied.", nameof(url));
var token = tokenraw.Value;
return this.AddWebhookAsync(id, token);
}
19
Source : LavalinkRestClient.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public Task<LavalinkLoadResult> GetTracksAsync(Uri uri)
{
var str = WebUtility.UrlEncode(uri.ToString());
var tracksUri = new Uri($"{this.RestEndpoint.ToHttpString()}{Endpoints.LOAD_TRACKS}?identifier={str}");
return this.InternalResolveTracksAsync(tracksUri);
}
19
Source : BsonWriter.cs
with MIT License
from akaskela
with MIT License
from akaskela
public override void WriteValue(Uri value)
{
base.WriteValue(value);
AddToken(new BsonString(value.ToString(), true));
}
19
Source : JValue.cs
with MIT License
from akaskela
with MIT License
from akaskela
internal static int Compare(JTokenType valueType, object objA, object objB)
{
if (objA == null && objB == null)
{
return 0;
}
if (objA != null && objB == null)
{
return 1;
}
if (objA == null && objB != null)
{
return -1;
}
switch (valueType)
{
case JTokenType.Integer:
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
if (objA is BigInteger)
{
return CompareBigInteger((BigInteger)objA, objB);
}
if (objB is BigInteger)
{
return -CompareBigInteger((BigInteger)objB, objA);
}
#endif
if (objA is ulong || objB is ulong || objA is decimal || objB is decimal)
{
return Convert.ToDecimal(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToDecimal(objB, CultureInfo.InvariantCulture));
}
else if (objA is float || objB is float || objA is double || objB is double)
{
return CompareFloat(objA, objB);
}
else
{
return Convert.ToInt64(objA, CultureInfo.InvariantCulture).CompareTo(Convert.ToInt64(objB, CultureInfo.InvariantCulture));
}
case JTokenType.Float:
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
if (objA is BigInteger)
{
return CompareBigInteger((BigInteger)objA, objB);
}
if (objB is BigInteger)
{
return -CompareBigInteger((BigInteger)objB, objA);
}
#endif
return CompareFloat(objA, objB);
case JTokenType.Comment:
case JTokenType.String:
case JTokenType.Raw:
string s1 = Convert.ToString(objA, CultureInfo.InvariantCulture);
string s2 = Convert.ToString(objB, CultureInfo.InvariantCulture);
return string.CompareOrdinal(s1, s2);
case JTokenType.Boolean:
bool b1 = Convert.ToBoolean(objA, CultureInfo.InvariantCulture);
bool b2 = Convert.ToBoolean(objB, CultureInfo.InvariantCulture);
return b1.CompareTo(b2);
case JTokenType.Date:
#if !NET20
if (objA is DateTime)
{
#endif
DateTime date1 = (DateTime)objA;
DateTime date2;
#if !NET20
if (objB is DateTimeOffset)
{
date2 = ((DateTimeOffset)objB).DateTime;
}
else
#endif
{
date2 = Convert.ToDateTime(objB, CultureInfo.InvariantCulture);
}
return date1.CompareTo(date2);
#if !NET20
}
else
{
DateTimeOffset date1 = (DateTimeOffset)objA;
DateTimeOffset date2;
if (objB is DateTimeOffset)
{
date2 = (DateTimeOffset)objB;
}
else
{
date2 = new DateTimeOffset(Convert.ToDateTime(objB, CultureInfo.InvariantCulture));
}
return date1.CompareTo(date2);
}
#endif
case JTokenType.Bytes:
if (!(objB is byte[]))
{
throw new ArgumentException("Object must be of type byte[].");
}
byte[] bytes1 = objA as byte[];
byte[] bytes2 = objB as byte[];
if (bytes1 == null)
{
return -1;
}
if (bytes2 == null)
{
return 1;
}
return MiscellaneousUtils.ByteArrayCompare(bytes1, bytes2);
case JTokenType.Guid:
if (!(objB is Guid))
{
throw new ArgumentException("Object must be of type Guid.");
}
Guid guid1 = (Guid)objA;
Guid guid2 = (Guid)objB;
return guid1.CompareTo(guid2);
case JTokenType.Uri:
if (!(objB is Uri))
{
throw new ArgumentException("Object must be of type Uri.");
}
Uri uri1 = (Uri)objA;
Uri uri2 = (Uri)objB;
return Comparer<string>.Default.Compare(uri1.ToString(), uri2.ToString());
case JTokenType.TimeSpan:
if (!(objB is TimeSpan))
{
throw new ArgumentException("Object must be of type TimeSpan.");
}
TimeSpan ts1 = (TimeSpan)objA;
TimeSpan ts2 = (TimeSpan)objB;
return ts1.CompareTo(ts2);
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException("valueType", valueType, "Unexpected value type: {0}".FormatWith(CultureInfo.InvariantCulture, valueType));
}
}
19
Source : CustomProvider.cs
with MIT License
from Akinzekeel
with MIT License
from Akinzekeel
protected string GetRequestUrl(string BaseUrl, int Offset, int Length, string OrderBy, bool OrderByDescending, string SearchQuery)
{
var b = Http.BaseAddress;
var uri = new UriBuilder(
b.Scheme,
b.Host,
b.Port,
Path.Combine(b.LocalPath, BaseUrl)
);
var parameters = new BlazorGridRequest
{
Offset = Offset,
Length = Length,
OrderBy = OrderBy,
OrderByDescending = OrderByDescending,
Query = SearchQuery
};
uri.Query = parameters.ToQueryString();
return uri.Uri.ToString();
}
19
Source : GvrDevice.cs
with MIT License
from alanplotko
with MIT License
from alanplotko
public override bool SetDefaultDeviceProfile(System.Uri uri) {
byte[] profile = System.Text.Encoding.UTF8.GetBytes(uri.ToString());
return SetDefaultProfile(profile, profile.Length);
}
19
Source : NewVersion.cs
with MIT License
from AlbertMN
with MIT License
from AlbertMN
private void BrowserNavigating(object sender, WebBrowserNavigatingEventArgs e) {
if (!(e.Url.ToString().Equals("about:blank", StringComparison.InvariantCultureIgnoreCase))) {
Process.Start(e.Url.ToString());
e.Cancel = true;
return;
}
e.Cancel = true;
Process.Start(e.Url.ToString());
}
19
Source : GettingStarted.cs
with MIT License
from AlbertMN
with MIT License
from AlbertMN
private void BrowserNavigating(object sender, WebBrowserNavigatingEventArgs e) {
if (e.Url.ToString() == "#" || e.Url.ToString() == "about:blank") {
return;
}
if (!(e.Url.ToString().Equals("about:blank", StringComparison.InvariantCultureIgnoreCase))) {
//Process.Start(e.Url.ToString());
//e.Cancel = true;
//return;
}
}
19
Source : TileResource.cs
with MIT License
from alen-smajic
with MIT License
from alen-smajic
public string GetUrl()
{
var uriBuilder = new UriBuilder(_query);
if (uriBuilder.Query != null && uriBuilder.Query.Length > 1)
{
uriBuilder.Query = uriBuilder.Query.Substring(1);
}
//return uriBuilder.ToString();
return uriBuilder.Uri.ToString();
}
19
Source : KUdpProtocol.cs
with MIT License
from alethic
with MIT License
from alethic
public IKProtocolEndpoint<TNodeId> ResolveEndpoint(Uri uri)
{
var n = HttpUtility.ParseQueryString(uri.Query);
var a = n.Get("format").Split(',');
return uri.Scheme == "udp" ? CreateEndpoint(KIpEndpoint.Parse(uri.ToString()), a) : null;
}
See More Examples