How To Open Download Dialog box in Javascript? - javascript

I make function in Aspx page and call this function from java script , Now i want to download files through Java script. But Download Dialog Doesn't Open.....
Download.Aspx:
string pid = Request.QueryString["Did"].ToString();
DataTable dt;
dt = common.GetFilePath(Convert.ToInt64(pid));
FilePath = dt.Rows[0]["FilePath"].ToString();
FileName = dt.Rows[0]["FileName"].ToString();
FilePath = System.Web.HttpContext.Current.Server.MapPath("~//" + FilePath + "");
Response.Clear();
Response.ClearHeaders();
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", "attachment; filename=" + FileName + "");
Response.WriteFile(FilePath);
Response.End();
Jquery:
function DownloadAttach(pid){
$.ajax({ type: "POST",
url: "http://localhost:1988/DownLoad.aspx?Did=" + pid,
dataType: "xml",
processData: true,
//error: function(XMLHttpRequest, textStatus, errorThrown) { ajaxError(XMLHttpRequest, textStatus, errorThrown); },
success: function(xml) {
//ShowMsg("projSaveMsg", "Attachment Deleted.");
}
});
}

You don't want to make an AJAX call for this - just redirect the browser:
function DownloadAttach(pid){
window.location = "http://localhost:1988/DownLoad.aspx?Did=" + pid;
}

Related

How can i check User Role in javascript (without razor or controller)

I'm trying to use User.IsInRole() with javascript like on the razor page. I don't want use Controller, if this can be done, How can i do this in MVC5?
Edit: I want to display button by user role. I can do this with the razor page. There are fields in javascript where I add elements to the table, I will try to use them here.
You can do like below as shown below in for price
#{var price=20;}
<html>
<body>
#if (price>30)
{
<p>The price is too high.</p>
}
else
{
<p>The price is OK.</p>
}
</body>
</html>
try like this:
//Check login User has 'System Administrator' 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 == "System Administrator") {
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;
}
https://msdynamicscrmblog.wordpress.com/2013/03/10/get-login-user-role-names-in-javascript-in-dynamics-crm-2011/

Link not opening after streaming data of the document down

I think I am missing some code on the JavaScript side. I am downloading the documents for each request. When the user clicks on the link, I go get the document data and stream it down. I see on Fiddler that the data is coming down, but the .txt document link is not opening.
[HttpGet]
public HttpResponseMessage GetDataFiles(Int64 Id)
{
var results = context.PT_MVC_RequestFile.Where(x => x.RowId == Id).FirstOrDefault();
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
try
{
if (results != null)
{
response.Headers.AcceptRanges.Add("bytes");
response.StatusCode = HttpStatusCode.OK;
response.Content = new ByteArrayContent(results.Data);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = results.FileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentLength = results.Data.Length;
}
}
catch (EntityException ex)
{
throw new EntityException("GetFiles Failed" + ex.Message);
}
return response;
}
Firstly, I downloaded all the documents for that request, and if the user clicks on the file, I call the download stream action.
$.ajax({
url: url,
type: 'GET',
// data: JSON.stringify(model, null),
contentType: "application/json",
success: function (data) {
if (data != "") {
$("#fileLength").val(data.length);
// alert(data.length);
$.each(data, function (i, item) {
var newDiv = $(document.createElement('div')).attr("id", 'file' + i);
newDiv.html("<input id=\"cb" + i + "\" type=\"checkbox\"> <a href=\"#\" onclick=\"GetData('" + item.RowId + "','" + item.mineType + "')\" >" + item.FileName + "</a>");
newDiv.appendTo("#fileRows");
});
} else {
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I think I am missing something after success though. Somehow it downloads the data, but the link does not open. Could it be the content type is not set, or that it thinks it is JSON data? Help with some ideas please.
Here is the link:
function GetData(rowId,mineType) {
// alert(mineType);
var url = "api/MyItemsApi/GetDataFiles/" + rowId;
$.ajax({
url: url,
type: 'GET',
//data: JSON.stringify(model, null),
contentType: "application/json",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
You can't easily download a file through an Ajax request. I recommend to post the data to a blank page from a form, instead of the Ajax (you can populate that form and post it via jQuery if you need to). If you're interested, I could guide you through it, just let me know.
If you still want to download from Ajax, I suggest you refer to this post.

CRM OData OrganizationData.svc does not work by IP

I have been working on CRM autoupdate filed and i got it working by
var lookUpObjectValue = Xrm.Page.getAttribute("new_kdid").getValue();
if ((lookUpObjectValue != null))
{
var lookupid = lookUpObjectValue[0].id;
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var odataSetName = "new_kdSet?";
var odataSelect = serverUrl + ODATA_ENDPOINT + "/" + odataSetName +
"$select=new_City" +
"&$filter=new_kdId eq (guid'" + lookupid + "')" +
"&$top=1";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) {XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest){
Xrm.Page.getAttribute("address1_city").setValue(data.d.results[0].new_City);
},
error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + odataSelect); }
});
}
And it works fine until I connect to CRM by IP.
Like http://193.92.1.4/CRMTest/main.aspx# instead of
crm-server01/CRMTest/main.aspx
then i get the error OData Select Failed:/*Some url that start with crm-server01/ ... */ and when i run it it get the right data?
This is down to cross site scripting. You will find this happens to a lot of different JavaScript doing requests on CRM.
I would recommend only connecting to CRM using your server name.

Why isn't my C# function executing from ajax Javascript code?

I have an HTML canvas on my page. When I click the canvas, a simple dot paints. I pass the coordinates into my InsertIntoDB function to enter the x and y coordinates into a MS SQL Server database, but it's not happening.
I can, however, place the C# call into an HTML element and get it to work fine, so long as I use dummy xCoord and yCoord numbers and return something (not void).
My code is actually popping up the "Success!" alert, but when I run a SQL query, there was no INSERT. Here is the Code from Default.aspx:
function insertIntoDB(x, y) {
try
{
$.ajax({
type: 'POST',
url: 'Default.aspx/InsertPoints',
data: "{'xCoord': '" + x + "', 'yCoord': '" + y + "'}",
// '{"xCoord": "' + x + '", "yCoord": "' + y + '"}',
success: function (data) {
alert("Success!");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Fail: " + textStatus);
}
});
}
catch (e)
{
alert(e);
}
}
Here is the C# code in Default.aspx.cs:
[WebMethod]
public static void InsertPoints(int xCoord, int yCoord) {
string myConn = "Data Source=MYDATABASEINFO;Initial Catalog=DATABASENAME;Integrated Security=False;User ID=USERID;Password=MYPASSWORD";
SqlConnection myConnection = new SqlConnection(myConn);
try
{
myConnection.Open();
SqlCommand myCommand= new SqlCommand("INSERT INTO DRAW (xCoord, yCoord) " +
"Values (" + xCoord + ", " + yCoord + ");", myConnection);
myCommand.ExecuteNonQuery();
myConnection.Close();
}
catch(Exception e)
{
Console.WriteLine(e.ToString());
}
}
Thanks for your help.
You are trying to send json data to server then you have to declare its content type.
add jquery ajax option for content type.
function insertIntoDB(x, y) {
try
{
var data = {
"xCoord": x,
"yCoord": y
};
$.ajax({
type: 'POST',
url: 'Default.aspx/InsertPoints',
data: JSON.stringify(data),
contentType: 'application/json',
success: function (data) {
alert("Success!");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Fail: " + textStatus);
}
});
}
catch (e)
{
alert(e);
}
}
Try creating an old school Web Service(.asmx file) and not a Web Page(.aspx file).
It will even be better if you create a WebApi endpoint. It is not good practice to use web pages for web services
Try change :
data: "{'xCoord': '" + x + "', 'yCoord': '" + y + "'}",
to:
data: {'xCoord': x , 'yCoord': y },
and try add datatype:
dataType: "json",
contentType: 'application/json',

Updating record via REST does not trigger workflow, CRM 2011

I have a workflow that wait three days and check a boolean field. If the boolean is yes do something, else finish as completed. That boolean field is default no and change to yes with an update via javascript.
I don't know why the workflow always do something even when the boolean field is no.
Javascript updates are not recognized by Dynamics CRM?
Code I'm using to update:
var obj = new Object();
obj.BooleanField= true;
var jsonEntity = window.JSON.stringify(obj);
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc/CustomEntity";
var ODataPath = serverUrl + ODATA_ENDPOINT;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataPath + "(guid'" + CustomEntityId + "')",
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus + "; ErrorThrown: " + errorThrown);
}
});

Categories

Resources