I am very new to Netsuite. I am trying to do encryption in Netsuite. It works when I add UserEvent Scripts beforeSubmit. But I wanted to decrypt the encrypted text in beforeLoad function. I am able to read the encrypted text and decrypt it successfully as well. But setting it back in the object fails and I see decrypted text in Netsuite UI. Any directions or help is appreciated.
thanks
// this function works
function beforeSubmit(type) {
var email = nlapiGetFieldValue('email');
var newEmail = 'LifeSpan.' + email;
nlapiSetFieldValue('email', newEmail );
nlapiLogExecution('DEBUG', 'Modified before Submit ' + email + ' to ' + newEmail);
}
// this printed "Modified before Submit customercare#abc.com to LifeSpan.customercare#abc.com"
// this function doesn't work; even though the correct value is printed correctly in the log
function beforeLoad(type, form, request) {
var email = nlapiGetFieldValue('email');
if(email.indexOf('SaaSSpan.') != -1) {
var newEmail = email.substring(9);
nlapiSetFieldValue('email', newEmail );
nlapiLogExecution('DEBUG', 'Modified before load ' + email + ' to ' + newEmail);
}
}
// this printed "Modified before load LifeSpan.customercare#abc.com to customercare#abc.com"...but I am still seeing LifeSpan.customercare#abc.com in the user interface
I will suggest you to try this code in a client script(PageInit and SaveRecord Events).
Works fine for me.
My Code :
function PageInit(type) {
try {
if (type == 'edit') {
var email = nlapiGetFieldValue('email');
if (email != null && email.indexOf('LifeSpan.') != -1) {
var newEmail = email.substring(9);
nlapiSetFieldValue('email', newEmail);
nlapiLogExecution('DEBUG', 'Modified before load ' + email + ' to ' + newEmail);
}
}
}
catch (err) {
nlapiLogExecution('ERROR', 'PageInit', err);
}}
function SaveRecord() {
try {
var email = nlapiGetFieldValue('email');
var newEmail = 'LifeSpan.' + email;
nlapiSetFieldValue('email', newEmail);
nlapiLogExecution('DEBUG', 'Modified before Submit ' + email + ' to ' + newEmail);
}
catch (err) {
nlapiLogExecution('ERROR', 'SaveRecord', err);
}
return true;}
nlapiSetFieldValue can be used in user event beforeLoad scripts to initialize field on new records or non-stored fields.
Related
I am using wso2/gmail package to send an email notification. According to the documentation (https://central.ballerina.io/wso2/gmail) we can send an attachment with the mail through the package. However, when I try to define attachment paths as a parameter, I get an error as follows.
incompatible types: expected 'wso2/gmail:0.9.7:AttachmentPath', found 'string'
What is AttachmentPath type? Can we parse string array of attachment paths to AttachmentPath? Here is my function to send mail.
import wso2/gmail;
import ballerina/io;
import ballerina/log;
import ballerina/config;
import ballerina/http;
function sendErrorLogMail(string senderEmail, string recipientEmail, string subject, string messageBody) returns boolean {
endpoint gmail:Client gmailErrorClient {
clientConfig:{
auth:{
accessToken:config:getAsString("gmailApiConfiguration.accessToken"),
refreshToken:config:getAsString("gmailApiConfiguration.refreshToken"),
clientId:config:getAsString("gmailApiConfiguration.clientId"),
clientSecret:config:getAsString("gmailApiConfiguration.clientSecret")
}
}
};
gmail:MessageRequest messageRequest;
messageRequest.recipient = recipientEmail;
messageRequest.sender = senderEmail;
messageRequest.subject = subject;
messageRequest.messageBody = messageBody;
messageRequest.contentType = gmail:TEXT_HTML;
//What is the attachment path?
AttachmentPath attachmentPath = "./org/wso2/logs/loginfo.txt";
messageRequest.attachmentPaths = attachmentPath;
var sendMessageResponse = gmailErrorClient->sendMessage(senderEmail, untaint messageRequest);
string messageId;
string threadId;
match sendMessageResponse {
(string, string) sendStatus => {
(messageId, threadId) = sendStatus;
log:printInfo("Sent email to " + recipientEmail + " with message Id: " + messageId + " and thread Id:"
+ threadId);
return true;
}
gmail:GmailError e => {
log:printInfo(e.message);
return false;
}
}
}
Yes. As #pasan has mentioned, AttachmentPath is a record. Following is the updated code if someone wants to refer.
function sendErrorLogMail(string senderEmail, string recipientEmail, string subject, string messageBody) returns boolean {
endpoint gmail:Client gmailErrorClient {
clientConfig:{
auth:{
accessToken:config:getAsString("gmailApiConfiguration.accessToken"),
refreshToken:config:getAsString("gmailApiConfiguration.refreshToken"),
clientId:config:getAsString("gmailApiConfiguration.clientId"),
clientSecret:config:getAsString("gmailApiConfiguration.clientSecret")
}
}
};
gmail:AttachmentPath attachmentPath= {
attachmentPath:"./org/wso2/logs/loginfo.txt",
mimeType:"Text/plain"
};
gmail:MessageRequest messageRequest;
messageRequest.recipient = recipientEmail;
messageRequest.sender = senderEmail;
messageRequest.subject = subject;
messageRequest.messageBody = messageBody;
messageRequest.contentType = gmail:TEXT_HTML;
messageRequest.attachmentPaths = [attachmentPath];
var sendMessageResponse = gmailErrorClient->sendMessage(senderEmail, untaint messageRequest);
string messageId;
string threadId;
match sendMessageResponse {
(string, string) sendStatus => {
(messageId, threadId) = sendStatus;
log:printInfo("Sent email to " + recipientEmail + " with message Id: " + messageId + " and thread Id:"
+ threadId);
return true;
}
gmail:GmailError e => {
log:printInfo(e.message);
return false;
}
}
}
AttachmentPath is defined in [wso2/gmail][1] as a record. The attachmentPaths field needs an array of such AttachmentPath objects. So following should work.
gmail:AttachmentPath attachmentPath= {
attachmentPath:"./org/wso2/logs/loginfo.txt",
mimeType:"text/plain"
};
messageRequest.attachmentPaths = [attachmentPaths];
The following is a method for sending an Email from a Razor page in ASP.NET Core. I need to use MailKit since System.Net.Mail is not available in ASP.NET Core.
Despite much research, I haven't been able to figure out a way to include the image to the Email. Note that it doesn't have to be an attachment - embedding the image will work.
public ActionResult Contribute([Bind("SubmitterScope, SubmitterLocation, SubmitterItem, SubmitterCategory, SubmitterEmail, SubmitterAcceptsTerms, SubmitterPicture")]
EmailFormModel model)
{
if (ModelState.IsValid)
{
try
{
var emailName= _appSettings.EmailName;
var emailAddress = _appSettings.EmailAddress;
var emailPassword = _appSettings.EmailPassword;
var message = new MimeMessage();
message.From.Add(new MailboxAddress(emailName, emailAddress));
message.To.Add(new MailboxAddress(emailName, emailAddress));
message.Subject = "Record Submission From: " + model.SubmitterEmail.ToString();
message.Body = new TextPart("plain")
{
Text = "Scope: " + model.SubmitterScope.ToString() + "\n" +
"Zip Code: " + model.SubmitterLocation.ToString() + "\n" +
"Item Description: " + model.SubmitterItem.ToString() + "\n" +
"Category: " + model.SubmitterCategory + "\n" +
"Submitted By: " + model.SubmitterEmail + "\n" +
// This is the file that should be attached.
//"Picture: " + model.SubmitterPicture + "\n" +
"Terms Accepted: " + model.SubmitterAcceptsTerms + "\n"
};
using (var client = new SmtpClient())
{
client.Connect("smtp.gmail.com", 587);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate(emailAddress, emailPassword);
client.Send(message);
client.Disconnect(true);
return RedirectToAction("Success");
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message + ": " + ex.StackTrace);
return RedirectToAction("Failure");
}
}
else
{
return View();
}
}
This is from the FAQ on Mailkit github repo, and seems to cover the full process.
https://github.com/jstedfast/MailKit/blob/master/FAQ.md#CreateAttachments
var message = new MimeMessage ();
message.From.Add (new MailboxAddress ("Joey", "joey#friends.com"));
message.To.Add (new MailboxAddress ("Alice", "alice#wonderland.com"));
message.Subject = "How you doin?";
// create our message text, just like before (except don't set it as the message.Body)
var body = new TextPart ("plain") {
Text = #"Hey Alice,
What are you up to this weekend? Monica is throwing one of her parties on
Saturday and I was hoping you could make it.
Will you be my +1?
-- Joey
"
};
// create an image attachment for the file located at path
var attachment = new MimePart ("image", "gif") {
ContentObject = new ContentObject (File.OpenRead (path), ContentEncoding.Default),
ContentDisposition = new ContentDisposition (ContentDisposition.Attachment),
ContentTransferEncoding = ContentEncoding.Base64,
FileName = Path.GetFileName (path)
};
// now create the multipart/mixed container to hold the message text and the
// image attachment
var multipart = new Multipart ("mixed");
multipart.Add (body);
multipart.Add (attachment);
// now set the multipart/mixed as the message body
message.Body = multipart;
Hello friends I have developed many to many chat application using signal R it is working perfectly fine.But i am getting one problem in developing one thing..that is typing message to the reciever for example:- there are two user online user x and user y.now when user x is typing message..on user y window it should come.."user x is typing message.." but when i send this message to group it is getting displayed on both screen..I want to display it on reciever screen only
This is the code
public void Send(string message, string groupName, string Istypingmessage)
{
if (Clients != null)
{
string[] words = message.Split(':');
string trim = words[0].Trim();
string imagetag = "<img width=\"32px\" height=\"32px\" src=\"userimages/" + trim + ".jpg" + "\"" + "></img> ";
Clients.Group(groupName).addMessage(message, groupName, words[0], imagetag, Istypingmessage);
}
}
where here typing message=0 means normal message and 1 means "user x is typing that message"
This is the key press event
//keypress event of textbbox here..
$(".ChatText").live('keyup', function () {
if($(".ChatText").val().length > 0)
{
var messsage_typing=$("#hdnUserName").val() + " is typing...";
var strGroupName = $(this).parent().attr('groupname');
if (typeof strGroupName !== 'undefined' && strGroupName !== false)
chat.server.send($("#hdnUserName").val() + ' : ' + messsage_typing, $(this).parent().attr('groupname'),"1");
}
});
//end of keypress
and this is add message code
chat.client.addMessage = function (message, groupName,recievername,imagetag,Istypingmessage) {
if ($('div[groupname=' + groupName + ']').length == 0) {
var chatWindow = $("#divChatWindow").clone(true);
$(chatWindow).css('display', 'block');
$(chatWindow).attr('groupname', groupName);
$("#chatContainer").append(chatWindow);
//buggy code do not delete..
//remove all previous li
$('div[groupname=' + groupName + ']').find('ul li').remove();
//replace header tag with new name
$('div[groupname=' + groupName + ']').find('a').html(recievername);
$("#chatContainer").draggable();
$("#chatContainer").css('cursor','move');
}
if(Istypingmessage=="0")
{
var stringParts = message.split(":");
var username = stringParts[0];
var message = stringParts[1];
//this code is for continous message sent
var lastliusername=$('div[groupname=' + groupName + '] ul li').eq(-2).find('div.designnone').html();
if(lastliusername!=null && $.trim(username)==$.trim(lastliusername))
{
$('div[groupname=' + groupName + '] ul li').eq(-2).find('div.designmessage').append("<span class='spansameuser'>" + message + "</span>");
//end of this code is for continous message sent
}
else
{
$('div[groupname=' + groupName + ']').find('ul').append("<li><div class='design'>" + imagetag + "</div><div class='designnone'> " + username + "</div><div class='designmessage'> " + message + " </div></li><li class='cleardivbetweenmsg'></li>");
}
}
else
{
$('div[groupname=' + groupName + ']').find('ul').append("<li><span>Hellos</span></li>");
}
$("#messages").scrollTop($("#messages")[0].scrollHeight);
};
How can i display typing message to my reciever instead of on both screens..please help me out..In short i want to send my message only to reciever of group not to sender of the group
Thanks
If you want to send a message to all clients in a group except for the sender, you can use Clients.OthersInGroup:
Clients.OthersInGroup(groupName).addMessage(/*...*/);
This is the equivalent to passing the sender's connection ID as a second parameter to Clients.Group making it an excluded connection ID.
Clients.Group(groupName, Context.ConnectionId).addMessage(/*...*/);
The method signature for Clients.Group is: public dynamic Group(string groupName, params string[] excludeConnectionIds).
I develop registration form and it have username field, and it's required to be like twitter username check ( real time check ) .. i already develop as in every textbox key up I use jquery to pass textbox.Text to page that return if is username exist or not
the following JavaScript method 'Check()' is invoked onkeyup for textbox :
function Check() {
var userName = $('#<%= TextBox1.ClientID %>').val();
if (userName.length < 3) {
$('#checkUserNameDIV').html("user name must be between 3 and 20");
return;
}
$('#checkUserNameDIV').html('<img src="loader.gif" />');
//setTimeout("CheckExistance('" + userName + "')", 5000);
CheckExistance(userName);
}
function CheckExistance(userName) {
$.get(
"JQueryPage.aspx", { name: userName },
function(result) {
var msg = "";
if (result == "1")
msg = "Not Exist " + '<img src="unOK.gif" />';
else if (result == "0")
msg = "Exist" ;
else if (result == "error")
msg = "Error , try again";
$('#checkUserNameDIV').html(msg);
}
);
}
but i don't know if is it the best way to do that ? specially i do check every keyup ..
is there any design pattern for this problem > or nay good practice for doing that ?
Maybe you could use a CustomValidator and a ServerSideValidationExtender with Ajax:
I have form in ASP.NET 3.5. Where lot of data elements and where i have Save and Submit buttions. I need to auto save my form every 2 min. What is the best way to implement this kind of functionility in ASP.NET.
I struggled for awhile with the same problem. The trouble was that I didn't want to save into the usual database tables because that would've required validation (validating integers, currencies, dates, etc). And I didn't want to nag the user about that when they may be trying to leave.
What I finally came up with was a table called AjaxSavedData and making Ajax calls to populate it. AjaxSavedData is a permanent table in the database, but the data it contains tends to be temporary. In other words, it'll store the user's data temporarily until they actually complete the page and move onto the next one.
The table is composed of just a few columns:
AjaxSavedDataID - int:
Primary key.
UserID - int:
Identify the user (easy enough).
PageName - varchar(100):
Necessary if you're working with multiple pages.
ControlID - varchar(100):
I call this a ControlID, but it's really just the ClientID property that .NET exposes for all of the WebControls. So if for example txtEmail was inside a user control named Contact then the ClientID would be Contact_txtEmail.
Value - varchar(MAX):
The value the user entered for a given field or control.
DateChanged - datetime:
The date the value was added or modified.
Along with some custom controls, this system makes it easy for all of this to "just work." On our site, the ClientID of each textbox, dropdownlist, radiobuttonlist, etc is guaranteed to be unique and consistent for a given page. So I was able to write all of this so that the retrieval of the saved data works automatically. In other words, I don't have to wire-up this functionality every time I add some fields to a form.
This auto-saving functionality will be making its way into a very dynamic online business insurance application at techinsurance.com to make it a little more user friendly.
In case you're interested, here's the Javascript that allows auto-saving:
function getNewHTTPObject() {
var xmlhttp;
/** Special IE only code */
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end
#*/
/** Every other browser on the planet */
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
function AjaxSend(url, myfunction) {
var xmlHttp = getNewHTTPObject();
url = url + "&_did=" + Date();
xmlHttp.open("GET", url, true);
var requestTimer = setTimeout(function() { xmlHttp.abort(); }, 2000);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState != 4)
return;
var result = xmlHttp.responseText;
myfunction(result);
};
xmlHttp.send(null);
}
// Autosave functions
var SaveQueue = []; // contains id's to the DOM object where the value can be found
var SaveQueueID = []; // contains id's for binding references (not always the same)
function ArrayContains(arr, value) {
for (i = 0; i < arr.length; i++) {
if (arr[i] == value)
return true;
}
return false;
}
function GetShortTime() {
var a_p = "";
var d = new Date();
var curr_hour = d.getHours();
if (curr_hour < 12)
a_p = "AM";
else
a_p = "PM";
if (curr_hour == 0)
curr_hour = 12;
else if (curr_hour > 12)
curr_hour = curr_hour - 12;
var curr_min = d.getMinutes();
curr_min = curr_min + "";
if (curr_min.length == 1)
curr_min = "0" + curr_min;
return curr_hour + ":" + curr_min + " " + a_p;
}
function Saved(result) {
if (result == "OK") {
document.getElementById("divAutoSaved").innerHTML = "Application auto-saved at " + GetShortTime();
document.getElementById("divAutoSaved").style.display = "";
}
else {
document.getElementById("divAutoSaved").innerHTML = result;
document.getElementById("divAutoSaved").style.display = "";
}
}
function getQueryString(name, defaultValue) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split("=");
if (pair[0] == name) {
return pair[1];
}
}
return defaultValue;
}
function urlencode(str) {
return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/#/g, '%40');
}
function AutoSave() {
if (SaveQueue.length > 0) {
var url = "/AjaxAutoSave.aspx?step=" + getQueryString("step", "ContactInformation");
for (i = 0; i < SaveQueue.length; i++) {
switch (document.getElementById(SaveQueue[i]).type) {
case "radio":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
break;
case "checkbox":
if (document.getElementById(SaveQueue[i]).checked)
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
default:
url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
}
}
SaveQueue = [];
SaveQueueID = [];
AjaxSend(url, Saved);
}
}
function AddToQueue(elem, id) {
if (id == null || id.length == 0)
id = elem.id;
if (!ArrayContains(SaveQueueID, id)) {
SaveQueue[SaveQueue.length] = elem.id;
SaveQueueID[SaveQueueID.length] = id;
}
}
Add this to your page to make this work:
window.setInterval("AutoSave()", 5000);
And to apply this to a Textbox, DropdownList, Listbox, or Checkbox you just need to add this attribute:
onchange="AddToQueue(this)"
...or this for a RadioButtonList or CheckBoxList:
onchange="AddToQueue(this, '" + this.ClientID + "')"
I'm sure this Javascript could be simplified quite a bit if you used JQuery so you might want to consider that. But in any case, AJAX is the thing to use. It's what Google uses to auto-save your email message in gmail, and the same thing is in blogger when you're writing a new post. So I took that concept and applied it to a huge ASP.NET application with hundreds of form elements and it all works beautifully.
Use the Timer class and the Tick method.