no action=transactResponse in Accept Hosted iframe for Authorize.net - iframe

I'm trying to implement the Authorize.net Accept Hosted hosted checkout solution in a Coldfusion application.
(For all the ColdFusion developers, this code run on BlueDragon.NET 9 which a CF9 implementation. The cfscript stacktrace support is terrible which is why this code is in tags and not in cfscript.)
Using our sandbox authorize.net account, the iframe hosted checkout page shows up. I can fill out the credit card info and submit. I get the receipt, 2 receipt emails from authorize.net and get sent to the confirmation page, but the case "transactResponse" in AuthorizeNetIFrame.onReceiveCommunication never gets triggered. I put a alert in the javascript function to see all the querystrings that come into the iframe.
Other than the coldfusion code to authenticate and get the token (which seems to work) I got the rest of the code from the Authorize.net documentation.
Any idea why I don't see the action=transactResponse query string come into iframe with the response from the authorize.net credit card transaction.
I tried this with a live authorize.net account as well and I get a 'User authentication failed due to invalid authentication values.' on the iframe payment page even though I can authenticate and get a token for the iframe successfully. What am I missing. Any help would be appreciated.
Sensitive parts of the code (i.e. credentials), email, and address have been redacted.
Here is the main code file (this includes the iframe):
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<head>
<title>HostedPayment Test Page</title>
<script src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function () {
$("#btnOpenAuthorizeNetIFrame").click(function () {
$("#add_payment").show();
$("#send_token").attr({ "action": "https://test.authorize.net/payment/payment", "target": "add_payment" }).submit();
$(window).scrollTop($('#add_payment').offset().top - 50);
});
});
</script>
</head>
<body>
<cfif NOT IsDefined("url.CFID") or NOT IsDefined("url.CFTOKEN")>
<p style="color: red;">Error: CFID and CFTOKEN required as URL parameters...</p>
<cfabort />
</cfif>
<cfinclude template="../#client.custom_path#/constants.cfm" />
<cfset variables.LOGIN_TOKEN_URL = "https://apitest.authorize.net/xml/v1/request.api" />
<cfset variables.API_LOGIN_ID = "ZZZZZZZZZZZ" />
<cfset variables.TRANSACTION_KEY = "ZZZZZZZZZZZZZZ" />
<h2>Authenticate</h2>
<cfoutput>
<cfsavecontent variable="variables.soapBody">
<authenticateTestRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<merchantAuthentication>
<name>#variables.API_LOGIN_ID#</name>
<transactionKey>#variables.TRANSACTION_KEY#</transactionKey>
</merchantAuthentication>
</authenticateTestRequest>
</cfsavecontent>
</cfoutput>
<cfhttp url="#variables.LOGIN_TOKEN_URL#"
method="post"
result="variables.result1">
<cfhttpparam
type="xml"
value="#Trim( variables.soapBody )#"
/>
</cfhttp>
<cfdump var="#variables.result1#" />
<cfset variables.response1 = XMLParse(Trim(Right(variables.result1.filecontent, Len(variables.result1.filecontent)-1))) />
<cfset variables.response = StructNew() />
<cfset variables.response.resultCode = xmlSearch(Trim(Right(variables.result1.filecontent, Len(variables.result1.filecontent)-1)),
"//*[ local-name() = 'resultCode' ]"
) />
<cfif IsDefined("variables.response.resultCode[1].XmlText")>
<cfset variables.response.resultCode = variables.response.resultCode[1].XmlText />
</cfif>
<cfset variables.response.code = xmlSearch(Trim(Right(variables.result1.filecontent, Len(variables.result1.filecontent)-1)),
"//*[ local-name() = 'code' ]"
) />
<cfif IsDefined("variables.response.code[1].XmlText")>
<cfset variables.response.code = variables.response.code[1].XmlText />
</cfif>
<cfset variables.response.text = xmlSearch(Trim(Right(variables.result1.filecontent, Len(variables.result1.filecontent)-1)),
"//*[ local-name() = 'text' ]"
) />
<cfif IsDefined("variables.response.text[1].XmlText")>
<cfset variables.response.text = variables.response.text[1].XmlText />
</cfif>
<cfif IsDefined("variables.response.text") AND FindNoCase("Successful", variables.response.text)>
<p style="color: green; font-weight: bold;">Success</p>
<cfelse>
<p style="color: red; font-weight: bold;">Failure</p>
</cfif>
<cfdump var="#variables.response#" />
<cfdump var="#variables.response1#" />
<h2>Get token</h2>
<cfoutput>
<cfsavecontent variable="variables.soapBody2">
<getHostedPaymentPageRequest xmlns="AnetApi/xml/v1/schema/AnetApiSchema.xsd">
<merchantAuthentication>
<name>#variables.API_LOGIN_ID#</name>
<transactionKey>#variables.TRANSACTION_KEY#</transactionKey>
</merchantAuthentication>
<transactionRequest>
<transactionType>authCaptureTransaction</transactionType>
<amount>0.01</amount>
<customer>
<email>ZZZZZZZZ#ZZZZZZZZ.com</email>
</customer>
<billTo>
<firstName>ZZZZZZZZ</firstName>
<lastName>Tester1</lastName>
<company></company>
<address>123 Main Street</address>
<city>ZZZZZZZZ</city>
<state>ZZ</state>
<zip>22222</zip>
<country>US</country>
</billTo>
</transactionRequest>
<hostedPaymentSettings>
<setting>
<settingName>hostedPaymentReturnOptions</settingName>
<settingValue>{"showReceipt": true, "url": "https://ZZZZZZZZ.com/test/hosted_pages/cart_hosted_confirm.cfm", "urlText": "Continue", "cancelUrl": "https://ZZZZZZZZ.com/test/hosted_pages/cart_hosted_cancel.cfm", "cancelUrlText": "Cancel"}</settingValue>
</setting>
<setting>
<settingName>hostedPaymentButtonOptions</settingName>
<settingValue>{"text": "Pay"}</settingValue>
</setting>
<setting>
<settingName>hostedPaymentStyleOptions</settingName>
<settingValue>{"bgColor": "blue"}</settingValue>
</setting>
<setting>
<settingName>hostedPaymentPaymentOptions</settingName>
<settingValue>{"cardCodeRequired": true, "showCreditCard": true, "showBankAccount": false}</settingValue>
</setting>
<setting>
<settingName>hostedPaymentSecurityOptions</settingName>
<settingValue>{"captcha": false}</settingValue>
</setting>
<setting>
<settingName>hostedPaymentShippingAddressOptions</settingName>
<settingValue>{"show": false, "required": false}</settingValue>
</setting>
<setting>
<settingName>hostedPaymentBillingAddressOptions</settingName>
<settingValue>{"show": true, "required":true}</settingValue>
</setting>
<setting>
<settingName>hostedPaymentCustomerOptions</settingName>
<settingValue>{"showEmail": true, "requiredEmail": true, "addPaymentProfile": false}</settingValue>
</setting>
<setting>
<settingName>hostedPaymentOrderOptions</settingName>
<settingValue>{"show": true, "merchantName": "Test Company, LLC"}</settingValue>
</setting>
<setting>
<settingName>hostedPaymentIFrameCommunicatorUrl</settingName>
<settingValue>{"url": "https://ZZZZZZZZ.com/test/hosted_pages/IFrameCommunicator.html"}</settingValue>
</setting>
</hostedPaymentSettings>
</getHostedPaymentPageRequest>
</cfsavecontent>
</cfoutput>
<cfhttp url="#variables.LOGIN_TOKEN_URL#"
method="post"
result="variables.result2">
<cfhttpparam
type="xml"
value="#Trim( variables.soapBody2 )#"
/>
</cfhttp>
<cfdump var="#variables.result2#" />
<cfset variables.response2 = XMLParse(Trim(Right(variables.result2.filecontent, Len(variables.result2.filecontent)-1))) />
<cfset variables.responseToken = StructNew() />
<cfset variables.responseToken.resultCode = xmlSearch(Trim(Right(variables.result2.filecontent, Len(variables.result2.filecontent)-1)),
"//*[ local-name() = 'resultCode' ]"
) />
<cfif IsDefined("variables.responseToken.resultCode[1].XmlText")>
<cfset variables.responseToken.resultCode = variables.responseToken.resultCode[1].XmlText />
</cfif>
<cfset variables.responseToken.code = xmlSearch(Trim(Right(variables.result2.filecontent, Len(variables.result2.filecontent)-1)),
"//*[ local-name() = 'code' ]"
) />
<cfif IsDefined("variables.responseToken.code[1].XmlText")>
<cfset variables.responseToken.code = variables.responseToken.code[1].XmlText />
</cfif>
<cfset variables.responseToken.text = xmlSearch(Trim(Right(variables.result2.filecontent, Len(variables.result2.filecontent)-1)),
"//*[ local-name() = 'text' ]"
) />
<cfif IsDefined("variables.responseToken.text[1].XmlText")>
<cfset variables.responseToken.text = variables.responseToken.text[1].XmlText />
</cfif>
<cfif IsDefined("variables.responseToken.text") AND FindNoCase("Successful", variables.responseToken.text)>
<p style="color: green; font-weight: bold;">Success</p>
<cfset variables.responseToken.token = xmlSearch(Trim(Right(variables.result2.filecontent, Len(variables.result2.filecontent)-1)),
"//*[ local-name() = 'token' ]"
) />
<cfif IsDefined("variables.responseToken.token[1].XmlText")>
<cfset variables.responseToken.token = variables.responseToken.token[1].XmlText />
</cfif>
<cfelse>
<p style="color: red; font-weight: bold;">Failure</p>
</cfif>
<cfdump var="#variables.response2#" />
<cfdump var="#variables.responseToken#" />
<h2>Hosted Page</h2>
<cfif IsDefined("variables.responseToken.token") AND Len(Trim(variables.responseToken.token)) GT 0>
<div>
Open Authorize.net in an iframe to complete transaction
<button id="btnOpenAuthorizeNetIFrame" onclick="">Show Payment Form</button>
</div>
<div id="iframe_holder" class="center-block" style="width:90%;max-width: 1000px">
<iframe id="add_payment" class="embed-responsive-item panel" name="add_payment" width="100%" frameborder="0" scrolling="no" hidden="true">
</iframe>
</div>
<cfoutput>
<form id="send_token" action="" method="post" target="add_payment">
<input type="hidden" name="token" value="#variables.responseToken.token#" />
</form>
</cfoutput>
<script type="text/javascript">
(function () {
if (!window.AuthorizeNetIFrame) window.AuthorizeNetIFrame = {};
AuthorizeNetIFrame.onReceiveCommunication = function (querystr) {
alert('processing 1:'+querystr);
var params = parseQueryString(querystr);
switch (params["action"]) {
case "successfulSave":
break;
case "cancel":
break;
case "resizeWindow":
var w = parseInt(params["width"]);
var h = parseInt(params["height"]);
var ifrm = document.getElementById("add_payment");
ifrm.style.width = w.toString() + "px";
ifrm.style.height = h.toString() + "px";
break;
case "transactResponse":
var ifrm = document.getElementById("add_payment");
ifrm.style.display = 'none';
var formData = { gatewayResponse: params["response"] };
$.ajax({
url: "cart_hosted_async_log.cfm?<cfoutput>#URLTOKEN#</cfoutput>",
type: "POST",
data: formData,
success: function(data, textStatus, jqXHR)
{},
error: function (jqXHR, textStatus, errorThrown)
{}
});
break;
}
};
function parseQueryString(str) {
var vars = [];
var arr = str.split('&');
var pair;
for (var i = 0; i < arr.length; i++) {
pair = arr[i].split('=');
vars.push(pair[0]);
vars[pair[0]] = unescape(pair[1]);
}
return vars;
}
}());
</script>
</cfif>
</body>
</html>
Here's the IFrameCommunicator.html code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Iframe Communicator</title>
<script type="text/javascript">
//<![CDATA[
function callParentFunction(str) {
if (str && str.length > 0
&& window.parent
&& window.parent.parent
&& window.parent.parent.AuthorizeNetIFrame
&& window.parent.parent.AuthorizeNetIFrame.onReceiveCommunication)
{
// Errors indicate a mismatch in domain between the page containing the iframe and this page.
window.parent.parent.AuthorizeNetIFrame.onReceiveCommunication(str);
}
}
function receiveMessage(event) {
if (event && event.data) {
callParentFunction(event.data);
}
}
if (window.addEventListener) {
window.addEventListener("message", receiveMessage, false);
} else if (window.attachEvent) {
window.attachEvent("onmessage", receiveMessage);
}
if (window.location.hash && window.location.hash.length > 1) {
callParentFunction(window.location.hash.substring(1));
}
//]]/>
</script>
</head>
<body>
</body>
</html>

On https://developer.authorize.net/api/reference/features/accept_hosted.html,
under Transaction Response is the following note:
Important: If you host the form in an iframe, you must include the
iframe communicator URL in the hostedPaymentIFrameCommunicatorUrl
parameter of your getHostedPaymentPageRequest API call. To ensure that
you receive a response code, you must also set showReceipt to
false.
Bolding added by me. After setting showReceipt to false, I get the response against my Sandbox account.
For the error:
'User authentication failed due to invalid authentication values.'
I found out my answer from Authorize.net support. It occurs when your site/software sends a request for a payment or creation of a profile to Authorize.Net via the API and we don’t recognize the API Login ID and Transaction Key that were submitted in the request. There are only three possible causes of this error:
Your site/software is posting to a live account's API Login ID and Transaction Key while using the test environment URL at https://apitest.authorize.net/xml/v1/request.api -- For live accounts, please ensure your site/software is posting to https://api.authorize.net/xml/v1/request.api instead.
Your site/software is posting to a test account's API Login ID and Transaction Key while using the live environment at https://api.authorize.net/xml/v1/request.api -- For test accounts, please post to https://apitest.authorize.net/xml/v1/request.api instead.
Your site/software is using an incorrect API Login ID or Transaction Key. If this is the case then we suggest to verify your API Login ID on the Authorize.Net portal or generate a new Transaction Key if needed. You can use this site as well on how to verify/generate these: https://support.authorize.net/s/article/What-Are-the-API-Login-ID-and-Transaction-Key
In my case I found the token was being sent to https://test.authorize.net/payment/payment not https://accept.authorize.net/payment/payment. Changed it and now the code works.

Related

Required CommonMultipartFile parameter 'testFile' is not present in spring mvc

when I upload a file to springmvc, getting a error message "Required CommonsMultipartFile parameter 'textFile' is not present", I don't know why I can meet it, that's my code.
<form id="form" enctype="multipart/form-data">
<input type="text" id="username" name="username" />
<input type="file" id="file" name="textFile" />
<input type="button" onclick="test()" value="上传" />
</form>
<script type="text/javascript">
function test(){
var form = new FormData(document.getElementById("form"));
$.ajax({
url:"http://localhost:8080/giraffe/upload1",
type:"post",
data:form,
cache: false,
processData: false,
contentType: false,
success:function(data){
alert("success!");
}
});
}
That's my controller and configuration.
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<property name="maxUploadSize" value="10240000"/>
</bean>
#RequestMapping(path = "/upload1", method = RequestMethod.POST)
public Object updloadImage(#RequestParam("textFile") CommonsMultipartFile file){
String fileName = file.getOriginalFilename();
return null;
}
Maybe you should change your RequestParam to
#RequestParam MultipartFile textFile
This is of type "org.springframework.web.multipart.MultipartFile"
Also important is that you expose the commons library to your server. So you must add your commons-fileupload-x.x.x.jar to the WEB-INF/lib folder.
And your controller must add the path
#RequestMapping(value="/giraffe")
because your AJAX-Request points to /giraffe/upload1
To check what and if anything is presented to the controller you can add
#RequestParam (required=false) ...
If you have an jsp-File for the page and no plain html then you can use the jstl. This can help you avoid problems with the correct url in your AJAX-request. Like this
url: "<c:url value='/giraffe/upload1' />",

how to correctly render a response on an gsp from on the same page as the request (REST call) in grails

I am new to grails and groovy.
I am trying to find out how to render a response from an action in a grails controller IN THE SAME gsp - but in a DIFFERENT SECTION OF THE gsp - as the gsp that takes the request (in this case a web form gsp page)?
any links or turorials or just straight to the point "do this" kind of replies are welcomed.
========= background with my code attempt) =========
Here is the code I am working with. It is a Grails application in which I am using a bootstrap template (available for free on the internet of course).
Now the actual code itself for functionality works. What I am having an issue with is this:
I have a gsp page that uses a css template and another gsp temlate for layout (this is from the bootstrap theme). I can start the page with the gsp+css tempate using this code (snippet) in my gsp page:
<g:layoutBody/>
This allows me to call my calling controller code in this gsp file for the request:
<body>
<g:form name="form" controller="apiStart" id="form">
<div><g:select name="protocolType" value="restCall" from="${["-select-", "GET", "POST", "PUT", "DELETE"]}"/> &nbsp <label>URL: </label><g:textField name="url" value="${url}" />
&nbsp <label>username: </label><g:textField name="userName" value="${userName}" /> &nbsp <label>password: </label><g:textField name="passWord" value="${passWord}" /></div>
%{--<div class="text-field"><label>URL: </label><g:textField name="url" value="${url}" /></div>--}%
%{--<div class="text-field"><label>username: </label><g:textField name="userName" value="${userName}" /></div>
<div class="text-field"><label>password: </label><g:textField name="passWord" value="${passWord}" /></div>--}%
<br>
<div><label>Use Advanced Parameters?</label><g:checkBox name="useAdvParms" value="${false}" /></div>
<div class="text-field"><label>Header1: </label><g:textField name="header1" value="${header1}" /> &nbsp <label>Value1: </label><g:textField name="value1" value="${header2}" /></div>
%{--<div class="text-field"><label>Value1: </label><g:textField name="value1" value="${header2}" /></div>--}%
<div class="text-field"><label>Header2: </label><g:textField name="header2" value="${header3}" /> &nbsp <label>Value2: </label><g:textField name="value2" value="${header4}" /></div>
%{--<div class="text-field"><label>Value2: </label><g:textField name="value2" value="${header4}" /></div>--}%
<br>
<div class="submit"><g:actionSubmit value="Submit" action="save"/></div>
</g:form>
</body>
And then this gsp code for the response:
<body>
<h3>API Test Results</h3>
API Tested: ${apiStart.url}, Response: ${apiStart.response3}
<br>
%{--<g:textArea name="myField" value="myValue" rows="20" cols="100"/>--}%
<div class="textarea"><label>Output</label><br><g:textArea name="myField" value="${apiStart.result3}" />
</div>
%{--Responce Code: ${apiStart.response3}<br>--}%
%{--Response: <br> ${apiStart.result3} <br>--}%
</body>
My issueis this: it works fine as separate pages. I want to render the results of the request on the same page as the calling request.
in the screen shot attached: I want to put the results in the text box where it says "Output Displayed here...."
I assumed templates in grails is the way to go about it; but I get a Java Null pointer exception when I try to insert the template into that part of the code.
here is the template gsp code:
<div>
API Tested: ${apiStart.url}, Response: ${apiStart.response3}
<br>
%{--<g:textArea name="myField" value="myValue" rows="20" cols="100"/>--}%
<div class="textarea"><label>Output</label><br><g:textArea name="myField" value="${apiStart.result3}" />
</div>
%{--Responce Code: ${apiStart.response3}<br>--}%
%{--Response: <br> ${apiStart.result3} <br>--}%
</div>
======== UPDATE: Addidng controller code ===========
controller:
package hellograils
import org.springframework.http.HttpMethod
import org.springframework.web.client.RestTemplate
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import java.util.Base64;
import java.util.Map;
import static javax.xml.bind.DatatypeConverter.parseString;
class ApiStartController {
def index() {
}
def save() {
def apiStart = new ApiStart(params)
apiStart.save()
render (view: "apiStart", model: [apiStart: apiStart])
System.out.println(apiStart.url);
System.out.println(apiStart.passWord);
System.out.println(apiStart.userName);
RestTemplate restTemplate = new RestTemplate();
System.out.println ("URI under Test is: " + String.valueOf(apiStart.url) + ". \n" + "Please stand by for results ... \n \n ");
//String linkUT = apiStart.url;
// apiStart.result3 = restTemplate.exchange(apiStart.url, HttpMethod.GET, null, String.class).getBody();
// apiStart.response3 = restTemplate.exchange(apiStart.url, HttpMethod.GET, null, String.class).getStatusCode();
if (apiStart.protocolType == "GET") {
apiStart.result3 = restTemplate.exchange(apiStart.url, HttpMethod.GET, null, String.class).getBody();
apiStart.response3 = restTemplate.exchange(apiStart.url, HttpMethod.GET, null, String.class).getStatusCode();
render(view: "apiStart", model:[apiStart: apiStart])
System.out.println(apiStart.protocolType);
System.out.println(apiStart.result3);
System.out.println(apiStart.response3);
}
else if (apiStart.protocolType == "POST") {
//apiStart.result3 = restTemplate.exchange(apiStart.url, HttpMethod.POST, request, String.class).getBody();
apiStart.result3 = restTemplate.execute(apiStart.url, HttpMethod.POST, null, String.class).getBody();
apiStart.response3 = restTemplate.exchange(apiStart.url, HttpMethod.POST, null, Map.class).getStatusCode();
// apiStart.result3 = restTemplate.exchange(apiStart.url, HttpMethod.POST, null, String.class).getBody();
// apiStart.response3 = restTemplate.exchange(apiStart.url, HttpMethod.POST, null, String.class).getStatusCode();
render(view: "apiStart", model:[apiStart: apiStart])
System.out.println(apiStart.protocolType);
System.out.println(apiStart.result3);
System.out.println(apiStart.response3);
}
else if (apiStart.protocolType == "PUT") {
render(view: "apiStart", "coming soon ....")
System.out.println(apiStart.protocolType);
System.out.println(apiStart.result3);
System.out.println(apiStart.response3);
}
else if (apiStart.protocolType == "DELETE") {
render(view: "apiStart", "coming soon ....")
System.out.println(apiStart.protocolType);
System.out.println(apiStart.result3);
System.out.println(apiStart.response3);
}
}
}
=================== end of controller code ==================
and here is the domain controller code:
================ domain model code ==========================
domain:
package hellograils
class ApiStart {
String url
String userName
String passWord
String result3
String response3
String header1
String header2
String value1
String value2
String protocolType
// static constraints = {
// }
}
======================= end of domain ================
Can someone advise and show me the best way to do this?
thanks.
ironmantis7x
Include the results pane in your gsp, but wrap it with a g:if tag. Supply a flag variable that determines whether grails renders that portion of the output or not.
<g:if test="${apiStart != null}">
<div class="textarea">
<label>Output</label><br>
<g:textArea name="myField" value="${apiStart.result3}" />
</div>
</g:if>
In the edit method, define apiStart as:
def apiStart = params.apiStart
When the edit view is initially rendered, the results pane should not appear.
In the save method, do whatever you're doing, define the apiStart map, populate it, and redirect to the edit method passing the apiStart as a parameter.
redirect(view:'edit', params:[apiStart:apiStart])
Or something like that. Haven't seen your controller code...

how to send email from web page in the most simple way with asp.net?

In my web site I have "contuct us" page and I want the manager able to reply via email
to the customers.
All the process need to be in the server side.
It is important to note that I works with Webmatrix development environment...
So considering my web development what is the simple way for me to add the ability to
send email?
My HTML code is:
foreach(var row in db.Query(displayApplicant,nameOfcustomer))
{
<tr>
<td class="dispExpertActScreen">#row.messegeID</td>
<td class="dispExpertActScreen">#row.name</td>
<td class="dispExpertActScreen">#row.email</td>
<td class="dispExpertActScreen">#row.isCustomer</td>
<td class="dispExpertActScreen">#row.userID</td>
<td class="dispExpertActScreen">#row.content</td>
<td class="dispExpertActScreen">answer the question</td>
<td class="dispExpertActScreen">remove</td>
</tr>
}
the javascript function: (to save details in hidden fields)
<script type="text/javascript">
function answerBox(messegeID,userID) {
var msg = prompt('answer to customer:');
document.getElementById('answer').value = msg;
document.getElementById('ansMode').value = 'true';
document.getElementById('msgID').value = messegeID;
document.getElementById('user').value = userID;
document.getElementById('ansMessege').submit();
}
</script>
the hidden fields:
<form method="post" id="ansMessege" style="font-size: medium; margin-top: 10%" dir="rtl">
<input type="hidden" name="answer" id="answer" value="">
<input type="hidden" name="msgID" id="msgID" value="">
<input type="hidden" name="user" id="user" value="">
<input type="hidden" name="ansMode" id="ansMode" value="">
</form>
the asp.net code:
<%# Import Namespace="System.Web.Mail" %>
#{
Layout = "~/_ManagerLayout.cshtml";
Page.Title = "Management Applications";
}
#{
var db = Database.Open("MyProjectSite");
var display="no";
var displayApplicant="";
var nameOfcustomer="";
var category="";
var yesNo="";
if(IsPost)
{
if(Request.Form["ansMode"] == "true")
{
var selectQuery="SELECT * FROM messegesFromCustomers";
var id=Request.Form["msgID"];
var msg=Request.Form["answer"];
var user=Request.Form["user"];
foreach(var row in db.Query(selectQuery))
{
if(row.messegeID == Convert.ToInt32(id))
{
if(row.isCustomer == "yes")// **send the messege to customer account**
{
var insertQuery="UPDATE messegesFromCustomers SET answer=#0 WHERE messegeID=#1";
db.Execute(insertQuery,msg,id);
Response.Write("<script>alert('your answer sent successfully');</script>");
break;
}
else
{
// **Send messege to Occasional customer via email**
// **here I want to add code for sending email...**
string from = "ofirhgy#gmail.com";
string to = "ofirhgy#gmail.com";
string subject = "Hi!";
string body = "How are you?";
SmtpMail.SmtpServer = "mail.gmail.com";
SmtpMail.Send(from, to, subject, body);
break;
}
}
}
}
}
}
As you see I try to use WebMail.Send(...) but I don't know how...
In addition to that I saw that someone wrote that there is need to add some code
to the Web.config or something like that....
thanks you for help.
Edit:I edit the code and I put the line:
<%# Import Namespace="System.Web.Mail" %>
in the top of the asp.net page but I get this error:
Parser Error Message: A space or line break was encountered after the "#" character. Only valid identifiers, keywords, comments, "(" and "{" are valid at the start of a code block and they must occur immediately following "#" with no space in between.
Can anybody place for me the exact code?
First, we need to import the System.Web.Mail namespace:
<%# Import Namespace="System.Web.Mail" %>
Sending the message is a matter of calling SmtpMail.Send() with the following arguments: sender, recipient, subject and body. For example, we'd send an email in C# like this:
string from = "sender#example.com";
string to = "recipient#example.com";
string subject = "Hi!";
string body = "How are you?";
SmtpMail.SmtpServer = "mail.example.com";
SmtpMail.Send(from, to, subject, body);
SmtpMail.SmtpServer lets you specify the mail server used to deliver your message.
Content from here
I found a solution to that
In my code I added this and the email sent sucessfully:
if(isCustomer == "yes")
{
db.Execute(insertQuery,msg,id);
db.Execute(deleteQuery,id);
}
else
{
WebMail.SmtpServer = "smtp.gmail.com";
WebMail.EnableSsl = true;
WebMail.SmtpPort = 587;//25
WebMail.UserName = "my gmail user name";
WebMail.Password = "my gmail password";
WebMail.From = "my address of email";
// Send email
WebMail.Send(
to: email,
subject: "Message from "some name of site" - Site",
body: msg);
db.Execute(deleteQuery,id);
}

Restrict upload by filetype or mimetype using Dexterity on Plone

I have a custom content type, built with dexterity. In the schema (The schema is listed below), I use 'plone.namedfile.field.NamedFile' for attachements/uploads.
I would like to restrict uploads so that only mp3 files can be attached to my content type. What is the best approach for achieving this?
Here is the full schema/model for my content type:
<model xmlns="http://namespaces.plone.org/supermodel/schema">
<schema>
<field name="date" type="zope.schema.Date">
<description />
<title>Date</title>
</field>
<field name="speaker" type="zope.schema.TextLine">
<description />
<title>Speaker</title>
</field>
<field name="service" type="zope.schema.Choice">
<description />
<title>Service</title>
<values>
<element>1st Service</element>
<element>2nd Service</element>
</values>
</field>
<field name="audio_file" type="plone.namedfile.field.NamedFile">
<description />
<title>Audio File</title>
</field>
</schema>
</model>
I shall begin my search here: http://plone.org/products/dexterity/documentation/manual/developer-manual/reference/default-value-validator-adaptors
I've decided to use javascript for my first line of validation.
I've based my solution on information found at <input type="file"> limit selectable files by extensions
Based on the advice my script looks something like this:
$(document).ready( function() {
function checkFile(event) {
var fileElement = document.getElementById("form-widgets-audio_file-input");
var fileExtension = "";
if (fileElement.value.lastIndexOf(".") > 0) {
fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
}
if (fileExtension == "mp3") {
return true;
}
else {
alert("You must select a mp3 file for upload");
return false;
}
}
$("form#form").bind("submit",checkFile);
});
This is half the solution, next I'll need to add validation on the server side.

POST data getting 'lost' somewhere

UPDATE
So it turns out internet exploder's stranglehold on "security" to "make up" for being so bad at security was causing my problems. I should have checked that out first haha. Thanks everyone for the input, it has given me ideas on how to optimize my application :D
I am writing a web app (in ASP.NET 3.5) that integrates with a platform app. The platform app takes the user's credentials and puts them into an "empty" HTML page that consists of a form with hidden items containing said credentials and POSTS to the webapp (default.aspx):
<HTML>
<HEAD>
<SCRIPT LANGUAGE=JSCRIPT>
function OnLoad(){
try {
document.form1.submit();
}
catch(e){
}
}
</SCRIPT>
</HEAD>
<BODY OnLoad="OnLoad()">
<FORM ACTION="http://localhost:51816/gs_ontheweb/default.aspx" METHOD=POST NAME=form1 TARGET="_NEW">
<INPUT TYPE="HIDDEN" NAME="ClientID" VALUE="123456">
<INPUT TYPE="HIDDEN" NAME="Password" VALUE="2830088828">
<INPUT TYPE="HIDDEN" NAME="PracType" VALUE="051">
<INPUT TYPE="HIDDEN" NAME="Encrypt" VALUE="12345620081111">
</FORM>
</BODY>
</HTML>
When my default.aspx page gets loaded up, it calls the following function:
Dim ClientID As String = Request.Form("ClientID")
Dim PassWord As String = Request.Form("Password")
Dim PracType As String = Request.Form("PracType")
Each one of them result in empty strings. Any ideas on why this is happening? Thanks in advance.
EDIT: Is there something I need to configure in my web.config file to make this work properly? Request.Params("<param name>") does not work.
Your issue is the "Target" property on the Form. Why is this here?
(I also took the liberty of cleaning your HTML up a little)
<html>
<head>
<title>Test JS Post</title>
<script type="text/javascript" language="javascript">
<!--
function OnLoad(){
try
{
alert("Posting...");
document.form1.submit();
}
catch(e)
{
alert("ERROR!");
alert(e);
}
}
//-->
</script>
</head>
<body onload="OnLoad()">
<form action="http://localhost:49684/Default.aspx" method="post" name="form1">
<input type="hidden" name="ClientID" value="123456" />
<input type="hidden" name="Password" value="2830088828" />
<input type="hidden" name="PracType" value="051" />
<input type="hidden" name="Encrypt" value="12345620081111" />
<h1>This is in the form. Submit me here:</h1><input type="submit" value="foo" />
</form>
</body>
</html>
In the code behind of Default.aspx:
Private Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
For Each value As String In Request.Form.Keys
Debug.WriteLine(String.Format("{0} = ""{1}""", value, Request.Form.Item(value)))
Next
End Sub
That HTML is just on the user's harddrive? Maybe the browser security won't let that POST because it's deemed to be a risk.
As a test -- take that exact HTML file and put it on your webserver and then browse to it. If it works, might be the browser refusing to send the data. You could check with Fiddler (for IE) or Firebug in FireFox.
Why not use System.Net.WebClient?
Some sample code (sorry, it's C#. Looks like your looking for VB. I can't translate quickly.)
System.Net.WebClient wc = new System.Net.WebClient();
byte[] b;
byte[] res;
string formdata = "text=test text&password=secret&checkbox=on&textarea=a longer text sentence&submit=submit";
// encode the form data string into a byte array
b = System.Text.Encoding.ASCII.GetBytes(formdata);
// set the content type for a form
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
// POST and get data
res = wc.UploadData("http://localhost:51816/gs_ontheweb/default.aspx", b);
//convert the return page from byte[] to ascii
string s = System.Text.Encoding.ASCII.GetString(res);

Resources