Anybody know that, how can write a javascript code in crm2011 to give edit option in one field based on security role?
You can use the below script to check the user roles on form load & enable the field. Make the field read-only by default.
Note: It has dependency to use jQuery & Json scripts to be loaded before this script library.
//Check login User has 'case title edit' role
function CheckUserRole() {
var currentUserRoles = Xrm.Page.context.getUserRoles();
for (var i = 0; i < currentUserRoles.length; i++) {
var userRoleId = currentUserRoles[i];
var userRoleName = GetRoleName(userRoleId);
if (userRoleName == "case title edit") {
//make the field editable here...
Xrm.Page.getControl("fieldname").setDisabled(false);
return true;
}
}
return false;
}
//Get Rolename based on RoleId
function GetRoleName(roleId) {
//var serverUrl = Xrm.Page.context.getServerUrl();
var serverUrl = location.protocol + "//" + location.host + "/" + Xrm.Page.context.getOrgUniqueName();
var odataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "RoleSet?$filter=RoleId eq guid'" + roleId + "'";
var roleName = null;
$.ajax(
{
type: "GET",
async: false,
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest) {
roleName = data.d.results[0].Name;
},
error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect); }
}
);
return roleName;
}
Reference
Related
Let me explain my problem, I have a LinkButton:
<asp:LinkButton ID="ForceUpdate" runat="server" OnClick="ForceUpdateBtn_Click" Text="<%$ Resources:Resource1, ForceUpdate%>" />
when I click on this LinkButton I set a command and then I check with JQuery if the button is clicked to show a message to wait until the machine is online to get the updated data and then disable the button:
window.setInterval(function () {
$.ajax({
async: true,
type: 'POST',
url: "../../WS/IOT_WebService.asmx/GetUpdateStatusStats",
data: { mccid: <%=mccIdToJavascript%>, language: '<%=currentCulture%>' }, // mccid: ID machine
cache: false,
beforeSend: function () {
},
success: function (txt) {
var string = xmlToString(txt);
string = string.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("<string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("</string>", "");
console.log('check is ', <%=checkClick%>);
var check = <%=checkClick%>;
if (check) {
$('#status-force-update').text(string);
} else {
$('#status-force-update').text('----------');
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}, 3000);
Here's the method from the webservice where I check if in the db a certain data is set (CMD_Date_hour_Ok
!= null) to update the message that the machine is online and enable back the button.
[WebMethod]
public string GetUpdateStatusStats(string mccid, string language)
{
String strResponse = String.Empty;
CultureInfo currentCulture = new CultureInfo(language);
Thread.CurrentThread.CurrentCulture = currentCulture;
Thread.CurrentThread.CurrentUICulture = currentCulture;
try
{
MCC_Machine mcc = MCC_Machine.Retrieve(Convert.ToInt32(mccid));
CMD_Command cmd = CMD_Command.RetrieveByMCCType(mcc, 14); // 14 means that a ForceUpdate were launched
if (cmd == null)
{
cmd = CMD_Command.RetrieveByMCCType(mcc, 14);
}
if (cmd.CMD_Date_hour_Ok != null)
{
// machine is online
strResponse = Resources.Resource1.ForceUpdateStatsOnline.ToString();
}
else
{
// machine is offline
strResponse = Resources.Resource1.ForceUpdateStatsOffline.ToString();
}
}
catch
{
strResponse = Resources.Resource1.ForceUpdateStatsOffline.ToString();
}
return strResponse;
}
Now I need to disable the LinkButton and maybe change the color to grey to get the idea that it is disabled when I click it and enable it when the machine is online.
How can I do that?
Thank you
You need to change disabled attribute of ForceUpdate at every interval as following:
window.setInterval(function () {
$.ajax({
async: true,
type: 'POST',
url: "../../WS/IOT_WebService.asmx/GetUpdateStatusStats",
data: { mccid: <%=mccIdToJavascript%>, language: '<%=currentCulture%>' }, // mccid: ID machine
cache: false,
beforeSend: function () {
},
success: function (txt) {
var string = xmlToString(txt);
string = string.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?><string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("<string xmlns=\"http://tempuri.org/\">", "");
string = string.replace("</string>", "");
console.log('check is ', <%=checkClick%>);
var check = <%=checkClick%>;
if (check) {
$('#status-force-update').text(string);
} else {
$('#status-force-update').text('----------');
}
if(string =="Online"){ //check is machine online then set disable false
$("#<%=ForceUpdate.ClientID %>").attr("disabled", false);
}else{ // else mean machine is offline
$("#<%=ForceUpdate.ClientID %>").attr("disabled", true);
}
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}, 3000);
In my application i am using one ashx handler for download ppt, In that i will create one screen shot(current screen as image) and pass that image name to one handler(ashx) from jquery. But am unable to track the downloading status.
If there is any way to return response from that handler to jquery. that is i want to know when that downloading will finish.
my current scenario is like this
jquery will generate one base64 string and pass that string to code behind by ajax call to convert that to image and save that image in one location
on the success call of that ajax request it will get that image name and pass that image name to handler
I am calling that handler by using "window.location.href"
my code
Ajax call for saving the image
$.ajax({
type: "POST",
url: AQ.AMT.Url + "/Home/StoreImage",
//async: false,
data: "{'base64':'" + base64 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Data) {
window.location.href = "~/Download/Export.ashx?Type=PPT&downloadToken=" + Data.Result + "&Summary=" + summaryText + "&Note=" + noteText + "&Name=" + name + "&Sample=" + sampleSize + "&SampleColor=" + sampleColor + "&pptType=" + pptType + "&flipName=" + flipName;
//here i need some response
},
error: function (e) {
}
});
Handler code for downloading the ppt
public void ProcessRequest(HttpContext context)
{
DownloadPPT(context);
}
public void DownloadPPT(HttpContext context)
{
//here i will take all parameters
try{
//downloading the ppt
saveFile(pres, "" + name + "-" + FlipName + "-" + System.DateTime.Today.ToLongDateString());//ppt name
}
catch{
}
finally
{
//after ppt download i am deleting that screenshot
if (File.Exists(path))
File.Delete(path);
}
}
I got one solution for this,Instead of using handler for downloading the files i used ajax and jquery. in this in code behind i will create the ppt and save the ppt in some folder and i will pass that name to ajax response and use anchor tag to enable the download in client side itself.
Saving the ppt
[HttpPost]
public JsonResult StoreImage(ExportToPPtRequest request)
{
ExportPptString obj = new ExportPptString();
string downloadToken = Guid.NewGuid().ToString();
string filepath = Server.MapPath("~/Download/Temp/" + downloadToken + ".png");
try
{
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(request.Base64)))
{
using (System.Drawing.Bitmap bm2 = new System.Drawing.Bitmap(ms))
{
//bm2.Save(filepath);
downloadToken = "";
downloadToken=DownloadPPT(bm2,request);
// bm2.Dispose();
}
// ms.Close();
}
obj.Result = downloadToken;
}
catch (Exception ex)
{
}
var result = Json(obj, JsonRequestBehavior.AllowGet);
return result;
}
public string DownloadPPT(Image imgToReplace, ExportToPPtRequest request)
{
string summaryText = request.Summary;
string note = request.Note;
string sampleSize = request.SampleSize;
string SampleColor = request.SampleColor;
string Type = request.Type;
string name = request.Name;
string pptName = "";
try
{
//if (downloadToken == string.Empty || downloadToken == null)
// throw new Exception("Download Token is unavailable.");
Aspose.Slides.License license = new Aspose.Slides.License();
license.SetLicense("Aspose.Slides.lic");
var _tempPPT = "";
_tempPPT = Server.MapPath("~/Download/Template/ExportPPt.pptx");
Aspose.Slides.Presentation pres = new Aspose.Slides.Presentation(_tempPPT);
pptName= saveFile(pres);//ppt name
}
catch (Exception ex)
{
}
return pptName;
}
public string saveFile(Aspose.Slides.Presentation pres)
{
string downloadToken = Guid.NewGuid().ToString();
try
{
//MemoryStream objMemoryStream = new MemoryStream();
//pres.Save(objMemoryStream, Aspose.Slides.Export.SaveFormat.Pptx);
pres.Save(Server.MapPath("~/Download/Temp/" + downloadToken + ".pptx"), Aspose.Slides.Export.SaveFormat.Pptx);
//byte[] buffer = objMemoryStream.ToArray();
//HttpContext.Current.Response.Clear();
//HttpContext.Current.Response.Buffer = true;
//HttpContext.Current.Response.AddHeader("Content-disposition", String.Format("attachment; filename=\"{0}.pptx\"", PresentationName));
//HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
//HttpContext.Current.Response.AddHeader("Content-Length", buffer.Length.ToString());
//HttpContext.Current.Response.BinaryWrite(buffer);
//HttpContext.Current.Response.Flush();
//HttpContext.Current.Response.Close();
}
catch (Exception ex)
{
}
return downloadToken;
}
in jquery
$.ajax({
type: "POST",
url: AQ.AMT.Url + "/Home/StoreImage",
//async: false,
data: JSON.stringify({ request: request }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Data) {
var _tempPPT = AQ.AMT.Url + "/Download/Temp/" + Data.Result + ".pptx";
// Trick for making downloadable link
a = document.createElement('a');
a.href = _tempPPT;// window.URL.createObjectURL(xhttp.response);
a.id = "idanchrPPT";
// Give filename you wish to download
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = dd + '/' + mm + '/' + yyyy;
if (flipName == "")
a.download = "" + name + "-" + today + ".pptx";
else
a.download = "" + name + "-" + flipName + "-" + today + ".pptx";
a.style.display = 'none';
document.body.appendChild(a);
a.click();
$("#idanchrPPT").remove();
//deleting the file
var deleteFiles = {};
deleteFiles.FilePath = Data.Result;
setTimeout(function () {
$.ajax({
type: "Post",
data: JSON.stringify({ deleteFiles: deleteFiles }),
url: AQ.AMT.Url + "/Home/DeleteExportedPPt",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
},
error: function (result) {
}
});
}, 1000);
},
error: function (e) {
}
});
I am using asp.net and jQuery 1.6
In my function I am required to pass html tags as a data parameter to my server side method written in C#. In my Database the column has Blob datatype.
I am able to submit data successfully upto 528b but If I submit large data... I'm not able to send at server side.
When I pass small data it works and a row inserted. But If I pass data around 17Kb then this doesn't go to the sever side, but prompt me an undefined error in jquery.
Following is Ajax Code:
$.ajax({
type: "POST",
url: "Post.aspx/savePost",
data: "{Title:'" + Title + "',Html:'" + Html + "'}",
contentType: "application/json",
dataType: "json",
success: function (data) {
if (data == undefined) {
alert("Error : 219");
}
else {
alert(data.d);
}
},
error: function (data) {
if (data == undefined) {
alert("Error : 465");
}
else {
alert("Error : 468 " + data.d);
}
}
});
Following is C# code
[System.Web.Services.WebMethod]
public static string savePost(string Title,string Html)
{
string retMsg = "Not Saved";
Post bp = new Post();
int count = 0;
count = bp.mySavePost(Title,Html);
if (count > 0)
{
retMsg = "Post Save Successfully.";
}
return retMsg;
}
protected int mySavePost(string Title, string Html)
{
int count=0;
try
{
string rawQuery = "INSERT INTO temp_posts (Title,HTML)"
+ " VALUES(?Title,?HTML)";
cmd = new MySqlCommand();
cmd.CommandText = rawQuery;
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add("?Title", MySqlDbType.VarChar).Value = Title;
cmd.Parameters.Add("?Html", MySqlDbType.Blob).Value = Html;
count = c.insertData(cmd);
}
catch(Exception ex){}
}
Please guide me with you valuable knowledge.
Thanks.
Many Thanks to everyone who put his best effort for this thread.
Finally with the help of one my senior I found where I was lacking in my code.
As I am passing html tags as a data parameter to my server side method written in C# from jQuery.ajax(); I need to encode the data.
As I used the escape() function in javascript to encode it worked. Data is submitted to database.
var encodedHTML = escape(Html); //here encoding Html.
$.ajax({
type: "POST",
url: "Post.aspx/savePost",
data: "{Title:'" + Title + "',Html:'" + encodedHTML + "'}",
contentType: "application/json",
dataType: "json",
success: function (data) {
if (data == undefined) {
alert("Error : 219");
}
else {
alert(data.d);
}
},
error: function (data) {
if (data == undefined) {
alert("Error : 465");
}
else {
alert("Error : 468 " + data.d);
}
}
});
Thanks everyone :)
default.aspx
<button id="getGrouper">GetGroupers</button>
<script type="text/javascript">
$(document).ready(function () {
$("#getGrouper").click(function () {
$.ajax({
type: "post",
url: "Groupers.aspx/groupers",
data: "{pid:25}",
dataType: "text",
success: function (data) { alert(data); },
error: function (err) { alert("err:" + err); }
});
return false;
});
});
</script>
groupers.aspx.cs
[WebMethod]
public static string groupers(
int project_id)
{
string employees = "";
foreach (string s in ids.Split(','))
{
u = user.getUserbyUid(Convert.ToInt32(s));
employees += "<a class=\"reply_notify_delete\" href =showuser.aspx?uid=" + u.Uid + "&pid=" + p.Pid + ">" + u.userName + "</a> ";
}
return employees;
}
want to get groupers by a project_id
i want to get string type ,then append it, but i debug the code , it doesn't work , no response , and i set breakpoin , it doesn't go into "groupers" static Method , why ?
Where you have
"{pid:25}",
dataType: "text",
change it to
'{"project_id":25}',
dataType: "json",
I have a javascript object which is converted from json to java script object. i want to display its values like after each key value pair, i want to insert new line. but i dont know exactly how to do that. below is my code, please take a look and tell me how i should insert a new line. i tried but its not inserting a new line is diplay.
$.ajaxSetup({
cache: false
//timeout: 1000000
});
//String.prototype.toJSON;
//var the_object = {};
//function concatObject(obj) {
// str = '';
// for (prop in obj) {
// str += prop + " value :" + obj[prop] + "\n";
// }
// return (str);
//}
function concatObject(obj) {
strArray = []; //new Array
for (prop in obj) {
strArray.push(prop + ":\t" + obj[prop]+"*******************************************************\"\n\"");
}
return strArray.join();
}
//var input = "stephen.gilroy1";
function testCAll() {
//var input = $('#Eid').val();
//var input = $document.getElementById('Eid').getValue();
//var input = $('input[name=Employee_NTID]').val();
var keyvalue = {
//ntid: $('#Eid').val()
ntid:"ambreen.haris",
name:"ambreen"
};
$.ajax({
type: "POST",
url: "Testing.aspx/SendMessage",
data: "{}",
//data: "{'ntid':'stephen.gilroy1'}", //working
//data: {'ntid': $('#Eid').val()},
//data: {keyvalue},
//data: { ntid: $('#Eid').val() },
//data: ({ 'ntid': $('input[name=Employee_NTID]').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
alert(result.d);
resultData = eval("(" + result.d + ")");
$("#rawResponse").html(concatObject(resultData));
//$("#response").html(resultData.sn);
},
error: function(result) {
alert("jQuery Error:" + result.statusText);
}
});
}
What's wrong with this?
function concatObject(obj) {
var strArray = []; //new Array
for (var prop in obj) {
strArray.push(prop + ":\t" + obj[prop]);
}
return strArray.join("\n");
}
EDIT:
You're appending HTML. So you should use <br />. Or surround the output with <pre> tags.
function concatObject(obj) {
var strArray = []; //new Array
for (var prop in obj) {
strArray.push(prop + ":\t" + obj[prop]);
}
return strArray.join("<br />");
}