non-invocable member 'File' cannot be used like a method error message- what am I missing? - blazor-server-side

I have a Blazor Application which had files uploaded to a upload folder on the web server. I am in the process of trying to figure out the code to download an uploaded file in the browser for retrieval and viewing. Right now the code is as below (the download part from code examples on the internet)
public void FileDetailsToolbarClickHandler(Syncfusion.Blazor.Navigations.ClickEventArgs args)
{
string path = null;
string uploads = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot\\uploads");
path = uploads + "\\" + SelectedFileName;
if (args.Item.Text == "Delete")
{
//Code for Deleting goes here
//UploadRef.Remove();
if (System.IO.File.Exists(path))
{
System.IO.File.Delete(path);
}
FileDetailsService.FileDetailsDelete(SelectedFileId); //NavigationManager.NavigateTo($"/ServiceRequestNotes/servicerequestnoteadd");
NavigationManager.NavigateTo($"/ServiceRequests/serviceRequestsaddedit2/{Id}", forceLoad: true);
}
else
{
// its a download
IFileProvider provider = new PhysicalFileProvider(uploads);
IFileInfo fileinfo = provider.GetFileInfo(path + SelectedFileName);
var readStream = fileinfo.CreateReadStream();
var mimeType = "application/pdf";
return File(readStream, mimeType, SelectedFileName);
}
}
On the last statement I am a getting the following error message
non-invocable member 'File' cannot be used like a method error message
What am I missing or do I need to change or add to have the output from the readstream render to the browser?
The blazor application is a blazor server app not WASM. It does not make use of API controllers.
Any advice?

This is a void method. You can't return anything at all. Also, if you're trying to instantiate a File object, you'd have to use the new keyword.

Related

Sensenet: Upload Files through Sensenet Client API and Set Modified User

I have a requirement that consists on uploading files through other system to sensenet.
I'm trying to use the Sensenet Client API to upload files but I'm having difficult using the examples documented on the follow links:
Client Library (the code runs well but the file doesn't appear on Sensenet)
Common API Calls (I'm having trouble to compile the code... to instantiate the BinaryData object)
Beside this, I need for each uploading file define the "Modified By" that I specify in my code and not the user that I use to authenticate me in the API.
I think rewriting the ModifiedBy field is an edge case (or a small hack) but it is possible without any magic (see the code). The easiest way is a POST followed by a PATCH, that is perfectly managed by the SenseNet.Client (the code uses a local demo site):
static void Main(string[] args)
{
ClientContext.Initialize(new[]
{new ServerContext {Url = "http://localhost", Username = "admin", Password = "admin"}});
var localFilePath = #"D:\Projects\ConsoleApplication70\TestFileFromConsole1.txt";
var parentPath = "/Root/Sites/Default_Site/workspaces/Document/londondocumentworkspace/Document_Library";
var fileName = "TestFileFromConsole1.txt";
var path = parentPath + "/" + fileName;
var userPath = "/Root/IMS/BuiltIn/Demo/ProjectManagers/alba";
using (var stream = new FileStream(localFilePath, FileMode.Open))
Content.UploadAsync(parentPath, fileName, stream).Wait();
Console.WriteLine("Uploaded");
Modify(path, userPath).Wait();
Console.WriteLine("Modified");
Console.Write("Press <enter> to exit...");
Console.ReadLine();
}
// Rewrites the ModifiedBy field
private static async Task Modify(string path, string userPath)
{
var content = await Content.LoadAsync(path);
content["ModifiedBy"] = userPath;
await content.SaveAsync();
}

OneDrive REST API get files without folderID

I'm trying to use the oneDrive REST API to get files in a specific folder.
I have the path to the folder (For example "myApp/filesToDownload/", but don't have the folder's oneDrive ID. Is there a way to get the folder ID or the files in the folder with the REST API?
The only way I see to get it is by using https://apis.live.net/v5.0/me/skydrive/files?access_token=ACCESS_TOKEN
to get the list of folders in the root, and then splitting the path string on "/" and looping on it, each time doing a GET https://apis.live.net/v5.0/CURRENT_FOLDER/files?access_token=ACCESS_TOKEN request for each hierarchy.. I would prefer to avoid doing all those requests because the path may be quite long..
Is there a better/simpler way of getting the files of a specific folder?
Thanks
As Joel has pointed out, Onedrive API supports path based addressing also (in addition to ID based addressing). So you don't need the folder ID. You can use the Onedrive API (api.onedrive.com) for getting the files/folders of a specific folder as follows:
String path = "path/to/your/folder"; // no '/' in the end
HttpClient httpClient = new DefaultHttpClient();
// Forming the request
HttpGet httpGet = new HttpGet("https://api.onedrive.com/v1.0/drive/root:/" + path + ":/?expand=children");
httpGet.addHeader("Authorization", "Bearer " + ACCESS_TOKEN);
// Executing the request
HttpResponse response = httpClient.execute(httpGet);
// Handling the response
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONObject finalResult = new JSONObject(tokener);
JSONArray fileList = null;
try{
fileList = finalResult.getJSONArray("children");
for (int i = 0; i < fileList.length(); i++) {
JSONObject element = (JSONObject) fileList.get(i);
// do something with element
// Each element is a file/folder in the form of JSONObject
}
} catch (JSONException e){
// do something with the exception
}
For more details see here.

PDF generation in mvc4 with itextsharp

I am working on pdf generation, it is successfully implemented using itextsharp.dll. It’s working fine on local environment after publish also. We have our own server at other site
But same code doesn't work on the server,pdf is not generated instead it gives an error: 'The document has no pages.'
Initially I thought it is due to no data in document but it works locally with or without data in the document.
I had code implemented as follows to make a web request Is any problem in that ??
try
{
var myHttpWebRequest = (HttpWebRequest)WebRequest.Create(strPdfData + "?objpatId=" + patID);
var response = myHttpWebRequest.GetResponse();
myHttpWebRequest.Timeout = 900000;
var stream = response.GetResponseStream();
StreamReader sr = new StreamReader(stream);
content = sr.ReadToEnd();
}
create a method in the controller:
[HttpGet]
public JsonResult GetFile()
{
var json = new WebClient().DownloadFile(string address, string fileName);
//This code is just to convert the file to json you can keep it in file format and send to the view
dynamic result = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var oc = Newtonsoft.Json.JsonConvert.DeserializeObject<countdata[]>(Convert.ToString(result.countdata));
return Json(oc, JsonRequestBehavior.AllowGet);
}
In the view just call this function:
#Url.Action('genPDF','GetFile');

<p:media display pdf from folder dynamically

I have several pdf files saved in ...WebContent/Manuals/filename.pdf that I am trying to display on my page. I am getting "Failed to Load PDF document" message in Chrome.
My Jsf:
<p:media value="#{reviewBean.manual}" player="pdf" height="600px" width="1000px" />
My #SessionScoped Bean:
public StreamedContent getManual() throws IOException {
String type = "application/pdf";
String path = "";
FacesContext context = FacesContext.getCurrentInstance();
if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
return new DefaultStreamedContent();
} else {
path = "C:\\.....\\WebContent\\Manuals\\filename.pdf";
InputStream is = new ByteArrayInputStream(path.getBytes());
return new DefaultStreamedContent(is, type);
}
}
There is additional logic that i have left out for clarity which decides which pdf is displayed.
I have also tried the file path of /Manuals/filename.pdf as path
I tried following the below example:
How to bind dynamic content using <p:media>?
In my case I do not need to retrieve a value using <f:param
Is my file path incorrect to display the image? Or am I building the Stream incorrectly? Any guidance is much appreciated.
I solved this by merely returning the url as a String.
public String getManual() {
return user.getManuals().get(user.getLData().getDepart());
}
Where the returned value is the file path of the pdf: Manuals/filename.pdf

How do I open a file when clicking an ActionLink?

How do I open an existing file on the server when a user clicks an actionlink? The following code works for downloading a file but I want to open a new browser window, or tab, and display the file contents.
public ActionResult Download()
{
return File(#"~\Files\output.txt", "application/text", "blahblahblah.txt");
}
You must add "inline" for a new tab.
byte[] fileBytes = System.IO.File.ReadAllBytes(contentDetailInfo.ContentFilePath);
Response.AppendHeader("Content-Disposition", "inline; filename=" + contentDetailInfo.ContentFileName);
return File(fileBytes, contentDetailInfo.ContentFileMimeType);
The way you're using the File() method is to specify a file name in the third argument, which results in a content-disposition header being sent to the client. This header is what tells a web browser that the response is a file to be saved (and suggests a name to save it). A browser can override this behavior, but that's not controllable from the server.
One thing you can try is to not specify a file name:
return File(#"~\Files\output.txt", "application/text");
The response is still a file, and ultimately it's still up to the browser what to do with it. (Again, not controllable from the server.) Technically there's no such thing as a "file" in HTTP, it's just headers and content in the response. By omitting a suggested file name, the framework in this case may omit the content-disposition header, which is your desired outcome. It's worth testing the result in your browser to see if the header is actually omitted.
Use a target of blank on your link to open it in a new window or tab:
Download File
However, forcing the browser to display the contents is out of your control, as it entirely depends on how the user has configured their browser to deal with files that are application/text.
If you are dealing with text, you can create a view and populate the text on that view, which is then returned to the user as a regular HTML page.
please try this and replace your controller name and action name in html action link
public ActionResult ShowFileInNewTab()
{
using (var client = new WebClient()) //this is to open new webclient with specifice file
{
var buffer = client.DownloadData("~\Files\output.txt");
return File(buffer, "application/text");
}
}
OR
public ActionResult ShowFileInNewTab()
{
var buffer = "~\Files\output.txt"; //bytes form this
return File(buffer, "application/text");
}
this is action link which show in new blank tab
<%=Html.ActionLink("Open File in New Tab", "ShowFileInNewTab","ControllerName", new { target = "_blank" })%>
I can´t vote your answered as is useful, follow dow. Thanks very much !
public FileResult Downloads(string file)
{
string diretorio = Server.MapPath("~/Docs");
var ext = ".pdf";
file = file + extensao;
var arquivo = Path.Combine(diretorio, file);
var contentType = "application/pdf";
using (var client = new WebClient())
{
var buffer = client.DownloadData(arquivo);
return File(buffer, contentType);
}
}