WebMatrix - Server.MapPath issues - razor

I am having an issue with the server.mappath method. My current code is:
var imageroot = Server.MapPath("~/Images/Property/");
var foldername = rPropertyId.ToString();
var path = Path.Combine(imageroot, foldername);
When I upload this path into my database, I expect to see the following URL:
/images/property/1/filename.jpg
But what I actually see is this URL:
C:\Users\gavin\Dropbox\My Web Sites\StayInFlorida\Images\Property\1\filename.jpg
How do I get around this? I'm assuming I have to change the MapPath method, but I've tried a few things but I've had no luck.

The Server.MapPath method returns a file system path. What you want is a (relative) URL. Paths and URLs are completely different things. Typically, you need a path if you want to manage files in your server side code, and you need a URL is you are providing access to those files to visitors via hyperlinks. URLs can be constructed from strings:
var url = string.Format("/Images/Property/{0}/{1}", rProprtyId, filename)

Related

How to access local webpage with parameters in vb?

I've scenario where i want open local web page (index.html) passing parameters in query which i can used in index.html but i'm having problem as it gives error as per below,
The system cannot find the file specified.
Vb.net Code
Dim url As String = ConfigurationManager.AppSettings("Url")
url = url & "?id=" & txtFilePath.Text
//Url example
"C:\Program Files\Products\Bella\index.html?id=232"
Process.Start(url)
i do not completely understand your question but i will try.
I do not know what the value of "Url" is, neither what the txtFilePath.text is supposed to be. but if you are trying to open a URL like
localhost/index.html?id=example
in a browser, you should use that as the first parameter.
Process.Start("IExplore.exe", url)
If you are trying to get the server to read the parameter you put into the URL, i do not know if you can make html-pages get parameters like that, maybe PHP or something else? But that should not make a difference at all for launching the browser and stuff, just a heads-up :)
But if you just want to open a static html file in a browser-window, you are, as far as i know, out of luck with passing parameters, but you SHOULD test for the existence of your file, so you are completely sure it exists in that path.
File.Exists(url)
EDIT:
Since your url is "C:\Program Files\Products\Bella\index.html?id=232" i do not believe you could pass parameters, i think it will try to find a file with the extension ".html?id=232", which obviously does not exist.
It seems there are two issues:
First:
I think the reason for the error is you need to have "file://" before the URL (as Mych mentioned in the comments) in order to access a local web page. Many browsers will automatically assume the URL should have "http://" unless you specify that it's a local file.
Depending on your browser it may add more forward slashes, but two should be sufficient to get Process.Start to recognize it.
So your URL should look like this:
"file://C:\Program Files\Products\Bella\index.html?id=232"
Second:
As far as passing a parameter to the URL the best way I have found (as jakobS suggested) you would have to use:
Process.Start("IExplore.exe", url)
'or
Process.Start("Chrome.exe", url)
or whichever browser you prefer.
So you could modify your code this way:
Dim url As String = ConfigurationManager.AppSettings("Url")
url = url & "?id=" & txtFilePath.Text
'Add "file://" to the beginning of the url.
url = "file://" & url
Process.Start("IExplore.exe", url)
That should get rid of your error and load the page with your parameters.
Hope it helps!

Edit on Google Docs without converting

I'm integrating my system with Google Drive. Everything is working so far, but one thing. I cannot edit the uploaded Word documents without converting them to Google Docs first.
I've read here it's possible using a Chrome plugin:
https://support.google.com/docs/answer/6055139?hl=en
But that's not my goal. I'm storing the file's information on my database and then I just request the proper URL for editing and previewing. Previewing is working fine, but when I try the edit URL it says the file does not exist. If I convert the file (using Google Drive's interface) and pass the new ID it works. I don't want to convert the user's documents to Google Drive because they still use Word as their main editing software.
Is there a way to accomplish this?
This is how I'm doing right now:
public static File UploadFile(FileInfo fileInfo, Stream stream, string googleAccount)
{
var mimetype = GetValidMimetype(fileInfo.MimeType);
var parentFolder = GetParentFolder(fileInfo);
var file = new File { Title = fileInfo.Title, MimeType = mimetype, Parents = parentFolder };
var uploadRequest = _service.Files.Insert(file, stream, mimetype);
uploadRequest.Upload();
file = uploadRequest.ResponseBody;
ShareFileWith(file.Id, googleAccount);
return file;
}
This is the URL for editing (where {0} is the file ID):
https://docs.google.com/document/d/{0}/edit?usp=drivesdk
I know that in order to convert the file I just need to:
uploadRequest.Convert = true;
But again, that's not what I want. Is it possible?
Thanks!
EDIT
Just an update. Convert = true should've worked but it's not. I've raised an issue for that here https://github.com/google/google-api-dotnet-client/issues/712
Bottomline, it only works if I open the file on Google Docs and then use its Id...

Open a file from Google Sheets script

I've had a Google Sheets script running for some time (a year) that needs to read an HTML file from it's Google Drive directory. The code to open the file looks like this:
var myHtmlFile = UrlFetchApp.fetch("https://googledrive.com/host/0B1m........JtZzQ/myfile.htm");
... and I could use the HTM file for further parsing.
Suddenly, the code above is throwing an error 404.
Has anything changed recently, stopping me from opening the file?
After a discussion with 'azawaza' (thanks for all the tips), I have finally solved this, so I'm posting the resolution in case others fall into this.
It looks like the construct
https://googledrive.com/host/{public_folder_id}/myfile.htm
in UrlFetchApp.fetch(url, true) can no longer be used. It gives error 404.
I was getting it from the following construct (for simplicity, assuming there is only one parent folder of my spreadsheet):
...
var myId = DocsList.getFileById(SpreadsheetApp.getActive().getId());
var folderId = myId.getParents()[0].getId();
var url = "https://googledrive.com/host/" + folderId + "/myfile.htm";
// url looks like: https://googledrive.com/host/0B1m....JtZzQ/myfile.htm"
var httpResp = UrlFetchApp.fetch(url,true); //throws 404 !!!
// now, parse 'httpResp'
The solution that worked for me, is to find the file directly using this construct (again, assuming there is only one file of given name) :
var htmlCont = DocsList.find("myfile.htm")[0].getContentAsString();
// now, parse htmlCont
I don't know why the 'old' solution no longer works. As I mentioned it worked for a year.
UPDATE (May 2015)
The 'DocsList' has been deprecated, a new construct:
var files = DriveApp.getFilesByName(myURL);
if (files.hasNext()) {
var htmlCont = files.next().getBlob().getDataAsString()
}
has to be used instead
I find it strange that it ever worked before! If it did, it was probably a bug - pretty sure it was never intended to work like that with "local" files... I have never seen it mentioned anywhere that UrlFetchApp.fetch() can fetch "local" files like that.
A simple fix would be to just use proper full url of the file:
var myHtmlFile = UrlFetchApp.fetch("https://googledrive.com/host/{public_folder_id}/myfile.htm");
That will ensure your code complies with the API and does not break next time Google changes something.

How to load an image using its real path in Grails

My idea is to save the images which the user uploads outside the context path as follow:
D:\somefolder\myWeb\web-app\
D:\somefolder\imagesOutsideContextPath\
The code for that is the next (working locally):
String path = servletContext.getRealPath("/");
String parentFolder = new File(path).getParentFile().getParent();
String imagesFolder = parentFolder + "\\imagesOutsideContextPath";
Another idea (if this one doesn't work on server) would be to save the images in the current user's home folder as #HoàngLong suggested me.
But I'm not able to load the images from the view. I think this article from official documentation is not valid for that purpose. The next code desn't load anything:
<img src="D:\\somefolder\\imagesOutsideContextPath\\bestImageEver.jpg" alt="if I don't see this message, I'll be happier">
How could I use the real path instead the an url path to load these images?
There's a new plugin that makes this easy, check out http://grails.org/plugin/img-indirect
Create an action
def profileImage() {
String profilePicturePath = "${grailsApplication.config.profilePictureDirectoryPath}/${params.id}"
File file = new File(profilePicturePath)
response.contentType = URLConnection.guessContentTypeFromName(file.getName())
response.outputStream << file.bytes
response.outputStream.flush()
}
and then call this action with image name in params like:
<g:img uri="${grailsApplication.config.grails.serverURL}/controller/profileImage/${user?.profilePicture?.fileName}"/>
I have declared the image directory file in my config.groovy file like:
profilePictureDirectoryPath = '/opt/CvSurgeon/profileImages'
You can set the src to an action. With that your user will not know where your images are stored (security) and you can easily change your logic to display them.
In the action, just get your image and print the bytes. Example here.
Firstly, thank you for your reference.
It's insecure to load images using real path. The web browser should know nothing about how the pictures are saved on server, therefore not aware of the folder structure.
What I mean is that the system should use a specific URL for all your pictures, such as http://your_app/photo/user/{id}. Then to that URL, you can construct an action which gets id as a parameter, look up the photo in your file system(of course you must store the picture folder in configuration), and render the photo back.

Loading an asset stored within a chrome extension

Let's say I have a JSON file stored within my extension called settings.json. I can get the URL of the file using:
chrome.extension.getURL("settings.json");
But now that I have the URL, how do I actually load the contents of that file so I can JSON.parse it and use it? The reason I'm doing this is that there is a server component, and I want to make deployment and testing on multiple servers easier (dev, staging, production, etc.) Alternatively if there's a way to add custom attributes to the manifest.json and access them, that would also work.
If you make your setting.js look like:
var settings = {"param":value,...};
Then you can just include it on a background page and use settings variable:
<script src="settings.js"></script>
If you want to have pure json in your file without assigning it to any variables then you can load it using XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange; // Implemented elsewhere.
xhr.open("GET", chrome.extension.getURL('/config_resources/config.json'), true);
xhr.send();
or if you included jquery into your project:
$.getJSON(chrome.extension.getURL('/config_resources/config.json'), function(settings) {
//..
});
(btw using chrome.extension.getURL is required only if you are accessing a file from a content script, otherwise you can just use relative path /config_resources/config.json)
I can verify that requesting the resource from an XHR in the background page works as previously described. Just be sure to add 'self' to the connect-src portion of your content_security_policy.