I have setup a WCF service that returns json format data with my configuration file setup as follows:
<system.web>
<compilation debug="true" strict="false" explicit="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="webHttpBindingJsonP" crossDomainScriptAccessEnabled="true" />
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="webHttpBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="webHttpBehavior" name="Services.Service1">
<endpoint address="mex"
binding="webHttpBinding" bindingConfiguration="webHttpBindingJsonP"
contract="Services.IService1" behaviorConfiguration="webHttpBehavior"/>
</service>
</services>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
My service WebInvoke function:
<OperationContract()>
<WebInvoke(Method:="GET", BodyStyle:=WebMessageBodyStyle.WrappedRequest, Responseformat:=WebMessageFormat.Json)>
Function RetrieveData(ByVal screenName As String) As Stream
And Finally my dojo based website's function to call the webservice:
<script type="text/javascript">
dojo.ready(function () {
dojo.io.script.get({ url:
"http://xxx.xxx.x.xxx/Services/Service/Service1.svc/GetData?item=Tweet",
callbackParamName: "callback",
content: { username: "me", password: "you" }
}).then(function (data){
return data.results;
})
});
</script>
The problem is that I cannot get the data to flow through to the dojo application. First I get the error callback undefined. Now I am not sure if I am clear on this callback thing: is it the name of the function in the dojo application as I have above but the function is not named or is it the name of the function the returns the json response in the web service which by the way is installed on a different domain.
this is what I do with .NET:
My service:
[OperationContract]
[WebGet(UriTemplate = "/GetMyStuff", ResponseFormat = WebMessageFormat.Json)]
public String GetMyStuff()
{
var myStuff = getFromService("foo");
return new { label = "name", identifier = "Id", items = myStuff.Select(w => new { Id = w.Id, name = w.Description }) }.ToJSON();
}
I use this ToJSON() helper function declared as this:
public static class LinqUtils
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
}
In web.config:
<system.serviceModel>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="false">
<serviceActivations>
<add relativeAddress="Services/StuffServiceJson.svc" service="MyStuff.MyStuffService" /> <!-- This is an actual URL mapping to your service endpoint -->
</serviceActivations>
</serviceHostingEnvironment>
<!-- other stuff -->
<services>
<service name="MyStuff.MyStuffService">
<endpoint binding="webHttpBinding" contract="MyStuff.MyStuffService" address="" behaviorConfiguration="webHttp"/> <!-- This is a service endpoint to your implementation class mapping -->
</service>
</services>
</system.serviceModel>
In Dojo:
require(["dojo/_base/xhr"], function(xhr) {
xhr.get({
url: "/Services/StuffServiceJson.svc/GetMyStuff",
handleAs: "json",
preventCache: true
}).then(function (data) {
//Do something with DATA
}, function (error) {
//Do something with error OMG
});
});
If you get a problem with the data being returned as string anyway (happens in .NET sometimes) then you're gonna have to take your data and do
require(["dojo/json"], function(json){
json.parse(data)
});
Luck,
Related
I'm trying to call a function exposed by WCF service using ajax but the success method is always returning 'undefined' even though the function itself on the WCF side is returning the right answer
I tried debugging and printing everything and the WCF is returning the right answer but when the ajax call enters the success method object it receives is undefined
WCF:
[OperationContract]
[ WebInvoke (
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json
)]
public Result_Login LoginAdmin(string email, string password)
{
System.Diagnostics.Debug.WriteLine("LoginAdmin called");
#region Declaration And Initialization Section.
Result_Login resultLogin = new Result_Login();
#endregion
#region Body Section
try
{
BLC.BLC oBLC_Default = new BLC.BLC();
BLCInitializer oBLCInitializer = new BLCInitializer();
oBLCInitializer.ConnectionString = ConfigurationManager.AppSettings["CONN_STR"];
System.Diagnostics.Debug.WriteLine("Connection string: "+ConfigurationManager.AppSettings["CONN_STR"]);
using(BLC.BLC oBLC = new BLC.BLC(oBLCInitializer))
{
resultLogin.login = oBLC.SignInAdmin(email, password);
}
}
catch(Exception ex)
{
if(ex.GetType().FullName != "BLC.BLCException")
{
resultLogin.ExceptionMsg = string.Format("Get_Persons : {0}", ex.Message);
}
else
{
resultLogin.ExceptionMsg = ex.Message;
}
}
#endregion
#region Return Section
return resultLogin;//giving the right result before ajax return method
#endregion
}
public override string ToString()
{
return base.ToString();
}
// Add more operations here and mark them with [OperationContract]
}
#region Action_Result
public partial class Action_Result
{
#region Properties.
public string ExceptionMsg { get; set; }
#endregion
#region Constructor
public Action_Result()
{
#region Declaration And Initialization Section.
#endregion
#region Body Section.
this.ExceptionMsg = string.Empty;
#endregion
}
#endregion
}
#endregion
#region Result_Login
public partial class Result_Login : Action_Result
{
#region Properties.
public bool login { get; set; }
#endregion
}
Javascript:
function IsAuthenticated_JSON() {
try {
_Params1 = new Object();
_Params1.email = $("#Login1_UserName").val();
_Params1.password = $("#Login1_Password").val();
_Params = JSON.stringify(_Params1);
_Service_Method = "LoginAdmin";
CallService(_Service_Method, IsClientAuthenticated_Completed, Service_Call_InCompleted);
}
catch (e) {
alert("IsAuthenticated_JSON: " + e.Message);
}
}
function IsClientAuthenticated_Completed(i_Input) {
try {
localStorage.setItem("UserInfo", JSON.stringify(i_Input.My_Result));
console.log("unstringify: " + JSON.stringify(i_Input.My_Result));//undefined
if (localStorage.getItem('UserInfo') != null) {
_UserInfo = JSON.parse(localStorage.getItem('UserInfo'));
_Ticket = _UserInfo.Ticket;
alert("done");
}
}
catch (e) {
console.log("error "+e.Message + " " + e.log)
}
}
function CallService(i_Service_Method, i_Success_Method, i_Failure_Method) {
var url = "";
url = js_Prepare_WCF_Url_For_Call();
var request = $.ajax({
type: "POST",
url: url,
data: _Params,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
console.log("data: "+msg.data +"status: "+ msg.status +"message: " + msg.Message);//undefined
i_Success_Method(msg);
},
error: function (msg) {
console.log("fail: " + msg.responseText + msg.statusText)
}
});
}
Web.config:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="FuelAppEntities" connectionString="metadata=res://*/DALC.csdl|res://*/DALC.ssdl|res://*/DALC.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=FuelApp;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<appSettings>
<add key="CONN_STR" value="Data Source=.;Database=FuelApp;User ID=sa;Password=sa" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="project.Service1AspNetAjaxBehavior">
<enableWebScript />
</behavior>
<behavior name="My_Behavior">
<webHttp defaultOutgoingResponseFormat="Json" />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<customBinding>
<binding name="project.WCF.customBinding0">
<binaryMessageEncoding />
<httpTransport />
</binding>
</customBinding>
<webHttpBinding>
<binding maxBufferPoolSize="1048576" maxReceivedMessageSize="1048576" maxBufferSize="1048576" name="jsonpWebHttpBinding" useDefaultWebProxy="false" crossDomainScriptAccessEnabled="false" />
</webHttpBinding>
</bindings>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" minFreeMemoryPercentageToActivateService="0"/>
<services>
<service name="project.WCF">
<endpoint address="a" behaviorConfiguration="project.Service1AspNetAjaxBehavior"
binding="webHttpBinding" contract="project.WCF" />
<endpoint address="" binding="webHttpBinding" bindingConfiguration="jsonpWebHttpBinding" contract="project.WCF" behaviorConfiguration="My_Behavior" />
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
</system.serviceModel>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Apple" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Android" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.WindowsPhone" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Blackberry" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="PushSharp.Windows" publicKeyToken="cf74b75eab2c0170" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.2.1.0" newVersion="2.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
Not sure why you meet this problem , I have copied your code and have a test, but I could get the response.
Below is my code.
[ServiceContract]
public class MyTestRestService
{
[OperationContract]
[WebInvoke(
Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json
)]
public Result_Login LoginAdmin(string email, string password)
{
Result_Login resultLogin = new Result_Login();
resultLogin.ExceptionMsg = "exception";
resultLogin.login = true;
return resultLogin;
}
}
Model
public partial class Action_Result
{
public string ExceptionMsg { get; set; }
public Action_Result()
{
this.ExceptionMsg = string.Empty;
}
}
public partial class Result_Login : Action_Result
{
public bool login { get; set; }
}
Endpoint config.
<service name="Service.Rest.MyTestRestService" >
<endpoint binding="webHttpBinding" contract="Service.Rest.MyTestRestService" behaviorConfiguration="web"></endpoint>
</service>
To enable cross origin request, if your wcf rest server and your client are not at the same origin.
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="*"/>
</customHeaders>
</httpProtocol>
protected void Application_EndRequest(object sender, EventArgs e)
{
if(HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.StatusCode = 200;
}
}
The result.
It worked after adding
<webHttp defaultOutgoingResponseFormat="Json" />
to the service behavior in web.config
INTRODUCTION:
In order to upload multiple files to the server I am using:
Symfony v3.2.6
OneUpUploaderBundle
OneUpFlysystemBundle
Plupload file uploading library jQuery UI Widget version
NOTE 1:
Please note that: this configuration works for single and multiple file uploads, but it does not return any response when ValidationException is thrown!
NOTE 2:
In order to know that upload of a file finished successfully I added response to part of my UploadListener:
public function onUpload(PreUploadEvent $event)
{
$file = $event->getFile();
$response = $event->getResponse();
$message = [
'error' => 'none'
];
$response->addToOffset($message, array('files'));
}
It gives following response (if there was no error with file upload)
response: {"files":[{"error": "none"}]}
TARGET:
I would like to receive response with corresponding error when ValidationException is thrown.
example:
response: {"files":[{"error": "error code"}]}
PROBLEM:
I am using validator to restrict some uploadable files.
At the moment - files that validator restricts are not uploaded (ValidationException is being thrown). Yet no response is sent to the client/browser on this occasion!
I do not know how to make Plupload and Symfony3 return errors after ValidationException to client/browser.
CODE:
Validation Listener:
<?php
namespace AppBundle\EventListener;
use Oneup\UploaderBundle\Event\ValidationEvent;
use Oneup\UploaderBundle\Uploader\Exception\ValidationException;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
class AllowedMimeTypeValidationListener
{
/**
* #var Container
*/
private $container;
private $file_extension_array = [];
private $file_type_array = [];
private $banned_files = [];
public function __construct(Container $container)
{
$this->container = $container;
}
public function onValidate(ValidationEvent $event)
{
$ultra_helpers = $this->container->get('app.ultra_helpers');
$ultra_text = $this->container->get('app.ultra_text');
array_push($this->file_extension_array, '.gif');
array_push($this->file_extension_array, '.jpg');
array_push($this->file_extension_array, '.jpeg');
array_push($this->file_extension_array, '.png');
array_push($this->file_extension_array, '.zip');
array_push($this->file_extension_array, '.7z');
array_push($this->file_extension_array, '.pdf');
array_push($this->file_extension_array, '.bin');
array_push($this->file_extension_array, '.txt');
array_push($this->file_type_array, 'image/gif');
array_push($this->file_type_array, 'image/jpg');
array_push($this->file_type_array, 'image/jpeg');
array_push($this->file_type_array, 'image/png');
array_push($this->file_type_array, 'application/zip');
array_push($this->file_type_array, 'application/x-7z-compressed');
array_push($this->file_type_array, 'application/pdf');
array_push($this->file_type_array, 'application/octet-stream');
array_push($this->file_type_array, 'text/plain');
array_push($this->banned_files, 'do_not_allow_me_1.txt');
array_push($this->banned_files, 'do_not_allow_me_2.txt');
array_push($this->banned_files, 'do_not_allow_me_3.txt');
$file = $event->getFile();
$file_extension = '.'. $file->getExtension();
$file_mime_type = $file->getMimeType();
$full_file_name = $file->getClientOriginalName()
if (in_array($full_file_name, $this->banned_files))
{
throw new ValidationException('error.file_exists');
}
// Is file mime type the same as extension mime type
$mime_type_position = array_search($file_extension, $this->file_extension_array);
if ($mime_type_position !== false)
{
$mime_type_by_extension = $this->file_type_array[$mime_type_position];
if ($mime_type_by_extension !== $file_mime_type)
{
throw new ValidationException('error.mime_type_mismatch');
}
}
// Is file type not in activated file type array
if (!in_array($file_mime_type, $this->file_type_array))
{
throw new ValidationException('error.forbidden_mime_type');
}
}
}
Twig template with JavaScript:
{% extends 'base.html.twig' %}
{% block stylesheets %}
{{ parent() }}
<link type="text/css" rel="stylesheet" href="{{ asset('js/plupload/jquery-ui-1.12.1/jquery-ui.css') }}" />
<link type="text/css" rel="stylesheet" href="{{ asset('js/plupload/jquery.ui.plupload/css/jquery.ui.plupload.css') }}" media="screen" />
{% endblock %}
{% block content %}
<div id="box-upload">
<div id="uploader">
<p>Your browser doesn't have HTML5 support.</p>
</div>
</div>
{% endblock %}
{% block javascripts %}
<script type="text/javascript" src="{{ asset('js/browserplus/browserplus.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/plupload/plupload.full.min.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/jquery-2.2.4.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/plupload/jquery-ui-1.12.1/jquery-ui.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/plupload/jquery.ui.plupload/jquery.ui.plupload.js') }}"></script>
<script type="text/javascript" src="{{ asset('js/plupload/i18n/lv.js') }}"></script>
<script type="text/javascript">
'use strict';
$(function()
{
var uploader;
uploader = $("#uploader");
uploader.plupload(
{
// General settings
runtimes: 'html5',
url: "{{ oneup_uploader_endpoint('gallery') }}",
multi_selection: true,
// Maximum file size
max_file_size: '5mb',
chunk_size: '5mb',
// Specify what files to browse for
filters: [
{title: "Binary files", extensions: "bin"},
{title: "Image files", extensions: "gif,jpg,jpeg,png"},
{title: "Media files", extensions: "avi"},
{title: "Pdf files", extensions: "pdf"},
{title: "Text files", extensions: "txt"},
{title: "Zip files", extensions: "zip,7z"}
],
// Rename files by clicking on their titles
rename: true,
// Sort files
sortable: true,
// Enable ability to drag'n'drop files onto the widget (currently only HTML5 supports that)
dragdrop: true,
// Views to activate
views: {
list: true,
thumbs: false, // Show thumbs
active: 'list'
}
});
var $uploader = uploader.plupload('getUploader');
// Add Clear Button
var $button = $("<button>"+ plupload.translate("Clear list") + "</button>").button({icons: {primary: "ui-icon-trash"}}).button("disable").appendTo('.plupload_buttons');
// Clear Button Action
$button.click(function()
{
removeErrorMessages();
$uploader.splice();
$(".plupload_filelist_content").html('');
$button.button("disable");
return true;
});
// Clear Button Toggle Enabled
$uploader.bind('QueueChanged', function ()
{
if ($uploader.files.length > 0)
{
$button.button("enable");
}
else
{
$button.button("disable");
}
});
// Clear Button Toggle Hidden
$uploader.bind('StateChanged', function ()
{
if ($uploader.state === plupload.STARTED)
{
$button.hide();
}
else
{
$button.show();
}
});
// Clear Button Toggle Hidden
$uploader.bind('Browse', function ()
{
removeErrorMessages();
$uploader.splice();
});
$uploader.bind('FileUploaded', function(up, file, info)
{
var response;
response = jQuery.parseJSON(info.response);
console.log("-- next is response --");
console.log(response);
up.trigger("error", {message: "Fails: "+ file.name +" jau atrodas šajā mapē!<br> Augšupielādējamais fails <i>netika</i> saglabāts!", code: 12345, details: "Testing errors"});
$("#"+ file.id).addClass("duplicateFile");
});
function removeErrorMessages()
{
$(".ui-state-error").remove();
}
});
</script>
{% endblock %}
UPDATE
Added current code to the question
PluploadErrorHandler.php
<?php
namespace Oneup\UploaderBundle\Uploader\ErrorHandler;
use Exception;
use Oneup\UploaderBundle\Uploader\Response\AbstractResponse;
class PluploadErrorHandler implements ErrorHandlerInterface
{
public function addException(AbstractResponse $response, Exception $exception)
{
$message = $exception->getMessage();
$response->addToOffset(array('error' => $message), array('files'));
}
}
errorhandler.xml
<?xml version="1.0" encoding="utf-8" ?>
<container xmlns="http://symfony.com/schema/dic/services" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<parameters>
<parameter key="oneup_uploader.error_handler.noop.class">Oneup\UploaderBundle\Uploader\ErrorHandler\NoopErrorHandler</parameter>
<parameter key="oneup_uploader.error_handler.blueimp.class">Oneup\UploaderBundle\Uploader\ErrorHandler\BlueimpErrorHandler</parameter>
<parameter key="oneup_uploader.error_handler.dropzone.class">Oneup\UploaderBundle\Uploader\ErrorHandler\DropzoneErrorHandler</parameter>
<parameter key="oneup_uploader.error_handler.plupload.class">Oneup\UploaderBundle\Uploader\ErrorHandler\PluploadErrorHandler</parameter>
</parameters>
<services>
<service id="oneup_uploader.error_handler.noop" class="%oneup_uploader.error_handler.noop.class%" public="false" />
<service id="oneup_uploader.error_handler.blueimp" class="%oneup_uploader.error_handler.blueimp.class%" public="false">
<argument type="service" id="translator"/>
</service>
<service id="oneup_uploader.error_handler.dropzone" class="%oneup_uploader.error_handler.dropzone.class%" public="false" />
<service id="oneup_uploader.error_handler.plupload" class="%oneup_uploader.error_handler.plupload.class%" public="false" />
<service id="oneup_uploader.error_handler.fineuploader" class="%oneup_uploader.error_handler.noop.class%" public="false" />
<service id="oneup_uploader.error_handler.uploadify" class="%oneup_uploader.error_handler.noop.class%" public="false" />
<service id="oneup_uploader.error_handler.yui3" class="%oneup_uploader.error_handler.noop.class%" public="false" />
<service id="oneup_uploader.error_handler.fancyupload" class="%oneup_uploader.error_handler.noop.class%" public="false" />
<service id="oneup_uploader.error_handler.mooupload" class="%oneup_uploader.error_handler.noop.class%" public="false" />
<service id="oneup_uploader.error_handler.custom" class="%oneup_uploader.error_handler.noop.class%" public="false" />
</services>
</container>
QUESTION:
What am I missing?
Sorry previous version was incorrect.
OneupUploaderBundle catches exceptions in a controller and pass them to error_handler service.
class PluploadController extends AbstractChunkedController
{
public function upload()
{
...
foreach ($files as $file) {
try {
$chunked ?
$this->handleChunkedUpload($file, $response, $request) :
$this->handleUpload($file, $response, $request)
;
} catch (UploadException $e) {
$this->errorHandler->addException($response, $e);
}
}
return $this->createSupportedJsonResponse($response->assemble());
}
You should check which error handler is used for your application. Looks like by default for Plupload the bundle set up NoopErrorHandler which does nothing with your exception.
Oneup\UploaderBundle\Uploader\ErrorHandler\NoopErrorHandler
public function addException(AbstractResponse $response, Exception $exception)
{
// noop
}
errorhandler.xml
<service id="oneup_uploader.error_handler.plupload" class="%oneup_uploader.error_handler.noop.class%" public="false" />
To get Response of desired shape you should set up BlueimpErrorHandler or to define a custom handler.
Oneup\UploaderBundle\Uploader\ErrorHandler\BlueimpErrorHandler
public function addException(AbstractResponse $response, Exception $exception)
{
$message = $this->translator->trans($exception->getMessage(), array(), 'OneupUploaderBundle');
$response->addToOffset(array('error' => $message), array('files'));
}
OT: Using exceptions in the validator that way will bring bad experience to a user. The user should see all errors with an uploaded file not just first one. You should collect all errors and then throw an exception. For example:
...
if (in_array($full_file_name, $this->banned_files))
{
throw new ValidationException('error.file_exists');
}
$errors = [];
// Is file mime type the same as extension mime type
$mime_type_position = array_search($file_extension, $this->file_extension_array);
if ($mime_type_position !== false)
{
$mime_type_by_extension = $this->file_type_array[$mime_type_position];
if ($mime_type_by_extension !== $file_mime_type)
{
$errors[] = 'error.mime_type_mismatch';
}
}
// Is file type not in activated file type array
if (!in_array($file_mime_type, $this->file_type_array))
{
$errors[] = 'error.forbidden_mime_type';
}
if (empty($errors)) {
throw new ValidationException(implode(', ', $errors));
}
...
Ajax is not sending the data to the specified URL. Here is my controller:
#Controller
public class HomeController {
private List<User> userList = new ArrayList<User>();
#RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)
public String showForm() {
return "AddUsers";
}
#RequestMapping(value = "User.htm", method = RequestMethod.POST)
public #ResponseBody
String addUser(#ModelAttribute(value = "user") User user,
BindingResult result) {
String returnText;
if (!result.hasErrors()) {
userList.add(user);
returnText = "User has been added to the list. Total number of users are"
+ userList.size();
} else {
returnText = "Sorry, an error has occur. User has not been added to list.";
}
return returnText;
}
#RequestMapping(value = "ShowUsers.htm")
public String showUsers(ModelMap model) {
model.addAttribute("Users", userList);
return "ShowUsers";
}
}
AddUser.jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<script src="/AjaxWithSpringMVC2Annotations/js/jquery.js"></script>
<script type="text/javascript">
function AjaxCall() {
alert('ready');
//get the form variables....
var name = $('#name').val();
var education = $('#education').val();
$.ajax({
type: "POST",
url: "AddUsers.htm",
data: " name=" + name + "&education=" + education,
success: function (response) {
$('#info').html(response);
$('#name').val('');
$('#education').val('');
},
error: function (e) {
alert('ERROR : ' + e);
}
});
}
</script>
<body>
<h1>Welcome to the AddUsers page. </h1>
<table>
<tr><td>Enter your name : </td><td> <input type = "text" id="name"></td></tr>
<tr><td>Educational qualification : </td><td> <input type = "text" id="education"></td></tr>
<tr><td colspan = "2"><input type="button" value="Add Users" onclick="AjaxCall()"></td></tr>
<tr><td colspan = "2"><div id ="info"></div></td></tr>
</table>
Show users
</body>
</html>
I have inserted an alert within the ajax which never comes up. So I believe there is something wrong with the ajax method.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I have also created a domain class which would store the student information:
public class User {
private String name = null;
private String education = null;
public void SetName(String name) {
this.name = name;
}
public String GetName() {
return name;
}
public void SetEdu(String education) {
this.education = education;
}
public String GetEdu() {
return education;
}
}
There is also a warning:
WARN : org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with
URI [/sum/] in DispatcherServlet with name 'appServlet'>`
Dispatch servlet:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans" xmlns="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources
in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources in the /WEB-
INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.faisal.sum" />
</beans:beans>
I corrected the upper case problem ($.ajax instead of $.Ajax). Thanks for pointing out.
Now I have a different error:
POST http://localhost:8080/sum/AddUsers.htm 405 (Method Not Allowed)
change url:"AddUsers.htm" to url: "${pageContext. request. contextPath}/AddUsers.htm" and try.
the url you are calling is this
type: "POST",
url: "AddUsers.htm",
Which is POST, the controller method is GET. Hecne the 405 error, method not supported.
You try to send POST request but mapped your method call with GET method
#RequestMapping(value = "AddUsers.htm", method = RequestMethod.GET)
try to change RequestMethod.GET to POST
Hi everyone I am trying to calla wcf service from a javascript function for some reason asp.net is not recognizing the namespace and give me an error on runtime, any help will be greatly appreciated following is code:
Default aspx page
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WeatherService.svc"/>
</Services>
</asp:ScriptManager>
Enter a zipcode:
<input id="zipCodeInput" type="text" />
<br/>
<input id="getForecastButton" type="button" value="Get Forecast" onclick="onGetForecast()"/>
<br/>
<div id="resultsDiv">
</div>
</form>
Javasript
<script language="javascript" type="text/javascript">
function onGetForecast() {
var zip = document.getElementById("zipCodeInput").value;
//alert(zip);
UltimateServices.GetForecast(zip, onGetForecastComplete, onGetForecastError, zip);
}
function onGetForecastComplete(result, userData) {
document.getElementById("resultsDiv").innerHTML = "Weather for " + userData + " is going to be " + result;
}
function onGetForecastError(err) {
alert("There was a error " + err.get_message());
}
</script>
WeatherService.cs file(codebehind)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
[ServiceContract(Namespace = "UltimateServices")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class WeatherService
{
private static Random _rand = new Random();
[OperationContract]
public string GetForecast(string zipcode)
{
string forecast = "";
switch(_rand.Next(3))
{
case 0:
forecast = "Sunny and Warm";
break;
case 1:
forecast = "Chilly and overcast";
break;
case 2:
forecast = "Hot and humid";
break;
}
return forecast;
}
// Add more operations here and mark them with [OperationContract]
}
web.config file
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="WeatherServiceAspNetAjaxBehavior">
<enableWebScript />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true"
multipleSiteBindingsEnabled="true" />
<services>
<service name="WeatherService">
<endpoint address="" behaviorConfiguration="WeatherServiceAspNetAjaxBehavior"
binding="webHttpBinding" contract="WeatherService" />
</service>
</services>
</system.serviceModel>
here i call simple hello world from WCF using javascript
Service.cs
using System;
using System.Collections.Generic;
using System.Linq;`
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Activation;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service : IService
{
[WebGet(ResponseFormat = WebMessageFormat.Json)]
public string helloworld(string name)
{
name = "Hello " + name;
return name;
}
}
web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0"/>
</system.web>
<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="DefaultBehavior">
<endpoint address="" binding="webHttpBinding" contract="IService" name="RunningBarbus.Services.RunningBarbusService" behaviorConfiguration="AjaxBehavior">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint contract="IMetadataExchange" binding="mexHttpBinding" address="mex"/>
</service>
</services>
<bindings>
<webHttpBinding>
<binding crossDomainScriptAccessEnabled="true">
<security mode="None"/>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="DefaultBehavior">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="AjaxBehavior">
<!--<enableWebScript/>-->
<webHttp helpEnabled="true" automaticFormatSelectionEnabled="false" />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
<standardEndpoints>
<webScriptEndpoint>
<standardEndpoint crossDomainScriptAccessEnabled="true" name="">
</standardEndpoint>
</webScriptEndpoint>
</standardEndpoints>
</system.serviceModel>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="access-control-allow-headers" value="content-type, Accept" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS" />
<add name="Access-Control-Max-Age" value="1728000" />
</customHeaders>
</httpProtocol>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
javascript code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="jsonp.aspx.cs" Inherits="jsonp" %>
<!DOCTYPE html >
<html>
<head runat="server">
<title></title>
<script src="js/jquery-1.10.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var name="";
var Type;
var Url = "http://192.168.X.X/WCFjavascript/Service.svc/helloworld?name=world";
var Data;
var ContentType;
var DataType;
var ProcessData;
var method;
//Generic function to call WCF Service
function CallService() {
$.ajax({
type: Type, //GET or POST or PUT or DELETE verb
url: Url, // Location of the service
// data: name, //Data sent to server
contentType: ContentType, // content type sent to server
//data: '[{"name":"' + name + '"}]',
dataType: DataType, //Expected data format from server
processdata: ProcessData, //True or False
success: function (msg) {//On Successfull service call
ServiceSucceeded(msg);
},
error: ServiceFailed// When Service call fails
});
}
function ServiceFailed(xhr) {
alert(xhr.responseText);
if (xhr.responseText) {
var err = xhr.responseText;
if (err)
error(err);
else
error({ Message: "Unknown server error." })
}
return;
}
function ServiceSucceeded(result) {
debugger;
if (DataType == "jsonp") {
alert(result);
resultObject = result.helloworld;
var string = result.name ;
alert(string);
}
}
function helloworld() {
debugger;
var uesrid = "";
Type = "GET";
// Url = "http://192.168.X.X/WCFjavascript/Service.svc/helloworld?'"+uesrid+'"';
Url = Url;
DataType = "jsonp"; ProcessData = false;
method = "helloworld";
CallService();
}
$(document).ready(
function () {
helloworld();
}
);
enter code here
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
You seem to lack the ScriptService/ScriptMethod attributes on your service/service methods.
I have a DataList and Update Panel in my page. After implementation, I checked that the response is talking very long time after using Update panels...Here is the study material. I have a Delete Command event in Datalist and works find in the above mentioned case. I was trying to implement Delete Command using Page Methods. Any Idea how to do that?
I basically want to find hidden controls in this event and have to delete the record in `database. Any help will be highly appreciated.
Rest Services
The full application can be downloaded from:
http://sdrv.ms/LJJz1K
This sample uses rest services in ASP.Net (the same concepts can be applied to a MVC application)
The clearer advantage when using rest services vs page methods, is testability.
I will guide you step by step to configure the service:
You need the following references:
System.Web.ServiceModel.dll
System.Web.ServiceModel.Activation.dll
System.Web.ServiceModel.Web.dll
Nuget packages:
jQuery
jQuery plugins:
jQuery Block UI (it’s available as a single script file)
Service info
[ServiceContract]
public interface IMyService
{
[OperationContract]
[WebInvoke(
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "/DeleteFromService",
Method = "DELETE")]
void Delete(int id);
}
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class MyService : IMyService
{
public void Delete(int id)
{
// delete your product
// simulate a long process
Thread.Sleep(5000);
}
}
In Global.asax
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RouteTable.Routes.Ignore("{resource}.axd/{*pathInfo}");
RouteTable.Routes.Add(new ServiceRoute("",
new WebServiceHostFactory(),
typeof(MyService)));
}
In web.config
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
<standardEndpoints>
<webHttpEndpoint>
<standardEndpoint name="" helpEnabled="true"
automaticFormatSelectionEnabled="true" />
</webHttpEndpoint>
</standardEndpoints>
</system.serviceModel>
Register scripts (they can be registered in a master page)
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js" language="javascript" ></script>
<script language="javascript" type="text/javascript" src="Scripts/jquery.blockui.1.33.js"></script>
In a ASP.Net content page (in this sample, I am using a master page)
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<input type="button" value="Delete" id="myButton" />
</asp:Content>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script type="text/javascript" language="javascript">
function deleteFromService() {
if (!confirm("Are you sure you want to delete?")) {
return;
}
$.blockUI();
$.ajax({
cache: false,
type: "DELETE",
async: true,
url: "/DeleteFromService",
data: "3", // get your id to delete
contentType: "application/json",
dataType: "json",
success: function () {
$(document).ajaxStop($.unblockUI);
alert("done");
},
error: function (xhr) {
$(document).ajaxStop($.unblockUI);
alert(xhr.responseText);
}
});
}
jQuery().ready(function () {
$("#myButton").click(deleteFromService);
});
</script>
</asp:Content>
And that’s it, ajax commands the easy way =)