Here are the examples of the csharp api System.Uri.UnescapeDataString(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
511 Examples
19
Source : NXMHandler.cs
with MIT License
from FelisDiligens
with MIT License
from FelisDiligens
public static NXMLink ParseLink(string nxmLink)
{
// nxm://fallout76/mods/<mod_id>/files/<file_id>?key=...&expires=1621492286&user_id=41275740
if (!nxmLink.StartsWith("nxm://"))
throw new ArgumentException("Invalid nxm link: " + nxmLink);
Uri uri = new Uri(nxmLink);
var query = uri.Query.Trim('?').Split('&')
.ToDictionary(c => c.Split('=')[0],
c => Uri.UnescapeDataString(c.Split('=')[1]));
NXMLink parsed = new NXMLink();
parsed.modId = Utils.ToInt(uri.Segments[2].Trim('/'));
parsed.fileId = Utils.ToInt(uri.Segments[4].Trim('/'));
parsed.key = query["key"];
parsed.expires = Utils.ToInt(query["expires"]);
return parsed;
}
19
Source : App.xaml.cs
with GNU General Public License v3.0
from files-community
with GNU General Public License v3.0
from files-community
protected override async void OnActivated(IActivatedEventArgs args)
{
await logWriter.InitializeAsync("debug.log");
Logger.Info($"App activated by {args.Kind.ToString()}");
await EnsureSettingsAndConfigurationAreBootstrapped();
var rootFrame = EnsureWindowIsInitialized();
switch (args.Kind)
{
case ActivationKind.Protocol:
var eventArgs = args as ProtocolActivatedEventArgs;
if (eventArgs.Uri.AbsoluteUri == "files-uwp:")
{
rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo());
}
else
{
var parsedArgs = eventArgs.Uri.Query.TrimStart('?').Split('=');
var unescapedValue = Uri.UnescapeDataString(parsedArgs[1]);
var folder = (StorageFolder)await FilesystemTasks.Wrap(() => StorageFolder.GetFolderFromPathAsync(unescapedValue).AsTask());
if (folder != null && !string.IsNullOrEmpty(folder.Path))
{
unescapedValue = folder.Path; // Convert short name to long name (#6190)
}
switch (parsedArgs[0])
{
case "tab":
rootFrame.Navigate(typeof(MainPage), TabItemArguments.Deserialize(unescapedValue), new SuppressNavigationTransitionInfo());
break;
case "folder":
rootFrame.Navigate(typeof(MainPage), unescapedValue, new SuppressNavigationTransitionInfo());
break;
}
}
// Ensure the current window is active.
Window.Current.Activate();
Window.Current.CoreWindow.Activated += CoreWindow_Activated;
return;
case ActivationKind.CommandLineLaunch:
var cmdLineArgs = args as CommandLineActivatedEventArgs;
var operation = cmdLineArgs.Operation;
var cmdLineString = operation.Arguments;
var activationPath = operation.CurrentDirectoryPath;
var parsedCommands = CommandLineParser.ParseUntrustedCommands(cmdLineString);
if (parsedCommands != null && parsedCommands.Count > 0)
{
async Task PerformNavigation(string payload, string selecreplacedem = null)
{
if (!string.IsNullOrEmpty(payload))
{
payload = CommonPaths.ShellPlaces.Get(payload.ToUpperInvariant(), payload);
var folder = (StorageFolder)await FilesystemTasks.Wrap(() => StorageFolder.GetFolderFromPathAsync(payload).AsTask());
if (folder != null && !string.IsNullOrEmpty(folder.Path))
{
payload = folder.Path; // Convert short name to long name (#6190)
}
}
var paneNavigationArgs = new PaneNavigationArguments
{
LeftPaneNavPathParam = payload,
LeftPaneSelecreplacedemParam = selecreplacedem,
};
if (rootFrame.Content != null)
{
await MainPageViewModel.AddNewTabByParam(typeof(PaneHolderPage), paneNavigationArgs);
}
else
{
rootFrame.Navigate(typeof(MainPage), paneNavigationArgs, new SuppressNavigationTransitionInfo());
}
}
foreach (var command in parsedCommands)
{
switch (command.Type)
{
case ParsedCommandType.OpenDirectory:
case ParsedCommandType.OpenPath:
case ParsedCommandType.ExplorerShellCommand:
var selecreplacedemCommand = parsedCommands.FirstOrDefault(x => x.Type == ParsedCommandType.Selecreplacedem);
await PerformNavigation(command.Payload, selecreplacedemCommand?.Payload);
break;
case ParsedCommandType.Selecreplacedem:
if (Path.IsPathRooted(command.Payload))
{
await PerformNavigation(Path.GetDirectoryName(command.Payload), Path.GetFileName(command.Payload));
}
break;
case ParsedCommandType.Unknown:
if (command.Payload.Equals("."))
{
await PerformNavigation(activationPath);
}
else
{
var target = Path.GetFullPath(Path.Combine(activationPath, command.Payload));
if (!string.IsNullOrEmpty(command.Payload))
{
await PerformNavigation(target);
}
else
{
await PerformNavigation(null);
}
}
break;
case ParsedCommandType.OutputPath:
OutputPath = command.Payload;
break;
}
}
if (rootFrame.Content != null)
{
// Ensure the current window is active.
Window.Current.Activate();
Window.Current.CoreWindow.Activated += CoreWindow_Activated;
return;
}
}
break;
case ActivationKind.ToastNotification:
var eventArgsForNotification = args as ToastNotificationActivatedEventArgs;
if (eventArgsForNotification.Argument == "report")
{
// Launch the URI and open log files location
//SettingsViewModel.OpenLogLocation();
SettingsViewModel.ReportIssueOnGitHub();
}
break;
}
rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo());
// Ensure the current window is active.
Window.Current.Activate();
Window.Current.CoreWindow.Activated += CoreWindow_Activated;
}
19
Source : UIHandlerAutomated.cs
with Apache License 2.0
from firebase
with Apache License 2.0
from firebase
Task TestCreateLongLinkAsync() {
Func<string, Dictionary<string, string>> extractUrlParams = (url) => {
var pattern = new Regex("[?&](?<name>[^=]+)=(?<value>[^&]+)");
var result = new Dictionary<string, string>();
foreach (Match m in pattern.Matches(url)) {
result.Add(m.Groups["name"].Value, m.Groups["value"].Value);
}
return result;
};
// This is taken from the values given in UIHandler.
var expected =
urlHost + "/?afl=https://mysite/fallback&" +
"amv=12&apn=com.google.FirebaseUnityDynamicLinksTestApp.dev&at=abcdefg&ct=hijklmno&" +
"ibi=com.google.FirebaseUnityDynamicLinksTestApp.dev&ifl=https://mysite/fallback&imv=1.2.3&" +
"ipbi=com.google.FirebaseUnityDynamicLinksTestApp.dev&" +
"ipfl=https://mysite/fallbackipad&ius=mycustomscheme&link=https://google.com/abc&" +
"pt=pq-rstuv&sd=My app is awesome!&si=https://mysite.com/someimage.jpg&st=My App!&" +
"utm_campaign=mycampaign&utm_content=mycontent&utm_medium=mymedium&utm_source=mysource&" +
"utm_term=myterm";
// The order of URL parameters is different between desktop and mobile implementations, and
// can't be relied upon.
var expectedParams = extractUrlParams(expected);
var source = new TaskCompletionSource<string>();
try {
var result = Uri.UnescapeDataString(CreateAndDisplayLongLink().ToString());
var resultHost = new Regex("/\\?").Split(result)[0];
var sameHost = resultHost == urlHost;
var resultParams = extractUrlParams(result);
var sameParams = expectedParams.Keys.All(k => resultParams.ContainsKey(k) &&
object.Equals(expectedParams[k], resultParams[k]));
if (sameHost && sameParams) {
source.TrySetResult(result);
} else {
List<string> differences = new List<string>();
differences.Add("The generated long link doesn't match the expected result.");
if (!sameHost) {
differences.Add(String.Format(
"Url Host:\n" +
" Expected: {0}\n" +
" Actual: {1}", urlHost, resultHost));
}
if (!sameParams) {
var diffParams = expectedParams.Keys.Where(k => !(resultParams.ContainsKey(k) &&
object.Equals(expectedParams[k], resultParams[k])));
foreach (var key in diffParams) {
differences.Add(String.Format(
"{0}: \n" +
" Expected: {1}\n" +
" Actual: {2}", key, expectedParams[key], resultParams[key]));
}
}
source.TrySetException(new Exception(String.Join("\n", differences.ToArray())));
}
} catch (Exception e) {
source.TrySetException(e);
}
return source.Task;
}
19
Source : UIHandler.cs
with Apache License 2.0
from firebase
with Apache License 2.0
from firebase
protected string FileUriStringToPath(string fileUriString) {
return Uri.UnescapeDataString((new Uri(fileUriString)).PathAndQuery);
}
19
Source : CustomSecurityManager.cs
with MIT License
from FlashpointProject
with MIT License
from FlashpointProject
int InternetInterfaces.IInternetSecurityManager.MapUrlToZone([MarshalAs(UnmanagedType.LPWStr)] string pwszUrl, ref uint pdwZone, uint dwFlags) {
// behave like local intranet
pdwZone = 1;
// don't map zone for file:// URLs, that's outside the proxy
if ((dwFlags & MUTZ_ISFILE) == MUTZ_ISFILE) {
return INET_E_DEFAULT_ACTION;
}
// error if URL is null
if (pwszUrl == null) {
return E_INVALIDARG;
}
// unescape URL if needed
if ((dwFlags & MUTZ_DONT_UNESCAPE) != MUTZ_DONT_UNESCAPE) {
try {
pwszUrl = Uri.UnescapeDataString(pwszUrl);
} catch (ArgumentNullException) {
// error if URL is null
return E_INVALIDARG;
}
}
pwszUrl = pwszUrl.ToLowerInvariant();
if (pwszUrl.IndexOf("http://") != 0 && pwszUrl.IndexOf("https://") != 0 && pwszUrl.IndexOf("ftp://") != 0) {
// we've wandered off from Flashpoint Server, revert to default zone settings
return INET_E_DEFAULT_ACTION;
}
return S_OK;
}
19
Source : CustomOAuth2Authenticator.cs
with MIT License
from folkehelseinstituttet
with MIT License
from folkehelseinstituttet
protected override void OnCreatingInitialUrl(IDictionary<string, string> query)
{
_redirectUrl = Uri.UnescapeDataString(query["redirect_uri"]);
_codeVerifier = CreateCodeVerifier();
query["response_type"] = "code";
query["nonce"] = Guid.NewGuid().ToString("N");
query["code_challenge"] = CreateChallenge(_codeVerifier);
query["code_challenge_method"] = "S256";
query["prompt"] = "login";
base.OnCreatingInitialUrl(query);
}
19
Source : SaveOutlookAttachementsDesigner.xaml.cs
with GNU General Public License v3.0
from FreeDemon2020
with GNU General Public License v3.0
from FreeDemon2020
private void LoadButton_Click(object sender, RoutedEventArgs e)
{
string currentDirectory = Directory.GetCurrentDirectory();
folderDialog.SelectedPath = currentDirectory;
if (folderDialog.ShowDialog() == DialogResult.OK && folderDialog.SelectedPath != null)
{
string text = folderDialog.SelectedPath;
if (text.ToLowerInvariant() == currentDirectory.ToLowerInvariant())
{
text = string.Empty;
}
else
{
try
{
Uri uri = new Uri(System.IO.Path.Combine(currentDirectory, System.IO.Path.PathSeparator.ToString()));
Uri uri2 = new Uri(folderDialog.SelectedPath);
if (uri.IsBaseOf(uri2))
{
text = Uri.UnescapeDataString(uri.MakeRelativeUri(uri2).OriginalString).Replace('/', System.IO.Path.DirectorySeparatorChar);
}
}
catch
{
}
}
base.ModelItem.Properties["FolderPath"].SetValue(new InArgument<string>(text));
}
}
19
Source : Common.cs
with GNU General Public License v3.0
from FreeDemon2020
with GNU General Public License v3.0
from FreeDemon2020
public static string MakeRelativePath(string baseDir, string filePath)
{
if (string.IsNullOrEmpty(baseDir)) throw new ArgumentNullException("baseDir");
if (string.IsNullOrEmpty(filePath)) throw new ArgumentNullException("filePath");
if (!baseDir.EndsWith(@"\") && !baseDir.EndsWith(@"/"))
{
baseDir += @"\";
}
Uri fromUri = new Uri(baseDir);
Uri toUri = new Uri(filePath);
if (fromUri.Scheme != toUri.Scheme) { return filePath; } // path can't be made relative.
Uri relativeUri = fromUri.MakeRelativeUri(toUri);
string relativePath = Uri.UnescapeDataString(relativeUri.ToString());
if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath;
}
19
Source : Common.cs
with GNU General Public License v3.0
from FreeDemon2020
with GNU General Public License v3.0
from FreeDemon2020
public static string MakeRelativePath(string baseDir, string filePath)
{
if (string.IsNullOrEmpty(baseDir)) throw new ArgumentNullException("baseDir");
if (string.IsNullOrEmpty(filePath)) throw new ArgumentNullException("filePath");
if(!baseDir.EndsWith(@"\") && !baseDir.EndsWith(@"/"))
{
baseDir += @"\";
}
Uri fromUri = new Uri(baseDir);
Uri toUri = new Uri(filePath);
if (fromUri.Scheme != toUri.Scheme) { return filePath; } // path can't be made relative.
Uri relativeUri = fromUri.MakeRelativeUri(toUri);
string relativePath = Uri.UnescapeDataString(relativeUri.ToString());
if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath;
}
19
Source : ParseNativePath.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
public static AbsoluteFilePath ToAbsoluteFilePath(this Uri uri)
{
return AbsoluteFilePath.Parse(Uri.UnescapeDataString(uri.AbsolutePath));
}
19
Source : ParseNativePath.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
public static AbsoluteDirectoryPath ToAbsoluteDirectoryPath(this Uri uri)
{
return AbsoluteDirectoryPath.Parse(Uri.UnescapeDataString(uri.LocalPath));
}
19
Source : NugetPackageElement.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
private string GetRelativePath(string filespec, string folder)
{
Uri pathUri = new Uri(filespec);
// Folders must end in a slash
if (!folder.EndsWith(Path.DirectorySeparatorChar.ToString()))
folder += Path.DirectorySeparatorChar;
Uri folderUri = new Uri(folder);
return
Uri.UnescapeDataString(
folderUri.MakeRelativeUri(pathUri).ToString().Replace(
'/',
Path.DirectorySeparatorChar));
}
19
Source : SolutionTestsHelper.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
public static string GetPhysicalLocation(this replacedembly replacedembly)
{
if (replacedembly == null)
throw new ArgumentNullException(nameof(replacedembly));
var replacedemblyPath = replacedembly.Location;
if (String.IsNullOrEmpty(replacedemblyPath))
{
var uri = new UriBuilder(replacedembly.CodeBase);
var unescapeDataString = Uri.UnescapeDataString(uri.Path);
replacedemblyPath = Path.GetFullPath(unescapeDataString);
}
return replacedemblyPath;
}
19
Source : Paths.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
public static string RelativeTo(this string toPath, string fromPath)
{
if (string.IsNullOrEmpty(fromPath)) throw new ArgumentNullException("fromPath");
if (string.IsNullOrEmpty(toPath)) throw new ArgumentNullException("toPath");
var fromUri = new Uri(fromPath);
var toUri = new Uri(toPath);
if (fromUri.Scheme != toUri.Scheme)
return toPath; // path can't be made relative.
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 : CommandRunner.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
private static string FindCommand()
{
var codeBase = replacedembly.GetExecutingreplacedembly().CodeBase;
var uri = new UriBuilder(codeBase);
var path = Uri.UnescapeDataString(uri.Path);
var replacedemblyDirectory = Path.GetDirectoryName(path);
return Path.Combine(replacedemblyDirectory, "Command.exe");
}
19
Source : UnoConfig.cs
with MIT License
from fuse-open
with MIT License
from fuse-open
public static string GetreplacedemblyDirectory(replacedembly asm)
{
if (asm == null)
return null;
var uri = new UriBuilder(asm.CodeBase);
var path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
19
Source : TransportHttp.cs
with MIT License
from getbucket
with MIT License
from getbucket
private void CaptureAuthentication(string uri)
{
var match = Regex.Match(uri, @"^https?://(?<user>[^:/]+):(?<preplaced>[^@/]+)@([^/]+)", RegexOptions.IgnoreCase);
if (!match.Success)
{
return;
}
var origin = BucketUri.GetOrigin(config, uri);
var username = match.Groups["user"].Value;
var preplacedword = match.Groups["preplaced"].Value;
io.SetAuthentication(origin, Uri.UnescapeDataString(username), Uri.UnescapeDataString(preplacedword));
}
19
Source : DownloaderVcs.cs
with MIT License
from getbucket
with MIT License
from getbucket
private string ProcessLocalSourceUri(string uri)
{
var needle = "file://";
var isFileProtocol = false;
if (uri.StartsWith(needle, StringComparison.Ordinal))
{
uri = uri.Substring(needle.Length);
isFileProtocol = true;
}
if (uri.Contains("%"))
{
uri = Uri.UnescapeDataString(uri);
}
uri = Path.GetFullPath(uri)
.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
// The source of protection must exist.
if (!FileSystem.Exists(uri, FileSystemOptions.Directory))
{
return string.Empty;
}
return isFileProtocol ? needle + uri : uri;
}
19
Source : PackUriUtils.cs
with MIT License
from gix
with MIT License
from gix
private static void GetreplacedemblyNameAndPart(
Uri uri, out replacedemblyName asmName, out string partName)
{
Debug.replacedert(uri != null && !uri.IsAbsoluteUri, "This method accepts relative uri only.");
string original = uri.ToString(); // only relative Uri here (enforced by Package)
// Start and end points for the first segment in the Uri.
int start = 0;
int end;
if (original[0] == '/')
start = 1;
asmName = null;
partName = original.Substring(start);
end = original.IndexOf('/', start);
string firstSegment = string.Empty;
bool hasComponent = false;
if (end > 0) {
firstSegment = original.Substring(start, end - start);
if (firstSegment.EndsWith(ComponentSuffix, StringComparison.OrdinalIgnoreCase)) {
partName = original.Substring(end + 1);
hasComponent = true;
}
}
if (!hasComponent)
return;
string[] replacedemblyInfo = firstSegment.Split(ComponentDelimiter);
int count = replacedemblyInfo.Length;
if (count < 2 || count > 4)
throw new UriFormatException(WrongFirstSegmentMessage);
// If the uri contains escaping character,
// Convert it back to normal unicode string
// so that the string as replacedembly name can be
// recognized by replacedembly.Load later.
string replacedemblyName = Uri.UnescapeDataString(replacedemblyInfo[0]);
string replacedemblyVersion = string.Empty;
string replacedemblyKey = string.Empty;
for (int i = 1; i < count - 1; ++i) {
if (replacedemblyInfo[i].StartsWith(VersionPrefix, StringComparison.OrdinalIgnoreCase)) {
if (!string.IsNullOrEmpty(replacedemblyVersion))
throw new UriFormatException(WrongFirstSegmentMessage);
replacedemblyVersion = replacedemblyInfo[i].Substring(1); // Get rid of the leading "v"
} else {
if (!string.IsNullOrEmpty(replacedemblyKey))
throw new UriFormatException(WrongFirstSegmentMessage);
replacedemblyKey = replacedemblyInfo[i];
}
}
if (!string.IsNullOrEmpty(replacedemblyName)) {
asmName = new replacedemblyName(replacedemblyName);
// We always use the primary replacedembly (culture neutral) for resource
// manager. If the required resource lives in a satellite replacedembly,
// ResourceManager can find the right satellite replacedembly later.
asmName.CultureInfo = new CultureInfo(string.Empty);
if (!string.IsNullOrEmpty(replacedemblyVersion))
asmName.Version = new Version(replacedemblyVersion);
if (!string.IsNullOrEmpty(replacedemblyKey)) {
int byteCount = replacedemblyKey.Length / 2;
byte[] keyToken = new byte[byteCount];
for (int i = 0; i < byteCount; ++i) {
string byteString = replacedemblyKey.Substring(i * 2, 2);
keyToken[i] = byte.Parse(byteString, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
asmName.SetPublicKeyToken(keyToken);
}
}
}
19
Source : DataKeyword.cs
with MIT License
from gregsdennis
with MIT License
from gregsdennis
private static string SimpleDownload(Uri uri)
{
switch (uri.Scheme)
{
case "http":
case "https":
return new HttpClient().GetStringAsync(uri).Result;
case "file":
var filename = Uri.UnescapeDataString(uri.AbsolutePath);
return File.ReadAllText(filename);
default:
throw new Exception($"URI scheme '{uri.Scheme}' is not supported. Only HTTP(S) and local file system URIs are allowed.");
}
}
19
Source : Common.cs
with MIT License
from GridProtectionAlliance
with MIT License
from GridProtectionAlliance
public static string GetRelativePathTo(this FileSystemInfo from, FileSystemInfo to)
{
string getPath(FileSystemInfo fsi) => fsi is not DirectoryInfo d ? fsi.FullName : AddPathSuffix(d.FullName);
string fromPath = getPath(from);
string toPath = getPath(to);
Uri fromUri = new Uri(fromPath);
Uri toUri = new Uri(toPath);
Uri relativeUri = fromUri.MakeRelativeUri(toUri);
string relativePath = Uri.UnescapeDataString(relativeUri.ToString());
return relativePath.Replace('/', Path.DirectorySeparatorChar);
}
19
Source : GrpcProtocolHelpers.cs
with Apache License 2.0
from grpc
with Apache License 2.0
from grpc
public static bool TryGetStatusCore(HttpHeaders headers, [NotNullWhen(true)]out Status? status)
{
var grpcStatus = GetHeaderValue(headers, GrpcProtocolConstants.StatusTrailer);
// grpc-status is a required trailer
if (grpcStatus == null)
{
status = null;
return false;
}
int statusValue;
if (!int.TryParse(grpcStatus, out statusValue))
{
throw new InvalidOperationException("Unexpected grpc-status value: " + grpcStatus);
}
// grpc-message is optional
// Always read the gRPC message from the same headers collection as the status
var grpcMessage = GetHeaderValue(headers, GrpcProtocolConstants.MessageTrailer);
if (!string.IsNullOrEmpty(grpcMessage))
{
// https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#responses
// The value portion of Status-Message is conceptually a Unicode string description of the error,
// physically encoded as UTF-8 followed by percent-encoding.
grpcMessage = Uri.UnescapeDataString(grpcMessage);
}
status = new Status((StatusCode)statusValue, grpcMessage);
return true;
}
19
Source : PercentEncodingHelpersTests.cs
with Apache License 2.0
from grpc
with Apache License 2.0
from grpc
[TestCaseSource(nameof(ValidPercentEncodingTestCases))]
public void DecodeMessageTrailer(string expectedDecodedValue, string value)
{
// Arrange & Act
var decodedValue = Uri.UnescapeDataString(value);
// replacedert
replacedert.AreEqual(expectedDecodedValue, decodedValue);
}
19
Source : PercentEncodingHelpersTests.cs
with Apache License 2.0
from grpc
with Apache License 2.0
from grpc
[Test]
public void StartOfHeaderChar_Roundtrip_Success()
{
// Arrange & Act
var encodedValue = PercentEncodingHelpers.PercentEncode("\x01");
var decodedValue = Uri.UnescapeDataString("%01");
// replacedert
replacedert.AreEqual("%01", encodedValue);
replacedert.AreEqual("\x01", decodedValue);
}
19
Source : PercentEncodingHelpersTests.cs
with Apache License 2.0
from grpc
with Apache License 2.0
from grpc
[Test]
public void ShiftInChar_Roundtrip_Success()
{
// Arrange & Act
var encodedValue = PercentEncodingHelpers.PercentEncode("\x0f");
var decodedValue = Uri.UnescapeDataString("%0F");
// replacedert
replacedert.AreEqual("%0F", encodedValue);
replacedert.AreEqual("\x0f", decodedValue);
}
19
Source : PercentEncodingHelpersTests.cs
with Apache License 2.0
from grpc
with Apache License 2.0
from grpc
[TestCase("%", "%")]
[TestCase("%A", "%A")]
[TestCase("%A%", "%A%")]
[TestCase("%AG", "%AG")]
[TestCase("%G0", "%G0")]
[TestCase("H%6", "H%6")]
[TestCase("\0", "\0")]
public void DecodeInvalidMessageTrailer(string expectedDecodedValue, string value)
{
// Arrange & Act
var decodedValue = Uri.UnescapeDataString(value);
// replacedert
replacedert.AreEqual(expectedDecodedValue, decodedValue);
}
19
Source : PercentEncodingHelpersTests.cs
with Apache License 2.0
from grpc
with Apache License 2.0
from grpc
[Test]
public void PercentEncode_TrailingHighSurrogate_SurrogatePairCorrectlyEncoded()
{
// Arrange
var originalText = "unmatchedLowSurrogate " + new string('£', PercentEncodingHelpers.MaxUnicodeCharsReallocate - 2) + "😀";
// Act
var escaped = PercentEncodingHelpers.PercentEncode(originalText);
// replacedert
replacedert.IsTrue(escaped.EndsWith("%F0%9F%98%80"), escaped);
replacedert.AreEqual(originalText, Uri.UnescapeDataString(escaped));
}
19
Source : Program.cs
with MIT License
from health-validator
with MIT License
from health-validator
public bool LoadResourceFile(string text)
{
if (text == null)
{
Console.Error.WriteLine("LoadResourceFile: no text preplaceded");
return false;
}
// input already pruned - accept as-is
if (!text.StartsWith("file://", StringComparison.InvariantCulture))
{
ResourceText = text;
return true;
}
var filePath = text;
// Windows can use three leading slashes, while others can use two
// examples load with just two on windows as well - so simpler to
// try both variants
filePath = filePath.RemovePrefix("file:///");
filePath = filePath.RemovePrefix("file://");
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) {
filePath = filePath.Prepend("/");
}
filePath = filePath.Replace("\r", "", StringComparison.InvariantCulture)
.Replace("\n", "", StringComparison.InvariantCulture);
filePath = Uri.UnescapeDataString(filePath);
Console.WriteLine($"Loading '{filePath}'...");
if (!File.Exists(filePath))
{
Console.WriteLine($"File to load doesn't actually exist: {filePath}");
return false;
}
ResourceText = File.ReadAllText(filePath);
if (ScopeDirectory == null)
{
ScopeDirectory = Path.GetDirectoryName(filePath);
}
return true;
}
19
Source : Program.cs
with MIT License
from health-validator
with MIT License
from health-validator
public void LoadScopeDirectory(string text)
{
// input already pruned - accept as-is
if (!text.StartsWith("file://", StringComparison.InvariantCulture))
{
ScopeDirectory = text;
return;
}
var filePath = text;
filePath = filePath.RemovePrefix(RuntimeInformation
.IsOSPlatform(OSPlatform.Windows) ? "file:///" : "file://");
filePath = filePath.Replace("\r", "", StringComparison.InvariantCulture)
.Replace("\n", "", StringComparison.InvariantCulture);
filePath = Uri.UnescapeDataString(filePath);
ScopeDirectory = filePath;
}
19
Source : TopUtils.cs
with MIT License
from hechenqingyuan
with MIT License
from hechenqingyuan
public static bool VerifyTopResponse(string callbackUrl, string appSecret)
{
Uri uri = new Uri(callbackUrl);
string query = uri.Query;
if (string.IsNullOrEmpty(query)) // 没有回调参数
{
return false;
}
query = query.Trim(new char[] { '?', ' ' });
if (query.Length == 0) // 没有回调参数
{
return false;
}
IDictionary<string, string> queryDict = SplitUrlQuery(query);
string topParams;
queryDict.TryGetValue("top_parameters", out topParams);
string topSession;
queryDict.TryGetValue("top_session", out topSession);
string topSign;
queryDict.TryGetValue("top_sign", out topSign);
string appKey;
queryDict.TryGetValue("top_appkey", out appKey);
topSign = (topSign == null ? null : Uri.UnescapeDataString(topSign));
return VerifyTopResponse(topParams, topSession, topSign, appKey, appSecret);
}
19
Source : TopUtils.cs
with MIT License
from hechenqingyuan
with MIT License
from hechenqingyuan
public static IDictionary<string, string> DecodeTopParams(string topParams, Encoding encoding)
{
if (string.IsNullOrEmpty(topParams))
{
return null;
}
byte[] buffer = Convert.FromBase64String(Uri.UnescapeDataString(topParams));
string originTopParams = encoding.GetString(buffer);
return SplitUrlQuery(originTopParams);
}
19
Source : AssetUtility.cs
with MIT License
from Hello-Meow
with MIT License
from Hello-Meow
public static string GetRelativePath(string path)
{
string currentDirectory = Directory.GetCurrentDirectory();
Uri pathUri = new Uri(path);
if (!currentDirectory.EndsWith(Path.DirectorySeparatorChar.ToString()))
currentDirectory += Path.DirectorySeparatorChar;
Uri directoryUri = new Uri(currentDirectory);
string relativePath = Uri.UnescapeDataString(directoryUri.MakeRelativeUri(pathUri).ToString().Replace('/', Path.DirectorySeparatorChar));
return relativePath;
}
19
Source : SupportingDocument.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
public FileInfo GetFileName()
{
if (URL == null || string.IsNullOrWhiteSpace(URL.AbsoluteUri) || !URL.IsFile)
return null;
var unescaped = Uri.UnescapeDataString(URL.AbsolutePath);
if (URL.IsUnc)
{
return new FileInfo(@"\\" + URL.Host + unescaped);
}
return new FileInfo(unescaped);
}
19
Source : BackblazeB2Client.cs
with MIT License
from HighEncryption
with MIT License
from HighEncryption
private static string UrlDecode(string str)
{
if (str == "+")
{
return " ";
}
return Uri.UnescapeDataString(str);
}
19
Source : SupportingDocument.cs
with GNU General Public License v3.0
from HicServices
with GNU General Public License v3.0
from HicServices
public FileInfo GetFileName()
{
if (URL == null || string.IsNullOrWhiteSpace(URL.AbsoluteUri) || !URL.IsFile)
return null;
return new FileInfo(Uri.UnescapeDataString(URL.AbsolutePath));
}
19
Source : Utils.cs
with MIT License
from hiloteam
with MIT License
from hiloteam
public static string MakeRelativePath(string fromPath, string toPath)
{
if (string.IsNullOrEmpty(fromPath)) throw new ArgumentNullException(nameof(fromPath));
if (string.IsNullOrEmpty(toPath)) throw new ArgumentNullException(nameof(toPath));
Uri fromUri = new Uri(fromPath + "/a.txt");
Uri toUri = new Uri(toPath);
if (fromUri.Scheme != toUri.Scheme) { return toPath; } // path can't be made relative.
Uri relativeUri = fromUri.MakeRelativeUri(toUri);
string relativePath = Uri.UnescapeDataString(relativeUri.ToString()).Replace("/a.txt", "");
if (toUri.Scheme.Equals("file", StringComparison.InvariantCultureIgnoreCase))
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath;
}
19
Source : StringExtensionMethods.cs
with GNU General Public License v3.0
from hitchhiker
with GNU General Public License v3.0
from hitchhiker
public static string ToUnEscapeJavascript(this string str)
{
if (string.IsNullOrWhiteSpace(str))
return str;
return Uri.UnescapeDataString(str);
}
19
Source : BeatmapConversionTest.cs
with MIT License
from hornyyy
with MIT License
from hornyyy
private Stream openResource(string name)
{
var localPath = Path.GetDirectoryName(Uri.UnescapeDataString(new UriBuilder(replacedembly.GetExecutingreplacedembly().CodeBase).Path));
return replacedembly.LoadFrom(Path.Combine(localPath, $"{Resourcereplacedembly}.dll")).GetManifestResourceStream($@"{Resourcereplacedembly}.Resources.{name}");
}
19
Source : ConnectionFactory.cs
with MIT License
from houseofcat
with MIT License
from houseofcat
private static string UriDecode(string uri)
{
return System.Uri.UnescapeDataString(uri.Replace("+", "%2B"));
}
19
Source : ImageLoadHandler.cs
with MIT License
from huali20040714
with MIT License
from huali20040714
private RImage GetImageFromData(string src)
{
var s = src.Substring(src.IndexOf(':') + 1).Split(new[] { ',' }, 2);
if (s.Length == 2)
{
int imagePartsCount = 0, base64PartsCount = 0;
foreach (var part in s[0].Split(new[] { ';' }))
{
var pPart = part.Trim();
if (pPart.StartsWith("image/", StringComparison.InvariantCultureIgnoreCase))
imagePartsCount++;
if (pPart.Equals("base64", StringComparison.InvariantCultureIgnoreCase))
base64PartsCount++;
}
if (imagePartsCount > 0)
{
byte[] imageData = base64PartsCount > 0 ? Convert.FromBase64String(s[1].Trim()) : new UTF8Encoding().GetBytes(Uri.UnescapeDataString(s[1].Trim()));
return _htmlContainer.Adapter.ImageFromStream(new MemoryStream(imageData));
}
}
return null;
}
19
Source : BaseHeader.cs
with MIT License
from huali20040714
with MIT License
from huali20040714
protected NameValueCollection GetRequestParams(string content)
{
var nv = new NameValueCollection();
//防御编程
if (string.IsNullOrEmpty(content))
return nv;
//按照&对字符进行分割
string[] reval = content.Split('&');
if (reval.Length <= 0)
return nv;
//将结果添加至字典
foreach (string val in reval)
{
string[] kv = val.Split(new char[] { '=' }, StringSplitOptions.RemoveEmptyEntries);
if (kv.Length != 2)
continue;
nv.Add(kv[0], Uri.UnescapeDataString(kv[1]));
}
//返回字典
return nv;
}
19
Source : Utilities.cs
with MIT License
from HughesMDflyer4
with MIT License
from HughesMDflyer4
public static string GetRelativePath(string fullPath, string basePath)
{
if (!basePath.EndsWith("\\"))
basePath += "\\";
Uri baseUri = new Uri(basePath);
Uri fullUri = new Uri(fullPath);
Uri relativeUri = baseUri.MakeRelativeUri(fullUri);
return Uri.UnescapeDataString(relativeUri.ToString());
}
19
Source : PackageDownloadManager.cs
with Mozilla Public License 2.0
from HuiDesktop
with Mozilla Public License 2.0
from HuiDesktop
static public object CheckType(string[] args)
{
if (args.Length == 2 && args[1] == "--autorun")
{
return new AutoRunRequest();
}
if (args.Length < 3 || args[1] != "--hdt-url")
{
return null;
}
var uri = new Uri(string.Join(" ", args.Skip(2).ToArray()));
switch (uri.Host)
{
case "download-module":
if (uri.AbsolutePath.Length == 1)
{
throw new FormatException("Path argument is not given for download-module");
}
if (uri.Query.Length <= 1)
{
throw new FormatException("Name argument is not given for download-module");
}
return new DownloadModuleRequest(uri.AbsolutePath.Substring(1), Uri.UnescapeDataString(uri.Query.Substring(1)));
case "create-sandbox":
var p = System.Web.HttpUtility.ParseQueryString(uri.Query.Substring(1));
var names = new Dictionary<int, string>();
var contents = new Dictionary<int, object>();
foreach (var i in p.AllKeys)
{
if (i.StartsWith("filename-"))
{
names.Add(Convert.ToInt32(i.Substring("filename-".Length)), p.Get(i));
}
else if (i.StartsWith("content-"))
{
var pos = i.IndexOf('-', "content-".Length);
if (pos != -1)
{
var id = Convert.ToInt32(i.Substring("content-".Length, pos - "content-".Length));
if (i.EndsWith("-string"))
{
contents[id] = p.Get(i);
}
else
{
contents[id] = Convert.FromBase64String(p.Get(i));
}
}
}
}
var fs = new List<(string, object)>();
foreach (var i in names)
{
if (contents.ContainsKey(i.Key))
{
fs.Add((i.Value, contents[i.Key]));
}
}
return new CreateSandboxRequest(p.Get("sandboxName"), fs, p.Get("recommendation"));
default:
return null;
}
}
19
Source : MessageDecoder.cs
with Apache License 2.0
from hyperledger
with Apache License 2.0
from hyperledger
public static async Task<AgentMessage> ParseMessageAsync(string value)
{
string messageDecoded = null;
if (value.StartsWith("http", StringComparison.OrdinalIgnoreCase)
|| value.StartsWith("https", StringComparison.OrdinalIgnoreCase)
|| value.StartsWith("didcomm", StringComparison.OrdinalIgnoreCase))
{
var url = new Uri(value);
var query = QueryHelpers.ParseQuery(url.Query);
if (query.TryGetValue("c_i", out var messageEncoded) ||
query.TryGetValue("d_m", out messageEncoded) ||
query.TryGetValue("m", out messageEncoded))
{
messageDecoded = Uri.UnescapeDataString(messageEncoded);
}
else
{
var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
var response = await client.GetAsync(value);
var invitationUri = response.Headers.Location;
query = QueryHelpers.ParseNullableQuery(invitationUri.Query);
if (query.TryGetValue("c_i", out messageEncoded) ||
query.TryGetValue("d_m", out messageEncoded) ||
query.TryGetValue("m", out messageEncoded))
{
messageDecoded = Uri.UnescapeDataString(messageEncoded);
}
}
}
else
{
messageDecoded = Uri.UnescapeDataString(value);
}
// Because the decoder above strips the +
// https://github.com/aspnet/HttpAbstractions/blob/bc7092a32b1943c7f17439e419d3f66cd94ce9bd/src/Microsoft.AspNetCore.WebUtilities/QueryHelpers.cs#L165
messageDecoded = messageDecoded.Replace(' ', '+');
var json = messageDecoded.GetBytesFromBase64().GetUTF8String();
var unpackedMessage = new UnpackedMessageContext(json, senderVerkey: null);
switch (unpackedMessage.GetMessageType())
{
case MessageTypes.ConnectionInvitation:
return unpackedMessage.GetMessage<ConnectionInvitationMessage>();
//case MessageTypes.EphemeralChallenge:
// return unpackedMessage.GetMessage<EphemeralChallengeMessage>();
case MessageTypes.PresentProofNames.RequestPresentation:
return unpackedMessage.GetMessage<RequestPresentationMessage>();
case MessageTypes.IssueCredentialNames.OfferCredential:
return unpackedMessage.GetMessage<CredentialOfferMessage>();
}
return null;
}
19
Source : MessageDecoder.cs
with Apache License 2.0
from hyperledger
with Apache License 2.0
from hyperledger
public static async Task<AgentMessage> ParseMessageAsync(string value)
{
string messageDecoded = null;
if (value.StartsWith("http", StringComparison.OrdinalIgnoreCase)
|| value.StartsWith("https", StringComparison.OrdinalIgnoreCase)
|| value.StartsWith("didcomm", StringComparison.OrdinalIgnoreCase))
{
var url = new Uri(value);
var query = QueryHelpers.ParseQuery(url.Query);
if (query.TryGetValue("c_i", out var messageEncoded) ||
query.TryGetValue("d_m", out messageEncoded) ||
query.TryGetValue("m", out messageEncoded))
{
messageDecoded = Uri.UnescapeDataString(messageEncoded);
}
else
{
var client = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false });
var response = await client.GetAsync(value);
var invitationUri = response.Headers.Location;
query = QueryHelpers.ParseNullableQuery(invitationUri.Query);
if (query.TryGetValue("c_i", out messageEncoded) ||
query.TryGetValue("d_m", out messageEncoded) ||
query.TryGetValue("m", out messageEncoded))
{
messageDecoded = Uri.UnescapeDataString(messageEncoded);
}
}
}
else
{
messageDecoded = Uri.UnescapeDataString(value);
}
// Because the decoder above strips the +
// https://github.com/aspnet/HttpAbstractions/blob/bc7092a32b1943c7f17439e419d3f66cd94ce9bd/src/Microsoft.AspNetCore.WebUtilities/QueryHelpers.cs#L165
messageDecoded = messageDecoded.Replace(' ', '+');
var json = messageDecoded.GetBytesFromBase64().GetUTF8String();
var unpackedMessage = new UnpackedMessageContext(json, senderVerkey: null);
switch (unpackedMessage.GetMessageType())
{
case MessageTypes.ConnectionInvitation:
return unpackedMessage.GetMessage<ConnectionInvitationMessage>();
//case MessageTypes.EphemeralChallenge:
// return unpackedMessage.GetMessage<EphemeralChallengeMessage>();
case MessageTypes.PresentProofNames.RequestPresentation:
return unpackedMessage.GetMessage<RequestPresentationMessage>();
case MessageTypes.IssueCredentialNames.OfferCredential:
return unpackedMessage.GetMessage<CredentialOfferMessage>();
}
return null;
}
19
Source : PathConverter.cs
with MIT License
from icsharpcode
with MIT License
from icsharpcode
public static string GetRelativePath(string relativeTo, string path)
{
var uri = new Uri(relativeTo);
var rel = Uri.UnescapeDataString(uri.MakeRelativeUri(new Uri(path)).ToString()).Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
return rel;
}
19
Source : Program.cs
with MIT License
from IllusionMods
with MIT License
from IllusionMods
private static string GetRelativePath(string fromPath, string toPath)
{
if (string.IsNullOrEmpty(fromPath)) throw new ArgumentNullException(nameof(fromPath));
if (string.IsNullOrEmpty(toPath)) throw new ArgumentNullException(nameof(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 (string.Equals(toUri.Scheme, Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase))
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath;
}
19
Source : FileSaver.cs
with MIT License
from immersivecognition
with MIT License
from immersivecognition
public static string GetRelativePath(string relativeToDirectory, string path)
{
relativeToDirectory = Path.GetFullPath(relativeToDirectory);
if (!relativeToDirectory.EndsWith("\\")) relativeToDirectory += "\\";
path = Path.GetFullPath(path);
Uri path1 = new Uri(relativeToDirectory);
Uri path2 = new Uri(path);
Uri diff = path1.MakeRelativeUri(path2);
return Uri.UnescapeDataString(diff.OriginalString);
}
19
Source : State.cs
with MIT License
from intelequia
with MIT License
from intelequia
public void ParseState(string s)
{
if (string.IsNullOrEmpty(s))
return;
var pairs = s.Split(';');
foreach (var pair in pairs)
{
var item = pair.Split('=');
if (item.Length == 2)
{
switch (item[0])
{
case "s":
Service = item[1];
break;
case "p":
PortalId = int.Parse(item[1]);
break;
case "c":
Culture = item[1];
break;
case "r":
RedirectUrl = Uri.UnescapeDataString(item[1]);
break;
case "up":
IsUserProfile = item[1] == "1";
break;
case "i":
IsImpersonate = item[1] == "1";
break;
default:
break;
}
}
}
}
19
Source : FileGenerator.cs
with Apache License 2.0
from IntelliTect
with Apache License 2.0
from IntelliTect
public override async Task GenerateAsync()
{
if (IsDisabled)
{
Logger?.LogDebug($"Skipped gen of {this}, generator disabled");
return;
}
if (!ShouldGenerate())
{
Logger?.LogDebug($"Skipped gen of {this}, {nameof(ShouldGenerate)} returned false");
return;
}
// Start reading the existing output file while we generate the contents.
string outputFile = EffectiveOutputPath;
var outputExistingContents = Task.Run(() =>
{
// Throw the creation of the directory on this thread too for max parallelization.
Directory.CreateDirectory(Path.GetDirectoryName(outputFile));
if (File.Exists(outputFile))
{
return File.ReadAllText(outputFile);
}
else
{
return String.Empty;
}
});
using (var contents = await GetOutputAsync().ConfigureAwait(false))
{
Logger?.LogTrace($"Got output for {this}");
if (!(await FileUtilities.HasDifferencesAsync(contents, await outputExistingContents)))
{
Logger?.LogTrace($"Skipped write of {this}, existing file wasn't different");
return;
}
var isRegen = File.Exists(outputFile);
using (FileStream fileStream = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
{
contents.Seek(0, SeekOrigin.Begin);
await contents.CopyToAsync(fileStream).ConfigureAwait(false);
await fileStream.FlushAsync();
Uri relPath = new Uri(Environment.CurrentDirectory + Path.DirectorySeparatorChar).MakeRelativeUri(new Uri(outputFile));
Logger?.LogInformation($"{(isRegen ? "Reg" : "G")}enerated: {Uri.UnescapeDataString(relPath.OriginalString)}");
};
}
}
See More Examples