Link not opening after streaming data of the document down - javascript

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.

Related

Access the session variables from controller inside ajax call

I have certain fields getting filled in my controller.
public string AjaxLogin()
{
//some code to check admin or not
Session["UserName"] = "Smith";
if(type="Admin")
{
Session["UserRole"] = 1;
}
Session["EmployeeID"] = 101;
}
I have an ajax call to this controller like below and if it is success, I need to access these session variables inside success to check the user role.
$.ajax(
{
url: GLOBAL.GetAppPath() + 'Home/AjaxLogin',
data: data,
type: 'POST',
error: function (xhr, status, error) {
console.log(error);
},
success: function (result, status, xhr) {
if (result == 'OK')
{
var UserVal = '#Session["UserRole"]';
alert(UserVal);
if(UserVal ==1)
{
var baseUrl ="#Url.Action("Admin","AdminPage")";
window.location.href = baseUrl;
}
else
{
var baseUrl ="#Url.Action("Admin","RegularPage")";
window.location.href = baseUrl;
}
}
else {
$('#msgError').html('Error: ' + result);
$('#msgError').css('display', 'block');
}
},
});
But I cannot access this variable in this call. I want to check the user role variable and give url actions accordingly.
If you want to redirect to a controller in your project you can use the Url helper for you
Sample:
return JavaScript( "window.location = '" + Url.Action("Edit","Dispatch") + "'" );
P.S: I couldn't comment since it asks for 50 reputation that's why I'm commenting it over here.

AJAX POST to WEB Method not working for me

I coded up just like everybody else on the net but my WebMethod isn't getting hit from the post action. I believe my code is fine but I'll post my code just in case.
I put a breakpoint in the WebMethod, this is how I know it isn't being called.
Any help would be appreciated.
AXAJ
var div = document.getElementById(this.id);
var divid = div.getElementsByClassName("portlet-id");
varSQL="UPDATE [ToDoTrack] SET [Status] = '" + this.id + "' WHERE [ID] = '" + divid[0].innerHTML + "'";
var item = {};
item.status = this.id;
item.id = divid[0].innerHTML;
var Data = '{varSQL: ' + varSQL + ' }'
$.ajax({
type: "POST",
url: "ToDoTrack.aspx/UpdateDB",
data: Data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
window.location.reload();
},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert("Status: " + textStatus);
alert("Error: " + errorThrown);
}
});
Code Behind
[WebMethod]
[ScriptMethod]
public static void UpdateDB(string varSQL)
{
string connStr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand(varSQL))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
There is a problem the data object, it's a string not an object
Its not recommended to create the SQL on client side, it's a security flaw unless it's an application
//Problem is a string not object
var Data = '{varSQL: ' + varSQL + ' }'
//Solution below
var Data = {'varSQL': varSQL };
// Or this
var Data = 'varSQL='+varSQL;
The code seemed to work fine but if you have this issue in the future, these are the things I got from the internet that you seem to need for ajax post to work with WebMethods:
Ensure your URL in AJAX is correct
Ensure your json is well formed
Set <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">, my script manager was in my site.master
Set settings.AutoRedirectMode = RedirectMode.Off; in the App_Start>RouteConfig.cs file

An ajax call to a .net web api method with a valid XML response has the responseXML as undefined

I have a .net web api method that when open in the browser it returns a valid XML (http://localhost:49546/api/Products)
<ArrayOfProductModel><ProductModel><Color>Black</Color><DiscontinuedDate i:nil="true"/><ListPrice>1431.5000</ListPrice><ModifiedDate>2008-03-11T10:01:36.827</ModifiedDate><Name>HL Road Frame - Black, 58</Name><ProductCategoryId>18</ProductCategoryId><ProductId>680</ProductId><ProductModelId>6</ProductModelId><ProductNumber>FR-R92B-58</ProductNumber><SellEndDate i:nil="true"/><SellStartDate>2002-06-01T00:00:00</SellStartDate><Size>58</Size><StandardCost>1059.3100</StandardCost><Weight>1016.04</Weight></ProductModel> </ArrayOfProductModel>
When I try to call that method using AJAX the data is being shown as an [object XMLDocument] but the data.responseXML is undefined so I can not process the XML response to show it as a table.
<script type="text/javascript">
$(document).ready(function () {
getProducts();
});
function getProducts()
{
$.ajax({
url: 'http://localhost:49546/api/Products',
method: 'GET',
dataType: 'xml',
//contentType: 'application/xml; charset=utf-8',
success: function (data) {
alert("GetProducts successfully");
showProducts(data);
},
fail: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
})
}
function showProducts(data)
{
alert(data);
alert(data.responseXML);
alert(data.responseText);
var i;
var xmlDoc = data.responseXML;
var table = "<tr><th>Nombre</th><th>ListPrice</th></tr>";
var x = xmlDoc.getElementsByTagName("ProductModel");
for (i = 0; i < x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("ListPrice")[0].childNodes[0].nodeValue +
"</td></tr>";
}
//alert(data);
document.getElementById("prodTable").innerHTML = table;
}
</script>
Please let me know what is missing or wrong
Web API passes back JSON as the default data type. That's what you're getting in {"location":null}
If you want to pass back XML, check out this article: WebAPI to Return XML

ASP.NET execute WebMethod with Jquery/AJAX

I have one WebMethod that will execute some DB search and return it's data in some HTML template. I need to execute this method using jquery to populate an area of the website but the problem is that my website URL/URI is dynamic.
My URL is http://site/school-name/home. The school-name will always change to indicate wich school i'm accessing.
I have accomplished so far:
$.ajax({
type: "POST",
url: "/Default.aspx/BuscaEquipe",
data: { 'pIndex': pIndex, 'pLimite': 4, 'pUnidadeCE': codigoEmitente },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert(response.d);
},
failure: function(response) {
alert(response.d);
}
});
and the WebMethod:
public static string BuscaEquipe(int pIndex, int pLimite, int pUnidadeCE)
{
var objEquipe = new Equipe { EquipeUnidadeCE = pUnidadeCE, EquipeAtivo = 1 };
var CaminhoImagem = Configuracoes.CaminhoVirtual + "Controles/Redimensiona.ashx?img=" + Configuracoes.CaminhoVirtual + "images/equipe/" + pUnidadeCE + "/";
if (!objEquipe.Listar(objEquipe)) return "";
var depoimentos = objEquipe.lstEquipe.Skip(pIndex).Take(pLimite);
var objJson = new JavaScriptSerializer().Serialize(depoimentos.Aggregate("", (current, equipe) =>
current + ("<div class='col-lg-3 col-md-3 col-sm-3'><img src='" + CaminhoImagem + equipe.EquipeImagem + "&w=400&h=400' alt='" + equipe.EquipeNome + "' class='img-circle img_perfil'><div class='nome_perfil text-center'>" + equipe.EquipeNome + "</div></div>")));
return objJson;
}
Using like this i get a 401 Not Authorized and if i try to use my full URL http://site/school-name/Default.aspx/BuscaEquipe i get a 404.
P.S. I have already used this same method in another project and it worked fine but i can't figure out what's wrong in this one, i think it might be related to the URl but i'm not sure.
the problem is with your URL
Use the ResolveClientUrl() method
<%= ResolveUrl("~/Default.aspx/BuscaEquipe") %>
And you must Have [WebMethod] attribute before your static server function
[WebMethod]
public static string BuscaEquipe(int pIndex, int pLimite, int pUnidadeCE)
{
//Code
}
Your data:
var requestData= JSON.stringify({
pIndex: pIndex,
pLimite: 4,
pUnidadeCE: codigoEmitente
})
and then
data:requestData

How to update or delete Sender and Receiver of an existing phonecall / email record using MS Dynamics CRM REST Endpoint

I am working on the application where I need to create and later update phonecall / email records in MS Dynamics CRM 2011 using REST API. Using Soap API is not an option.
I have figured out how to create the phonecall / email record (which is well documented here
or here).
Updating the existing phonecall / email record itself is not a problem either.
My question is: HOW do I update the Receiver and Sender fields (To and From) of an existing phonecall / email record?
I have tried different approaches described below with no luck so far.
I get Error processing request stream. Deep updates are not supported in PUT operations. error if I try to update phonecall_activity_parties relationship - see code below
var callLogEntity = {
"Subject": "My call", "Description": "Call comments go here" };
var activityParties = [];
activityParties.push({
"PartyId": {"Id":"4A9FD17D-5890-4BF0-94AA-D68285C46039", "LogicalName":"contact"},
"ParticipationTypeMask": { "Value": 1 }
}); // sender is a contact
activityParties.push({
"PartyId": { "Id": Xrm.Page.context.getUserId(), "LogicalName": "systemuser" },
"ParticipationTypeMask": { "Value": 2 }
}); // receiver is a current user
callLogEntity.phonecall_activity_parties = activityParties;
var restQueryUrl = "http://<crm_url>/XRMServices/2011/OrganizationData.svc/" +
"PhoneCallSet(guid'" + callLogId + "')";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
data: JSON.stringify(callLogEntity),
url: restQueryUrl,
beforeSend: function (XMLHttpRequest)
{
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
},
success: function (data, textStatus, XmlHttpRequest)
{
console.log("Success");
},
error: function (XmlHttpRequest, textStatus, errorObject)
{
console.warn("Request FAILED: " + XmlHttpRequest.responseText);
}
});
I get An activityparty cannot be disassociated from an activity error if I try to disassociate an activity using the disassociateRecords method from this SDK Example - see code below
var restQueryUrl = "http://<crm_url>/XRMServices/2011/OrganizationData.svc/" +
"PhoneCallSet(guid'" + callLogId + "')/$links/" +
"phonecall_activity_parties(guid'" + activityPartyId + "')";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: restQueryUrl,
beforeSend: function (XMLHttpRequest)
{
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
},
success: function (data, textStatus, XmlHttpRequest)
{
console.log("Success");
},
error: function (XmlHttpRequest, textStatus, errorObject)
{
console.warn("Request FAILED: " + XmlHttpRequest.responseText);
}
});
I get Forbidden error when I try to delete one of the ActivityParty found in the phonecall_activity_parties directly from ActivityPartySet.
var restQueryUrl = "http://<crm_url>/XRMServices/2011/OrganizationData.svc/" +
"ActivityPartySet(guid'" + activityPartyId + "')";
// then do an AJAX POST request with "X-HTTP-Method": "DELETE" header
Updating each ActivityParty from that list individually has no effect on the phonecall record (i.e. the MERGE request seems to be successful, but the ActivityParty still points to the old record)
var activityData = {
"PartyId":{"Id":"cc1cdb40-a844-e211-ab1a-000c297d9c06","LogicalName":"contact"},
"ParticipationTypeMask":{"Value":1}
};
var restQueryUrl = "http://<crm_url>/XRMServices/2011/OrganizationData.svc/" +
"ActivityPartySet(guid'" + activityPartyId + "')";
// then do an AJAX post request with "X-HTTP-Method": "MERGE" header
// and activityData as the message body
If anyone can shed some light on how to change (or delete, as in "clear the field") the Sender and Receiver of an EXISTING phonecall / email record I would greatly appreciate it.
Can you try this code. I hope this will be helpful.
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = "3D417D54-412C-440D-A390-33ED7398254D";
lookupValue[0].name = "UserName";
lookupValue[0].entityType = "systemuser";
lookupValue[1] = new Object();
lookupValue[1].id = "8BD96ECC-573D-E211-A12B-1CC1DE79B4CA";
lookupValue[1].name = "QueueName";
lookupValue[1].entityType = "queue";
createRecord(lookupValue, "EmailSet", _emailCreateSuccess, _error);
//Xrm.Page.getAttribute("to").setValue(lookupValue);

Categories

Resources