jQuery-Validation-Engine - Validation File MIME Type - jquery-validation-engine

I would like to use the jQuery-Validation-Engine to validate the MIME Type of a file input. How could I do this?
My approach would be something like this:
function checkMIME(field, rules, i, options){
var file = $("#userfile")[0].files[0];
var MimeFilter = /^(image\/bmp|image\/gif|image\/jpeg|image\/png|image\/tiff)$/i;
if (! MimeFilter.test(file.type)) {
return options.allrules.validate2fields.alertText;
}
}
Thanx
Kashuda

OK, found a solution by adding these lines to the query.validationEngine-LANG.js:
"validateMIME": {
"func": function(field, rules, i, options){
//add to input tag: data-validation-engine="validate[required, custom[validateMIME[image/jpeg|image/png]]]"
var fileInput = field[0].files[0];
var MimeFilter = new RegExp(rules[3],'i');
if (fileInput) {
return MimeFilter.test(fileInput.type);
} else { return true;}
},
"alertText": "* Wrong Mime Type."
},

By modifying your code, I have implemented another way to validate File MIME type:
First append the following code into the '_validateField' method of jquery.validationEngine.js file
case "checkFileType":
errorMsg = methods._checkFileType(field, rules, i, options);
break;
Then append the following code into the same file
_checkFileType: function (field, rules, i, options) {
var uploadedFile = $(field);
if (uploadedFile) {
var extensions = rules[i + 1];
var mimeFilter = new RegExp(extensions);
if (!mimeFilter.test($(uploadedFile).val().split('.').reverse()[0])) {
return options.allrules.checkFileType.alertText;
}
}
else {
return true;
}
},
Finally,
append the following line to jquery.validationEngine-en.js file
"checkFileType": {
"regex": "none",
"alertText": "* Wrong file Type."
},
Usage:
<input type="file" name="file" id="myfile" class="validate[checkFileType[jpg|jpeg|gif|JPG|png|PNG]]"/>

Just add this to jquery.validationEngine.js if the image is not required option add to input tag:
class="validate[optional, custom[validateMIME[image/jpeg|image/png]]]"
If it is a required field add
add to input tag:
class="validate[required, custom[validateMIME[image/jpeg|image/png]]]"
"validateMIME": {
"func": function(field, rules, i, options){
//add to input tag: data-validation-engine="validate[required, custom[validateMIME[image/jpeg|image/png]]]"
var fileInput = field[0].files[0];
var MimeFilter = new RegExp(rules[3],'i');
if (fileInput) {
return MimeFilter.test(fileInput.type);
} else { return true;}
},
"alertText": "* Wrong Mime Type."
},

This works for me
In form field
class="validate[required], custom[validateMIME[pdf|doc|docx]"
In query.validationEngine-LANG.js
"validateMIME": {
"func": function(field, rules, i, options){
var uploadedFile = $(field);
if (uploadedFile) {
var extensions = rules[i+2];
var mimeFilter = new RegExp(extensions);
return (mimeFilter.test($(uploadedFile).val().split('.').reverse()[0])) ? true : false;
}
},
"alertText": "Wrong File Extension"
},

Related

How to send a excel attachment in QCubed

This is what i am trying
$attach is the path to my excel => c:/xampp/htdocs/project/excel.xlsx
Notification::SendEmail('xyz#gmail.com', 'abc#gmail.com', "Subject","message", $attach);
If the$attach is removed then the email will go.
But it fails if i add the attachment
SendEmail function
public static function SendEmail($mixFrom, $mixTo, $strSubject, $strMessage, $mixAttachment = null, $mixCc = null, $mixBcc = null) {
// Declaration of Local Variables
$strSMTPHost = QApplication::getSettingValue(Mssetting::SMTP_HOST);
$strSMTPPort = QApplication::getSettingValue(Mssetting::SMTP_PORT);
$objMessage = Swift_Message::newInstance($strSubject, $strMessage, 'text/html');
// Set the source/destination data
$objMessage->setFrom($mixFrom);
$objMessage->setTo($mixTo);
$objMessage->setCc($mixCc);
$objMessage->setBcc($mixBcc);
// Check for attachments
if(is_array($mixAttachment)) {
foreach($mixAttachment as $strFilePath)
$objMessage->attach (Swift_Attachment::fromPath ($strFilePath));
}
elseif(is_string($mixAttachment)) {
$objMessage->attach(Swift_Attachment::fromPath($mixAttachment));
}
// Setup the transport
$objTransport = Swift_SmtpTransport::newInstance();
if($strSMTPHost) $objTransport->setHost ($strSMTPHost);
if($strSMTPPort) $objTransport->setPort($strSMTPPort);
// Setup the mailer
$objMailer = Swift_Mailer::newInstance($objTransport);
// Send the message
$objMailer->send($objMessage, $arrFailures);
if($arrFailures)
return $arrFailures;
return true;
}
I got the answer for this,
use this code:
$Attachment = $file_path; // path to your excel
Notification::SendEmail('from#abc.com',to#abc,com, "Subject", "Message", $Attachment);
in Notification.php
class Notification {
public static function SendEmail($mixFrom, $mixTo, $strSubject, $strMessage, $mixAttachment, $mixCc = null, $mixBcc = null) {
// Declaration of Local Variables
$strSMTPHost = QApplication::getSettingValue(Mssetting::SMTP_HOST);
$strSMTPPort = QApplication::getSettingValue(Mssetting::SMTP_PORT);
$objMessage = Swift_Message::newInstance($strSubject, $strMessage, 'text/html');
// Set the source/destination data
$objMessage->setFrom($mixFrom);
$objMessage->setTo($mixTo);
$objMessage->setCc($mixCc);
$objMessage->setBcc($mixBcc);
// Check for attachments
if(is_array($mixAttachment)) {
foreach($mixAttachment as $strFilePath)
$objMessage->attach (Swift_Attachment::fromPath ($strFilePath));
}
elseif(is_string($mixAttachment)) {
$objMessage->attach(Swift_Attachment::fromPath($mixAttachment));
}
// Setup the transport
$objTransport = Swift_SmtpTransport::newInstance();
if($strSMTPHost) $objTransport->setHost ($strSMTPHost);
if($strSMTPPort) $objTransport->setPort($strSMTPPort);
// Setup the mailer
$objMailer = Swift_Mailer::newInstance($objTransport);
// Send the message
$objMailer->send($objMessage, $arrFailures);
if($arrFailures)
return $arrFailures;
return true;
}
This will do the work.

How can I pass object properties to onSyndicationSuccess event while using SMF.Net.WebClient dynamically

I'm trying to create a central function for dynamic web requests.
function makeWebRequest(remoteURL, requestString, callBackFunction) {
var myWebRequest = new SMF.Net.WebClient({
url : remoteURL,
httpMethod : "POST",
requestString : requestString,
requestHeaders : [
"Content-Type: application/x-www-form-urlencoded"],
onSyndicationSuccess : callBackFunction,
onServerError : function (e) {
alert(e);
}
});
myWebRequest.run(false);
}
While calling makeWebRequest, passing a callBackFunction to it like;
var remoteURL = "http://parse.com/12/test";
var requestString = "category=news&type=world";
function callBackFunction(e) {
responseText = this.responseText;
if (responseText != null) {
parsedJSON = JSON.parse(responseText);
}
}
makeWebRequest(remoteURL,requestString,callBackFunction);
Application raises an error at line
responseText = this.responseText;
How can I pass myWebRequest itself to a function like that?
I used your codeLines. I just add a textButton to Page1, and it works fine both for Android and iOS .
In Global.js;
function makeWebRequest(remoteURL, requestString, callBackFunction) {
var myWebRequest = new SMF.Net.WebClient({
url : remoteURL,
httpMethod : "POST",
requestString : requestString,
requestHeaders : [
"Content-Type: application/x-www-form-urlencoded"],
onSyndicationSuccess : callBackFunction,
onServerError : function (e) {
alert(e);
}
});
myWebRequest.run(false);
}
var remoteURL = "http://parse.com/12/test";
var requestString = "category=news&type=world";
function callBackFunction(e) {
var responseText = this.responseText;
alert(responseText);
if (responseText != null) {
parsedJSON = JSON.parse(responseText);
}
}
function Global_Events_OnStart(e) {
changeLang(Device.language, true);
include("BC.js"); //included for future BC support. Removing is not advised.
// Comment following block for navigationbar/actionbar sample. Read the JS code file for usage.
// Also there is a part of code block in Page1, which should be copied to every page for HeaderBar usage
load("HeaderBar.js");
header = new HeaderBar();
// Uncomment following block for menu sample. Read the JS code file for usage.
/*
load("Menu.js");
/**/
}
function Global_Events_OnError(e) {
switch (e.type) {
case "Server Error":
case "Size Overflow":
alert(lang.networkError);
break;
default:
SES.Analytics.eventLog("error", JSON.stringify(e));
//change the following code for desired generic error messsage
alert({
title : lang.applicationError,
message : e.message + "\n\n*" + e.sourceURL + "\n*" + e.line + "\n*" + e.stack
});
break;
}
}
In Page1.js;
function Page1_Self_OnKeyPress(e) {
if (e.keyCode === 4) {
Application.exit();
}
}
function Page1_Self_OnShow() {
//Comment following block for removing navigationbar/actionbar sample
//Copy this code block to every page onShow
header.init(this);
header.setTitle("Page1");
header.setRightItem("RItem");
header.setLeftItem();
/**/
}
function Page1_TextButton1_OnPressed(e){
makeWebRequest(remoteURL,requestString,callBackFunction);
}
it works fine. Check your makeWebRequest function, must be on Global.js. Also define "responseText" variable with "var".

Polymer Clone Objects

How can we clone an object in Polymer?
Example
this.colorsAsc.push({color: 'red'});
this.colorsDesc = this.colorsAsc.reverse();
this.colorsDesc[0].color = 'blue'; // Both will be blue doing this
I can do it in these many functionalities What is the most efficient way to deep clone an object in JavaScript? but I wonder if there is a way in Polymer to do that?
Angular does it https://docs.angularjs.org/api/ng/function/angular.copy
You can try the following hack:
this.colorsDesc = JSON.parse(JSON.stringify(this.colorsAsc.reverse());
I have had the same question here, where I have finally also found and posted an answer.
Short version:
newElement = element.cloneNode(true);
for(var i in element.properties) {
newElement[i] = element[i]
}
To clone a utility via Polymer
Full implementation:
(function(callBackFn) {
Polymer({
//Component Name
is: 'my-cloner',
properties: {
//Declare a published property
cloneableObject: { //Placeholder for Object to be cloned
reflectToAttribute: true,
type: Object,
notify: true
}
},
attached: function() {
//Hide if this component got attached
this.hidden = true;
},
getClone: function(incomingcloneableObject) { //Will be called to get the Clone
this.cloneableObject = this.cloneableObject || incomingcloneableObject;
switch (typeof this.cloneableObject) {
case "undefined":
return null;
break;
case "object":
var localClone = this.cloneNode();
return (localClone.cloneableObject);
break;
case "boolean":
return new Boolean(this.cloneableObject).valueOf();
//Other possible way
//return(this.cloneableObject ? true : false);
break;
case "number": //NaN is taken care of
return new Number(this.cloneableObject).valueOf();
//Other possible way
//return(this.cloneableObject * 1);
break;
case "string":
return new String(this.cloneableObject).valueOf();
//Other possible way
//return(this.cloneableObject + '');
break;
default:
return null;
}
}
});
//adding Util into window
callBackFn();
})(function() {
window.cloneUtil = document.createElement('my-cloner');
});
//To use this util
//window.cloneUtil.getClone();

Need if-else advice in actionscript3

function clickButtonHandler(event:MouseEvent):void
{
var message:Object = new Object();
message.text = txtMessage.text;
message.userName = txtUser.text;
//Posts to this swf
showMessage(message);
//Posts to ALL OTHER swf files..
group.post(message);
}
function showMessage(message:Object):void
{
output_txt.appendText(message.userName+": "+message.text + "\n");
}
function jsalertwindow(event:MouseEvent):void
{
var alert:URLRequest = new URLRequest("javascript:alert('Please enter your User name')");
navigateToURL(alert, "_self");
}
As you can see there are two function which are contain mouseevent. I want to send those function with an if-else statement. If user write something in text input component which name is txtUser and,
send_btn.addEventListener(MouseEvent.CLICK, clickButtonHandler);
will work, else(if the user forget writing anything)
send_btn.addEventListener(MouseEvent.CLICK, jsalertwindow);
will work.
And one more question should i use MouseEvent.CLICK or MouseEvent.MOUSE_DOWN? Thanks for your advice.
Assign a single handler to the button click (MouseEvent.CLICK is the right event to use) and check the field is populated in the handler:
function clickButtonHandler(event:MouseEvent):void
{
var message:Object = new Object();
// Check the field is populated
if (txtUser.text != "")
{
message.text = txtMessage.text;
message.userName = txtUser.text;
showMessage(message);
//Posts to ALL OTHER swf files..
group.post(message);
}
else
{
// Nothing in the input field, show the alert
showAlert();
}
}
function showMessage(message:Object):void
{
output_txt.appendText(message.userName+": "+message.text + "\n");
}
function showAlert():void
{
var alert:URLRequest = new URLRequest("javascript:alert('Please enter your User name')");
navigateToURL(alert, "_self");
}

How to save base64 file to the client using JavaScript?

I have the gotten a certain result from the Notes tab.
The link you see inside the iframe is the name of the file.
I have the DocumentBody from the annotation in some format that looks like base64.
How do I download it?
Thanks,
Fabio
Perform a JQuery request to a URL like this
Xrm.Page.context.getServerUrl() + "XRMServices/2011/OrganizationData.svc/ActivityMimeAttachmentSet(guid'abc...')?$select=Body"
By specifying the select you will request only what you want.
Assign the result to a variable and prepend
data:application/pdf;base64,
From there you could display it inline as an HTML object or try to open it as a new window with
window.location or window.open or document.location.href
I had already the base64 documentbody string extracted like this:
function getSla() {
// Define SOAP message
var objectId;
if (typeof crmForm === "undefined") {
objectId = parent.crmForm.ObjectId;
}
else {
objectId = crmForm.ObjectId;
}
var xml =
[
"<?xml version='1.0' encoding='utf-8'?>",
"<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" ",
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ",
"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">",
GenerateAuthenticationHeader(),
"<soap:Body>",
"<RetrieveMultiple xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>",
"<query xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' ",
"xsi:type='q1:QueryExpression'>",
"<q1:EntityName>annotation</q1:EntityName>",
"<q1:ColumnSet xsi:type='q1:AllColumns' />",
"<q1:Distinct>false</q1:Distinct><q1:Criteria><q1:FilterOperator>And</q1:FilterOperator>",
"<q1:Conditions><q1:Condition><q1:AttributeName>objectid</q1:AttributeName><q1:Operator>Equal</q1:Operator>",
"<q1:Values><q1:Value xsi:type=\"xsd:string\">",
objectId,
"</q1:Value></q1:Values></q1:Condition></q1:Conditions></q1:Criteria>",
"</query>",
"</RetrieveMultiple>",
"</soap:Body>",
"</soap:Envelope>"
].join("");
var resultXml = executeSoapRequest("RetrieveMultiple", xml);
var result = filter(resultXml.getElementsByTagName("q1:filename"), function (element) {
return /master.*sla/i.test(element.text);
});
if (result.length == 0) {
return null;
}
else {
return result[0].parentNode;
}
}
function getSlaDocumentBody(sla) {
return sla.getElementsByTagName("q1:documentbody")[0].text;
}
window.open("data:application/pdf;base64," + getSlaDocumentBody(sla));
It opened a new window with the string data:application/pdf.......... in the address bar but did nothing. I would prefer that solution indeed.
Ended up using srasmussen solution in here: http://social.microsoft.com/Forums/en/crm/thread/05134277-dd76-4fbb-8f6e-89b1a2a45af1.
var URL = serverUrl + "/userdefined/edit.aspx?etc=5&id=" + slaId;
$.get(URL, function (data) {
var WRPCTokenElement = $(data).find("[WRPCTokenUrl]");
if (WRPCTokenElement) {
var WRPCTokenUrl = WRPCTokenElement.attr("WRPCTokenUrl");
if (WRPCTokenUrl) {
URL = "/Activities/Attachment/download.aspx?AttachmentType=5&AttachmentId=" + slaId + "&IsNotesTabAttachment=undefined" + WRPCTokenUrl;
window.open(URL);
}
}
return false;
});

Resources