Javascript for CRM 2016 phones - crm

I would like to ask about CRM Javascript code for phones, for example I have the following JS(Javascript) code for CRM web application it's not working with CRM phones
function checkCurrentUserInTeam(teamId) {
var serverUrl = "https://" + window.location.host;
var userId = Xrm.Page.context.getUserId();
if (teamId != null) {
var fwdFilter = "TeamMembershipSet?$filter=TeamId eq guid'" + teamId + "' and SystemUserId eq guid'" + userId + "'";
var url = serverUrl + "/xrmservices/2011/OrganizationData.svc/" + fwdFilter;
var fwdResult = GetOdataResults(url).results;
if (fwdResult != null && fwdResult.length > 0) {
return true;
}
else {
return false;
}
}
return false;
}
function GetOdataResults(url) {
CallOData(url);
str = CallOData(url);
var data = eval('(' + str + ')');
return data.d;
}
function CallOData(url) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", url, false);
xmlhttp.setRequestHeader("X-Requested-Width", "XMLHttpRequest");
xmlhttp.setRequestHeader("Accept", "application/json, text/javascript, */*");
xmlhttp.send(null);
return xmlhttp.responseText;
}
I'm using checkCurrentUserInTeam function with team ID as parameter, and the error I think when XMLHttpRequest call the page in phones (See the below pic) .
Click here to view the image
I need your help if you have a specially code for CRM phones or some library for it. Any help in this regard will be highly appreciated.
Thanks ..

It might be the way you are creating your serverUrl. Try using getClientUrl instead.
var serverUrl = Xrm.Page.context.getClientUrl()

Related

Modifying Netsuite Object on loading

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.

Why my following ajax is not working in Asynchronous mode

below is my code that I call on page load.
it works when I use
xmlhttp.open("GET", "../handlers/fetchshift.ashx?id=" + divs[i].id, false);
but if I use
xmlhttp.open("GET", "../handlers/fetchshift.ashx?id=" + divs[i].id, true);
xmlhttp.onreadystatechange is called for only last div. Why it is happening? I need it in Asynchronous mode.
function myfunction() {
try {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var table = document.getElementById('<%=GridView1.ClientID%>');
if (table == null) return;
var divs = table.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var msg = xmlhttp.responseText.split("|");
var table = document.getElementById('<%=GridView1.ClientID%>');
var divs = table.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
if (divs[i].id == msg[0]) {
divs[i].innerHTML = msg[1];
divs[i].parentNode.style.backgroundColor = msg[2];
}
}
}
}
xmlhttp.open("GET", "../handlers/fetchshift.ashx?id=" + divs[i].id, false);
xmlhttp.send();
}
} catch (e) {
alert(e);
}
}
You need to create a new xmlhttp object inside your for cycle. Currently you are overwriting everything each time so only the last request actually goes through.
It works in synchronous mode because xmlhttp.open() will block until everything is finished so in the next iteration everything is overwritten but that does not matter anymore.
function myfunction() {
try {
var table = document.getElementById('<%=GridView1.ClientID%>');
if (table == null) return;
var divs = table.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var msg = xmlhttp.responseText.split("|");
var table = document.getElementById('<%=GridView1.ClientID%>');
var divs = table.getElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
if (divs[i].id == msg[0]) {
divs[i].innerHTML = msg[1];
divs[i].parentNode.style.backgroundColor = msg[2];
}
}
}
}
xmlhttp.open("GET", "../handlers/fetchshift.ashx?id=" + divs[i].id, false);
xmlhttp.send();
}
} catch (e) {
alert(e);
}
}

MVC Valums Ajax Uploader - IE doesn't send the stream in request.InputStream

i'm using Valums Ajax uploader. all works great in Mozilla with this code:
View:
var button = $('#fileUpload')[0];
var uploader = new qq.FileUploader({
element: button,
allowedExtensions: ['jpg', 'jpeg', 'png', 'gif'],
sizeLimit: 2147483647, // max size
action: '/Admin/Home/Upload',
multiple: false
});
Controller:
public ActionResult Upload(string qqfile)
{
var stream = Request.InputStream;
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
var path = Server.MapPath("~/App_Data");
var file = Path.Combine(path, qqfile);
File.WriteAllBytes(file, buffer);
// TODO: Return whatever the upload control expects as response
}
which was answered in this post:
MVC3 Valums Ajax File Upload
However issue is that this doesn't work in IE. I did find this but i can't figure out how to implement it:
IE doesn't send the stream in
"request.InputStream" ... instead get
the input stream through the
HttpPostedFileBase from the
Request.Files[] collection
Also, this here that shows how this guy did it but i'm not sure how to change for my project:
Valum file upload - Works in Chrome but not IE, Image img = Image.FromStream(Request.InputStream)
//This works with IE
HttpPostedFileBase httpPostedFileBase = Request.Files[0]
as HttpPostedFileBase;
can't figure this one out. please help!
thanks
I figured it out. This works in IE and mozilla.
[HttpPost]
public ActionResult FileUpload(string qqfile)
{
var path = #"C:\\Temp\\100\\";
var file = string.Empty;
try
{
var stream = Request.InputStream;
if (String.IsNullOrEmpty(Request["qqfile"]))
{
// IE
HttpPostedFileBase postedFile = Request.Files[0];
stream = postedFile.InputStream;
file = Path.Combine(path, System.IO.Path.GetFileName(Request.Files[0].FileName));
}
else
{
//Webkit, Mozilla
file = Path.Combine(path, qqfile);
}
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
System.IO.File.WriteAllBytes(file, buffer);
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message }, "application/json");
}
return Json(new { success = true }, "text/html");
}
Shane's solution works but it seems like the Request["qqfile"] is being set anyway in IE. Not sure if this is because I'm using an updated version of the fileuploader but I've modified the "if" statement to make it work for IE (checking if there are any uploaded files in the request).
if (Request.Files.Count > 0) {
//ie
} else {
//webkit and mozilla
}
Here is the full snippet
[HttpPost]
public ActionResult FileUpload(string qqfile)
{
var path = #"C:\\Temp\\100\\";
var file = string.Empty;
try
{
var stream = Request.InputStream;
if (Request.Files.Count > 0)
{
// IE
HttpPostedFileBase postedFile = Request.Files[0];
stream = postedFile.InputStream;
file = Path.Combine(path, System.IO.Path.GetFileName(Request.Files[0].FileName));
}
else
{
//Webkit, Mozilla
file = Path.Combine(path, qqfile);
}
var buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
System.IO.File.WriteAllBytes(file, buffer);
}
catch (Exception ex)
{
return Json(new { success = false, message = ex.Message }, "application/json");
}
return Json(new { success = true }, "text/html");
}

XMLHttpRequest Request URI too large (414)

Well I hoped everything would work fine finally. But of course it doesn't. The new problem is the following message:
Request-URI Too Large The requested URL's length exceeds the
capacity limit for this server.
My fear is that I have to find another method of transmitting the data or is a solution possible?
Code of XHR function:
function makeXHR(recordData)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var rowData = "?q=" + recordData;
xmlhttp.open("POST", "insertRowData.php"+rowData, true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-Length",rowData.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert("Records were saved successfully!");
}
}
xmlhttp.send(null);
}
You should POST rowData in the request body via the send method. So, instead of posting to "insertRowData.php" + rowData, POST to "insertRowData.php" and pass the data in rowData to send.
I suspect that your rowData is a query string with the question mark. If that is the case, then the message body is simply rowData without the prepended question mark.
EDIT: Something like this should work:
var body = "q=" + encodeURIComponent(recordData);
xmlhttp.open("POST", "insertRowData.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = // ...
xmlhttp.send(body);

Auto save of form

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.

Resources