String.Replace for Path and Url - string

I have a problem about path string data. I have a string columb in Database and keep path in this columb.Like this;
D:\SCANNEDDOCUMENTS\2\3C9DED0628F44190ABF92D3C14F14A14-2-D.pdf
In my project i'll reach documents on IIS.I config all settings for IIS. And I need an Url like this;
HTTP://LOCALHOST/SCANNEDDOCUMENTS/2/3C9DED0628F44190ABF92D3C14F14A14-2-D.pdf
And i don't want to change paths in database.They're original local path.Only i need change on viewmodel. So need replace first path to second Url. And when i get path value from database i saw that:
D:\\SCANNEDDOCUMENTS\\2\\3C9DED0628F44190ABF92D3C14F14A14-2-D.pdf
There is double backslash? Why? And how can replace this like my wanted Url?
I tried several thing like;
private static string ReplaceDocumentPathLocalToWeb(string path)
{
if (!string.IsNullOrEmpty(path))
{
SArchiveModule archivingModule = ContainerManager.Container.GetInstance<SArchiveModule>();
SbtGeneralParameterModel parameter = archivingModule.GetGeneralParameters();
string docDirectory = parameter.DocumentDirectoryPath;
string docWebDirectory = parameter.DocumentWebRootPath + #"/" + parameter.DocumentWebFolderPath;
path.Replace(docDirectory, docWebDirectory);
path.Replace("\"", "/");
if (path.StartsWith(#"/"))
{
path.TrimStart(new char[] { '/' });
}
if (path.EndsWith(#"/"))
{
path.TrimEnd(new char[] { '/' });
}
}
return path;
}
path="D:\SCANNEDDOCUMENTS\2\3C9DED0628F44190ABF92D3C14F14A14-2-D.pdf";
parameters from database too;
docDirectory="D:\SCANNEDDOCUMENTS"
docWebDirectory="HTTP://LOCALHOST/SCANNEDDOCUMENTS"
But this code is not working too:
path.Replace(docDirectory, docWebDirectory);
What should i do for replace? And why my data came with double backslash? In database it's with one backslash?

So sorry my wrong. Now i got the problem. I couldn't see the string.replace result 'cause i need use code like:
path=path.Replace(docDirectory, docWebDirectory);
path=path.Replace("\"", "/");
if (path.StartsWith(#"/"))
{
path=path.TrimStart(new char[] { '/' });
}
if (path.EndsWith(#"/"))
{
path=enter code here`path.TrimEnd(new char[] { '/' });
}
It's really silly mistake...

Related

How can nestjs recognize two path?

I have created the following two APIs.
However, when I hit "http://localhost:3000/arg1/arg2", it is recognized, but
But "http://localhost:3000/show/config" is not recognized.
How can I make "show/config" URL Mapping?
#Get(':arg1/:arg2')
pathMappingTest(): string {
return 'pathMappingTest';
}
#Get('show/config')
showConfig(): string {
return this.appService.showConfig();
}
try set :arg/:otherArg for the last, because if you put anything with two arg with slash between, the API will know it is two args.
#Get('show/config')
showConfig(): string {
return this.appService.showConfig();
}
#Get(':arg1/:arg2')
pathMappingTest(): string {
return 'pathMappingTest';
}

Is there a regex to be able to match two url's , one that has a wildcard and one that doesn't?

I am writing a program in Nodejs with the following scenarios.
I have an array of url's that include wildcards, such as the following:
https://*.example.com/example/login
http://www.example2.com/*/example2/callback
Secondly, I have an incoming redirect url that I need to validate matches what is in the array of url's above. I was wondering if there was a way using Regex or anything else that I can use something like arr.includes(incomingRedirectUrl) and compare the two.
I can match non-wildcard url's using array.includes(incomingRedirectUrl), but when it comes to matching the array that has wildcards, I cannot think of a solution.
For example,
https://x.example.com/example/login should work because it matches the first url in the above example, only replacing the "*" with the x.
Is there a way I can achieve this? Or do I have to break down the url's using something like slice at the "*" to compare the two?
Thanks in advance for any help.
for (let i = 0; i < arr.length; i++) {
if (arr[i].indexOf('*') !== -1) {
wildcardArr.push(arr[i]);
} else {
noWildcardArr.push(arr[i]);
}
}
***Note, the reason I check noWildcardArr first is because most of the validate redirect url's do not contain wildcard
if (noWildcardArr.includes(incomingRedirectUrl)) {
//Validated correct url, proceed with the next part of my code (this part already works)
} else if (wildcardArr.includes(incomingRedirectUrl)) {
//need to figure out this logic here, not sure if the above is possible without formatting wildcardArr but url should be validated if url matches with wildcard
} else {
log.error('authorize: Bad Request - Invalid Redirect URL');
context.res = {
status: 400,
body: 'Bad Request - Invalid Redirect URL',
};
}
You could compile your URL array into proper regex and then iterate over them to see if it matches. Similar to something like a web framework would do that allows URL path parameters such as /users/:id.
function makeMatcher(urls) {
const compiled = urls.map(url => {
// regex escape the url but dont escape *
let exp = url.replace(/[-[\]{}()+?.,\\^$|#\s]/g, '\\$&');
// replace * with .+ for the wildcard
exp = exp.replaceAll('*', '.+');
// the expression is used to create the match function
return new RegExp(`^${exp}$`);
});
// return the match function, which returns true, on the first match,
// or false, if there is no match at all
return function match(url) {
return compiled.find(regex => url.match(regex)) == undefined ?
false :
true;
};
}
const matches = makeMatcher([
'https://*.example.com/example/login',
'http://www.example2.com/*/example2/callback'
]);
// these 2 should match
console.log(matches('https://x.example.com/example/login'));
console.log(matches('http://www.example2.com/foo/example2/callback'));
// this one not
console.log(matches('http://nope.example2.com/foo/example2/callback'));

How do I append a string to a URL

I am working on an Angular app and having a bit of a problem.
I am trying to test my API by appending a string into a URL.
It works fine when I hardcode the string into the URL but when I append it won't work.
this is a function that will get the string that I want to append.
getString(str: string){
this.strAppend = str
}
this is the URL,
url: string = http://localhost:3000/document/id/${this.strAppend}/transaction?from=1610742245&to=1623439932
notice how I use this.strAppend. Well, this is not working. Is this even the right approach?
You can use Template Literals to solve your problem.
var base = 'url'
getString(strToAdd: string) {
return `${base}/${strToAdd}`;
}
var newStr = getString('test');
First declare the variable in string
for time being refer this
$scope.str1 = 'This is ';
$scope.str2 = 'Sticked Toghether';
$scope.res = '';
$scope.join = function() {
$scope.res = $scope.str1 + $scope.str2;
};

After switching from a filesystem to mongodb approach, how can I recreate nested directory iteration?

I was storing files in a nested file structure like
data/category/year/month/day/type/subtype/0.json
and to get a list of files / directories within any folder I'd simply use a func like:
getDirectoryContentsSync(pathName) {
let exists = this.exists(pathName);
if (exists) {
let files = fs.readdirSync(pathName)
return files;
} else {
return [];
}
}
Now I'm switching to storing files in mongodb, identifying the files by their original file-path string like:
store(data, path) {
this.db.collection('fs').insertOne({
path,
data
});
}
load(path) {
let data = this.db.collection('fs').find({
path
})[0].data;
return data;
}
But I'm struggling to figure out a way to continue iterating through the structure the way I used to. The approach I'm thinking is pretty gross, like to assign a separate value for each sub-path pointing to children but I think its gonna be a really bad approach, something like:
store(data, path) {
this.db.collection('fs').insertOne({
path,
data
});
let pathParts = path.split("/");
let subPath = "";
pathParts.forEach(dir => {
subPath += dir;
this.db.collection('dir').insertOne({
path: subPath,
data: true,
children: []
});
});
}
That's not the full code for the concept because I realized it seemed like an overly complicated way to do it and decided to stop and ask. I'm just new to mongo db and I bet there's a much better way to handle this but have no idea where to start. What's a good way to do what I want?

Internet Explorer truncating flashVars containing JSON

This only happens in IE.
I'm using swfobject and loading the flash vars as such
var flashVars = {
myVar:'{"url":"http://google.com/", "id":"9999"}',
};
var params = {
allowFullScreen:"true",
wmode:"transparent",
allowScriptAccess:'always'
};
swfobject.embedSWF("mySwf.swf", "mySwf", "512", "318", "10.0.0", "./js/swfobject/expressInstall.swf", flashVars, params);
Everything works perfectly in all browser but IE. I checked myVar and it comes into the swf as { and that's it. I know it's dying at the '. I've tried putting a \ infront, then tried \\ and kept adding one slash until I got to \\\\\\\\. I even inverted all the slashes and tried the same ritual. Nothing.
I can get the string to finally come through, with inverted quotes and using double slashes, but then my JSON parser gets mad about there being slashes in my string.
Here's an example of what works, but of what is invalid JSON:
"{\\'url\\':\\'http://google.com/\\', \\'id\\':\\'9999\\'}"
Yep IE treats flashVars differently to all the other major browsers, I believe you need to make use of the JavaScript encodeURIComponent method which will escape all reserved characters from your String, eg:
// Removing all reserved characters from the flashVar value.
var flashVars = {
myVar: encodeURIComponent('{"url":"http://google.com/", "id":"9999"}'),
};
If you are passing multiple values in the flashVars then you could iterate through them and encode all chars in a single pass:
var flashVars = {
myVar: '{"url":"http://google.com/", "id":"9999"}',
anotherVar: 42
};
// Escape all values contained in the flashVars object.
for (key in flashVars) {
if (flashVars.hasOwnProperty(key)) {
flashVars[key] = encodeURIComponent(flashVars[key]);
}
}
As #dgmdan and #bcmoney suggested, it would probably make your code easier to read if you made use of JSON.stringify - however, you need to bear in mind that IE8 and below do not have a native JSON object, so you will need to include Crockford's JS Library in your HTML page.
// Making use of a JSON library.
var flashVars = {
myVar: encodeURIComponent(JSON.stringify({ url: "http://google.com/", id: "9999"})),
};
Also, it's worth bearing in mind that flashVars are limited to ~64k; so if you are planning to pass a lot of data, it might be better to use an ExternalInterface call to pull them from the JavaScript instead.
Try this to replace your first 3 lines:
var subVars = { url: "http://google.com/", id: "9999" };
var flashVars = { myVar: JSON.stringify(subVars) };

Resources