How can I change this .NET code to File.Exists? - asp.net

I am working with a framework written in .NET and I do not know .NET. I just need to change this one line where it checks to see if a variable exists, and I need to change it to instead just check on the server to see if the file itself exists.
Here is what is there now:
#if (!string.IsNullOrEmpty(Model.DrawingLink2){
Is this the correct code to change it to check if the file exists instead?
#if (File.Exists(/Portfolio/#(Model.FileNumber)/Images/Large_#(Model.FileNumber)_1.jpg))

You need to map that file, relative to the root of the web application, to the physical file system. You can use HttpServerUtility.MapPath for that. You also need quotes around string literals. The process running the code also needs read access to the directory (very likely the case, just mentioning it to be complete).
#if (File.Exists(HttpServerUtility.MapPath("/Portfolio/#(Model.FileNumber)/Images/Large_#(Model.FileNumber)_1.jpg"))

Related

Replacing the Ajaxfileupload control in a Windows Forms application

We have a windows forms legacy asp.net site that uses the AjaxFileUpload control to manage file uploads. One of our issues is that we have different file type uploads but these types are distinguished not by the extension, but by an element right before the extnsion, EG: .gh.zip vs. .gy.zip. It seems that if I add one of these, but not the other, to the AllowedFileTypes, it doesn't allow either. Is it possible to piggyback some additional JS validation code to prevent an invalid file name, or would I need to replace the entire module with something else, and if so, what would be the recommendation for something that's going to be the least time-consuming that will offer a reasonable amount of configuratability?
That control is open source - you can download the source and change it if you wish.
However, why would not just specifying zip as allowed file type work?
If I set a allowed extension of zip?
Then all of these work:
.gh.zip ok
.gy.zip ok
.pdf no
However, my markup is this:
<ajaxToolkit:AjaxFileUpload ID="AjaxFileUpload1" runat="server"
OnClientUploadCompleteAll="MyCompleteAll" ChunkSize="16384"
AllowedFileTypes="zip"
/>
So, above only allows zip files.
if I try to say add a pdf file to above que, then I get this:
So just add allowed extension type = zip
(Edit: do NOT include the "." in this extension)
I not sure why that would not work?
But as noted, you can grab the source - it is open source code now.
However, I suspect perhaps some other issue is going on here?
Or maybe you need "more" complex file extensions parsing?
I mean, you could for the "rare" cases or say some "out liner" cases allow that file up-load, and THEN the post-processing code could reject the file type anyway, right?
However, looking at above, just specify file type = zip, and you should be ok.

How do I check whether a file exists without exceptions in Julia?

How do I see if a file exists without exceptions using Julia? I want to make sure that my program does not crash if for some reason the file I am trying to open is not accessible, has been deleted, or does not exist.
There are two simple ways of doing so.
First:
println(isfile("Sphere.jl"))
false
This isfile() function will simply check if the file exists. Note: if Sphere.jl is not in your current file path, you would need to provide the absolute path to get to that file.
Second (more of a trial by fire example):
try
open("Sphere.jl", "w") do s
println(s, "Hi")
end
catch
#warn "Could not open the file to write."
end
The second example utilizes the try-catch schema. It is always best for your program to not have to deal with errors so it's recommended that you use isfile() unless you have to use try-catch for your use case.
It's worth noting that there may be some cases where the file exists, but writing to it is not possible (i.e. it's locked by the os). In that case, using try-catch is a great option when attempting to write.

NLog Web - AspNet-User-Identity without domain

I'm currently using the NLog.Web package for writing my .Net logs in my application.
After reading the NLog.Web I've noticed that unlike the ${windows-identity} layout renderer, the ${aspnet-user-identity} layout renderer got no domain parameter for it.
For example, if I want to log the current running windows identity, it logs out: domain\user, but when specifying domain=false, it logs only user.
How do I implement this kind of ability with the ${aspnet-user-identity}? Because when I configured ${aspnet-user-identity:domain=false} it didn't work.
The WindowsIdentity.Name, used in NLog, will always give the full name, including domain.
The logon name is in the form DOMAIN\USERNAME.
https://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.name(v=vs.110).aspx
I think you need a custom layout renderer, and split it by-hand on the /.
Something like this: (maybe also add soms checks for outOfIndex)
using NLog.LayoutRenderers;
....
//register ${my-aspnet-user-identity}
LayoutRenderer.Register("my-aspnet-user-identity",
(logEvent) => HttpContext.Current?.User?.Identity?.Name?.Split('/')[1]);
Register it as soon as possible.
I found a different way to solve this issue #Julian
in the NLog.config file, i created a variable:
<variable name="aspnetIdentity" value="${replace:searchFor=^\\w+\\\\:replaceWith=:regex=true:inner=${aspnet-user-identity}}" />
As defined in the variable, the regex searches for at least one word (at the start) and finally searching for a backslash.
the other backslashes are written to escape special characters and also double backslashing. Finally, what was found (it's the domain name) will be replaced with an empty string and therefore I got only the username and not the Domain\Username
Thanks for the help #Julian

Overwrite an existing file programmatically

I have a QDialogBox where there is an option to upload a file.
I can upload files and save them to a folder. It works fine.
But if in case there is a file that already exists in the folder, I am not sure how to handle that scenario.
I want to warn the user that the file with same name already exists.
Is there a Windows API that I can use in this case? (because when we manually save an existing file, we get a warning, how can I use that?)
If someone can point me to that documentation, it will be great.
If you are using a QFileDialog, confirmOverwrite is activated by default, so, if getSaveFileName() returned a non-empty QString, then that means the user accepted to overwrite the file. Other way, you get an empty QString.
Then, you can check if the file exists, and remove it in that case, but you know that the user was Ok with that.
There is always a potential race condition when saving files. Checking to see if the file exists first is not safe, because some other process could create a file with the same name in between the check and when you actually write the file.
To avoid problems, the file must be opened with exclusive access, and in such a way that it immediately fails if it already exists.
If you want to do things properly, take a look at these two answers:
How do I create a file in python without overwriting an existing
file
Safely create a file if and only if it does not exist with
python
You can use QDir::entryList() to get the file names in a directory if you're not using a QFileDialog.
QDir dir("/path/to/directory");
QStringList fileNames = dir.entryList();
Then iterating through file names, you can see if there's a file with the same name. If you need it, I can give an example for that too. It'd be C++, but easily adaptable to Python.
Edit: Smasho just suggested that using QDir::exists() method. You can check if the file name exists in the directory with this method instead of iterating like I suggested.
if(dir.exists(uploadedFileName))

Asp.NET / VB.NET: Getting the path from the URL / URI?

Say I have a project that I am deploying at
www.foo.com/path1/default.aspx
and
www.foo.com/path2/default.aspx
What would be the most reliable way to know if I was in the folder "path1", or "path2"? Can I grab that directly, or do I need to split() somehow on the Request.Url.AbsolutePath, or... ?
I just want to change colors, etc. based on which folder the user is in.
Thanks for any assistance!
If you want to code that logic directly into the page, then yeah, I'd go with split() on Request.Url.AbsolutePath.
That said, I'd consider storing this kind of setting in the AppSettings section of web.config. That way if you decide to change the color in path2, you just need to edit the web.config for path2. If you need to add a new path, just deploy there and edit the web.config as appropriate.
Yeah use Request.Url.AbsolutePath.
I do it to create Breadcrumbs, using Split to split the URL, then in your case I suggest to use Switch statement to change color based on the case of the Switch statement
Here is a great article about Paths in ASP.
Check out the MSDN docs on System.IO.Path. It contains a number of useful functions for dealing with path names. You can get GetDirectoryName() or GetFullPath() or GetFileName() or GetFileNameWithoutExtension().

Resources