Multiple File uploads using .ashx - file-upload

I have been looking at this for several days now with no success. I am trying to create a multi-file upload system for a website. I have tried several jQuery plugins, including SWFUpload and Uploadify. Everything works except for the actual upload; the uploaded files never save to the folder. I'm guessing its the way I am using the .ashx, so any direction on whats wrong with the following code is appreciated. Thanks,
//Jquery is inherited, and I'm pretty sure this is all correct
<link href="/_uploadify/uploadify.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="/_uploadify/swfobject.js"></script>
<script type="text/javascript" src="/_uploadify/jquery.uploadify.v2.1.4.min.js"></script>
//Again, this all works as expected. CSS displays, SWF works, the issue I THINK deals
//with 'script' and 'folder'. My Upload.ashx is in the root, as well as uploads folder
<script type="text/javascript">
$(document).ready(function () {
alert("here");
$('#file_upload').uploadify({
'uploader': '/_uploadify/uploadify.swf',
'script': 'Upload.ashx',
'cancelImg': '/_uploadify/cancel.png',
'folder': 'uploads',
'multi': true,
'auto': true
});
});
</script>
<input id="file_upload" name="file_upload" type="file" />
//My handler code, I'm not sure if this works or not but I do know that if
//I try to debug nothing ever fires... I'm sure that's part of the problem
<%# WebHandler Language="C#" Class="Upload" %>
using System;
using System.Web;
using System.IO;
public class Upload : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
HttpPostedFile file = context.Request.Files["Filedata"];
file.SaveAs("C:\\" + file.FileName);
context.Response.ContentType = "text/plain";
context.Response.Write("Hello World");
}
public bool IsReusable
{
get
{
return false;
}
}
}
That's everything I have. If I try to upload a file with SWFUpload jQuery it says it succeeds but nothing ever saves to the folder. If I try with Uploadify it fails with either an HTTP Error or IO Error, and again, nothing saves. Thanks for any and all help.

I figured it out after some more time and debugging. The issue was actually with Form Authentication and occurred on any pages after the login screen. Here is the fix...
Add one of the below snippets to the web.config
If you aren't worried about any authentication try
<authorization>
<allow users="*"/>
</authorization>
If you only want to allow access to the new handler, do this
<location path="_handlers/Upload.ashx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
After I did this the debug points I had in my handler file were getting hit and I was able to solve the rest from there.

Related

Shopware - Not able to show my page in My apps

I created Shopware App. I wanted to show my app in Iframe. But always showing "Whoops! You’ve moved too fast and lost orientation."
This is my manifest.xml
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/shopware/platform/trunk/src/Core/Framework/App/Manifest/Schema/manifest-1.0.xsd">
<meta>
<name>TF</name>
<label>TF</label>
<label lang="de-DE">TF</label>
<author>TF</author>
<copyright></copyright>
<version>1.0.0</version>
<license>MIT</license>
</meta>
<setup>
<secret>test</secret>
<registrationUrl>https://example.com/shopware/register</registrationUrl>
</setup>
<permissions>
<read>order</read>
<read>product</read>
</permissions>
<admin>
<main-module source="https://example.com/app/shopware"/>
</admin>
</manifest>
I am using Laravel for my site. And I created route like
Route::get('/app/shopware', 'ShopwareController#showApp');
and my function is
public function showApp(Request $request)
{
echo 'Showing TF';
}
If I access this URL directly its working fine, but in Shopware showing error like this
How to solve this issue?
Thanks
I think you need to append the shop id and a timestamp to the url in the registrationUrl tags. This could be the reason shopware throws this error.
Take a look in here App Base Guide
There is an example of how a request should look like.
I think you need to add script code in the response html
<script>
window.onload = function () {
window.parent.postMessage('sw-app-loaded', '*');
}
</script>

Microsoft WebHelpers with NETCore.App (2.1)

I'm trying to get the below code to work, but I keep getting compatibility problems with Microsoft.Web.Helpers v 3.2.6 and my current SDK package of NETCore 2.1. Also, for the life of me, I can't get the simplest calls of IsPost and Request to be recognized. I'm sure it's an obvious fix, but I can't find it!
Thanks in Advance for any direction...
#using Microsoft.Web.Helpers;
#{
var fileName = "";
if (IsPost) {
var fileSavePath = "";
var uploadedFile = Request.Files[0];
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/App_Data/UploadedFiles/" +
fileName);
uploadedFile.SaveAs(fileSavePath);
}
}
<!DOCTYPE html>
<html>
<head>
<title>FileUpload - Single-File Example</title>
</head>
<body>
<h1>FileUpload - Single-File Example</h1>
#FileUpload.GetHtml(
initialNumberOfFiles:1,
allowMoreFilesToBeAdded:false,
includeFormTag:true,
uploadText:"Upload")
#if (IsPost) {
<span>File uploaded!</span><br/>
}
</body>
</html>
The WebHelpers library is not compatible with ASP.NET Core. It relies on System.Web, which .NET Core has been designed to move away from.
The replacement for the IsPost block is a handler method. By convention, a handler method named OnPost will be executed if the method used to request the page is POST (which is what the IsPost property used to check).
Personally, I never understood the point of the FileUpload helper unless you wanted to allow the user to add additional file uploads to the page (which you clearly don't in this case). An input type="file" is easier to add to a page.
File uploading in ASP.NET Core is completely different to Web Pages. Here's some guidance on it: https://www.learnrazorpages.com/razor-pages/forms/file-upload

How to run SystemJs module when view loads

I have a component that loads a javascript module that builds on Bootstrap.js and Jquery to automatically build a table of contents for a page based on H1,H2,... headers. The component code is as follows:
import { bindable, bindingMode, customElement, noView } from 'aurelia-framework';
#noView()
#customElement('scriptinjector')
export class ScriptInjector {
#bindable public url;
#bindable public isLocal;
#bindable public isAsync;
#bindable({ defaultBindingMode: bindingMode.oneWay }) protected scripttag;
private tagId = 'bootTOCscript';
public attached() {
if (this.url) {
this.scripttag = document.createElement('script');
if (this.isAsync) {
this.scripttag.async = true;
}
if (this.isLocal) {
System.import(this.url);
return;
} else {
this.scripttag.setAttribute('src', this.url);
}
document.body.appendChild(this.scripttag);
}
}
public detached() {
if (this.scripttag) {
this.scripttag.remove();
}
}
}
Essentially for those not familiar with Aurelia, this simply uses SystemJs to load the bootstrap-toc.js module from my app-bundle wherever I put this on my view:
<scriptinjector url="lib/bootstrap-toc.js" is-local.bind='true'></scriptinjector>
My problem is that although this works perfectly when I first load the view, subsequent visits don't generate a TOC (table of contents). I have checked that Aurelia is in fact calling System.Import each time the view is loaded, but it seems that once a module has been imported once, it is never imported again (the code from the bundle never runs a second time).
Does anyone know how I can unload/reload/reset/rerun the module when I re-enter the view?
Ok, so after days of fighting with this I have figured out an acceptable solution that keeps all the functionality of the TOC library and requires as few changes to the skeleton project and the target library as I could manage. Forget the script injector above.
In the index.html, do as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Holdings Manager</title>
<!--The FontAwesome version is locked at 4.6.3 in the package.json file to keep this from breaking.-->
<link rel="stylesheet" href="jspm_packages/npm/font-awesome#4.6.3/css/font-awesome.min.css">
<link rel="stylesheet" href="styles/styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body aurelia-app="main" data-spy="scroll" data-target="#toc">
<div class="splash">
<div class="message">Holdings Manager</div>
<i class="fa fa-spinner fa-spin"></i>
</div>
<!-- The bluebird version is locked at 4.6.3 in the package.json file to keep this from breaking -->
<!-- We include bluebird to bypass Edge's very slow Native Promise implementation. The Edge team -->
<!-- has fixed the issues with their implementation with these fixes being distributed with the -->
<!-- Windows 10 Anniversary Update on 2 August 2016. Once that update has pushed out, you may -->
<!-- consider removing bluebird from your project and simply using native promises if you do -->
<!-- not need to support Internet Explorer. -->
<script src="jspm_packages/system.js"></script>
<script src="config.js"></script>
<script src="jspm_packages/npm/bluebird#3.4.1/js/browser/bluebird.min.js"></script>
<script src="jspm_packages/npm/jquery#2.2.4/dist/jquery.min.js"></script>
<script src="jspm_packages/github/twbs/bootstrap#3.3.7/js/bootstrap.min.js"></script>
<script>
System.import('core-js').then(function() {
return System.import('polymer/mutationobservers');
}).then(function() {
System.import('aurelia-bootstrapper');
}).then(function() {
System.import('lib/bootstrap-toc.js');
});
</script>
</body>
</html>
This is assuming you have installed bootstrap using jspm (which brings in jquery as a dependency). This also assumes you have put the javascript library (the one you want to incorporate, bootstrap-toc in my case) in your src/lib folder and that you have configured your bundling to include js files from your source folder.
Next, if your library has a self executing anonymous function defined, you need to take that code and move it inside the 'attached' method of the viewmodel where you want the library to be applied. So in this case, I have a 'help' view with a bunch of sections/subsections that I wanted a TOC generated for, so the code looks like:
import { singleton } from 'aurelia-framework';
#singleton()
export class Help {
public attached() {
$('nav[data-toggle="toc"]').each((i, el) => {
const $nav = $(el);
window.Toc.init($nav);
});
}
}
The code inside the 'attached' method above was cut and pasted from the bootstrap-toc.js file and I removed the self-executing anonymous method.
I tried using system.import for the jquery/bootstrap libraries but that made part of the TOC functionality stop working and I have lost my patience to figure out why so those libraries are staying as script references for now.
Also, when you build the project you will get errors :
help.ts(7,7): error TS2304: Cannot find name '$'.
help.ts(9,16): error TS2339: Property 'Toc' does not exist on type 'Window'.
These do not cause problems at runtime since both $ and Toc will be defined before the view is ever instantiated. You can solve these build errors with this solution here.

Asp.net core and IE 11 rendering page issue

This is the weirdest error i have seen so far, and im not sure what i am doing wrong here.
I have asp.net core application. I wanted to wire-up different layout page to Error view instead of default _layout.cshtml. So here are the steps i followed:
1> Created a new asp.net core web application using VS 2015 community using default project template.
2> I added a new _ErrorLayout.cshtml layout page into Views\Shared Folder.
_ErrorLayout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>My Application</title>
</head>
<body>
<div>
#RenderBody()
</div>
</body>
</html>
3> Then i wired up Error.cshtml to new _ErrorLayout.cshtml layout.
Error.cshtml
#{
Layout = "~/Views/Shared/_ErrorLayout.cshtml";
}
<h1>Error.</h1>
<h2>An error occurred while processing your request.</h2>
<h3>Development Mode</h3>
<p>
Swapping to <strong>Development</strong> environment will display more detailed information about the error that occurred.
</p>
<p>
<strong>Development environment should not be enabled in deployed applications</strong>, as it can result in sensitive information from exceptions being displayed to end users. For local debugging, development environment can be enabled by setting the <strong>ASPNETCORE_ENVIRONMENT</strong> environment variable to <strong>Development</strong>, and restarting the application.
</p>
4> Just for local testing purpose, in startup's configure method, i wire-up /Home/Error view for development environment.
Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
if (env.IsDevelopment())
{
//app.UseDeveloperExceptionPage();
app.UseExceptionHandler("/Home/Error");
app.UseBrowserLink();
}
}
5> For testing pupose throw exception in Home's Index method.
Home.cs
public class HomeController : Controller
{
public IActionResult Index()
{
throw new Exception();
}
}
Now whenever application starts it goes to error page as expected.
Issue
Error view has unwanted text. I just want header and a message. So i deleted everything below <h2>.
Modified Error.cshtml
#{
Layout = "~/Views/Shared/_ErrorLayout.cshtml";
}
<h1>Error.</h1>
<h2>An error occurred while processing your request.</h2>
Now if i run application i get Http 500 error
I press F12 in IE 11 and check the response. It looks correct but i dont know why page does not render. Below is the captured response in IE11
Notes
This is only happening in IE 11. Google chrome shows error page on application startup.
If put the deleted text back in error view then IE 11 works.

$.connection.(hubname) is undefined. Signalr/hub 501(not implemented)

I have a MVC 4 application which has a register page.
The code for hub is as follows:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SignalR.Hubs;
[HubName("messageHub")]
public class MessageHub : Hub
{
/// <summary>
/// Broadcast the message to all clients
/// </summary>
/// <param name="message">message to be broadcasted</param>
public void Broadcast(string message, string messagetype, string messagetitle)
{
this.Clients.showMessage(message, messagetype, messagetitle);
}
public void Getsubscription()
{
}
}
Similarly, the JS hub code is:-
<script type="text/javascript" src="#Url.Content("~/Scripts/json2.js")"></script>
<script src= "#Url.Content("~/Scripts/jquery.signalR-0.5.2.js")" type="text/javascript"></script>
<script src="#Url.Content("~/signalr/hubs")" type="text/javascript"></script>
<h2>Index</h2>
<script type="text/javascript">
$(document).ready(function () {
//Initialize hub
var hub = $.connection.messageHub;
// hub.start();
$.connection.hub.start();
//Append event to Button
//hub.broadcast("c","b","a");
});
</script>
Now, after running it is get $.connection.messageHub as undefined
secondly my chrome network shows;-
Thirdly, when clicking on initiator for signalr/hub i get not implemented error:-
I have tried changing the URL's for scripts, also ran as IIS but couldn't get it working.
If i keep my scripts in .cshtml (View) and change --> use Local IIS Webserver, its working fine
Any help.!
#Scripts.Render("~/bundles/modernizr")
#Scripts.Render("~/bundles/jquery")
commented this section out in layout section and worked for me.
I found that adding reference to /signalr/hubs in bundle config dose not work because it is generated at run-time and bundling happens at compile-time.
so i did this:
1- created a section like this in each view i need to have reference to signalr/hubs:
#section SignalRScripts{
<script src="/signalr/hubs"></script>
}
2- in my layout file after rendering all other scripts, rendered this section:
#Scripts.Render("~/js")
#RenderSection("SignalRScripts", required: false)
#RenderSection("Scripts", required: false)
then it worked fine.