Asp.net webForms problem : Generate an empty pdf on production Server - asp.net

In my webForm project as follow :
I have a button which user click on it
call a web method (via jquery request) to extract some binary data from sql server as pdf
Then give a user to download/view the pdf via browser.
This works for my development machine. However, this fails on production server and give to user an empty pdf!
Where is my problem & how to solve it?
Here is jquery request to my web method :
function OpenAttachment(jsonData){
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MedicalHistory.aspx/OpenAttachment",
data: JSON.stringify({ objData: jsonData }),
dataType: "json",
success: function (response) {
gdv.PerformCallback('downloadfile|' + response.d);
},
error: function (request, status, error) {
alert('error : ' + error);
}
});
}
Here is my web method :
[WebMethod]
public static string OpenAttachment(object objData)
{
string strResult = string.Empty;
if (objData == null)
return strResult;
DataTable dtResult = Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(objData.ToString());
string strDocContent = dtResult.Rows[0]["DocContent"].ToString();
string strFileName = dtResult.Rows[0]["FileName"].ToString();
byte[] pdfByteArray = Encoding.Default.GetBytes(strDocContent);
HttpContext.Current.Session["_binDownloadData"] = pdfByteArray;
strResult = strFileName;
return strResult;
}
And here is download code in my download page :
object objDownloadData = Session["_binDownloadData"];
if (objDownloadData != null)
{
byte[] pdfByteArray = (byte[])objDownloadData;
string strContentType = string.Empty;
if (strFileType == "pdf")
{
strContentType = "application/pdf";
}
#region Downloading file
HttpContext.Current.Response.Clear();
MemoryStream ms = new MemoryStream(pdfByteArray);
HttpContext.Current.Response.ContentType = strContentType;
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", strFileName));
HttpContext.Current.Response.Buffer = true;
ms.WriteTo(HttpContext.Current.Response.OutputStream);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.SuppressContent = true;
HttpContext.Current.ApplicationInstance.CompleteRequest();
#endregion
Session["_binDownloadData"] = null;
}
Thanks in advance.

Try with changing contentType and dataType.
$.ajax - dataType
function OpenAttachment(jsonData){
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "MedicalHistory.aspx/OpenAttachment",
data: JSON.stringify({ objData: jsonData }),
dataType: "application/pdf",
success: function (response) {
gdv.PerformCallback('downloadfile|' + response.d);
},
error: function (request, status, error) {
alert('error : ' + error);
}
});
}

Related

How to pass an array to asmx web service via JSON?

I want to pass array value to my web service file. But it throws the following error
setDeleteFiles
Test
The test form is only available for methods with primitive types as parameters.
Here is my jquery code
$('#btnDeleteFiles').click(function () {
var filesPaths = [];
i = 0;
$("input:checkbox[name=filed-checkedbox]:checked").each(function () {
filesPaths[i] = $(this).val();
i++;
});
//alert("filesPaths = " + filesPaths)
var location = $('#ddlLocation option:selected').text();
alert("Location = "+location)
$.ajax({
method: 'post',
url: "GetAllFolderDetails.asmx/setDeleteFiles",
data: {
location: location,
fileNames: filesPaths
},
dataType: "json",
success: function (data) {
window.location.reload(true);
//alert("Success");
},
error: function (result) {
alert("Error");
}
});
});
GetAllFolderDetails.asmx code
[WebMethod]
public void setDeleteFiles(string location, string[] fileNames)
{
var locationID = 0;
var domain = "domain";
var username = "xxx"; //username
var Password = "***"; //password
Debug.WriteLine("Location = "+location);
Debug.WriteLine("fileNames = " + fileNames);
using (new ImpersonateUser(username , domain, Password))
{
Debug.WriteLine("Files names = "+ fileNames);
foreach (string file in fileNames)
{
FileInfo files = new FileInfo(file);
files.Delete();
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize("Files are successfully Deleted"));
}
}
Note
If I pass a string as a parameter without an array, it is working fine
Use the following
data: JSON.stringify({ location: location, fileNames: filesPaths }),
contentType: "application/json; charset=utf-8",
dataType: "json",
and change the input parameter datatype as List<string> instead of string[]
Just remove
dataType: "json",
from your ajax call.
and also check in your asmx file that it is decorated with
[System.Web.Script.Services.ScriptService]
try this.

calling webmethod using jquery

I am having two asp textboxes, TextBoxPicPostCode and TextBoxPicAddress.
The goal of this task is that when i enter a post code in TextBoxPicPostCode and the focus gets lost from this TextBox it should automatically populate TextBoxPicAddress using the method in code behind.
The method getadd() in .cs code works fine and uses google api but i am not getting an idea how to use jquery ajax with it.
Code-Behind
public void getadd()
{
string address = "";
//_Address.InnerText = _PostCode.Text;
XmlDocument xDoc = new XmlDocument();
xDoc.Load("http://maps.google.com/maps/api/geocode/xml?address=" + TextBoxPicPostCode.Text + "&sensor=false");
XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
if (distanceX.Count > 0)
{
address = distanceX[0].InnerXml;
TextBoxPicAddress.Text = address;
}
}
JavaScript
<script type="text/javascript">
function submit() {
$.ajax({
type: "POST",
url: "Establishment_Controller.aspx.cs/getadd",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert("We returned: " + result.d);
}
});
}
</script>
Markup
<asp:TextBox ID="TextBoxPicPostCode" runat="server"
CssClass="time"
onblur="submit();">
</asp:TextBox>
<asp:TextBox ID="TextBoxPicAddress" runat="server"
CssClass="address">
</asp:TextBox>
Make these changes
JavaScript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
<script type="text/javascript">
// change the function name from 'submit' here and at markup
function FetchAddress() {
//passing postalCode as string.
//Make sure that 'postalCode' is the parameter name at the webmethod
var dataValue = "{ 'postalCode' : '" + $('.time').val() + "'}";
//would be worthwhile to read about JSON.stringify, its the standard method
//var dataValue = JSON.stringify({ postalCode: $(".time").val() });
$.ajax({
type: "POST",
url: "Establishment_Controller.aspx/getadd", // .cs is not required
data: dataValue,
contentType: 'application/json', //charset is not required
//dataType: 'json', // not required
success: function (result) {
var data = result.hasOwnProperty("d") ? result.d : result;
//alert("We returned: " + result.d);
// now we are assigning the return value to TextBoxPicAddress
$(".address").val(data);
}
});
}
</script>
Code-behind
//1. webmethod attribute required
[System.Web.Services.WebMethod]
//2. web methods should be static
//ref: http://encosia.com/why-do-aspnet-ajax-page-methods-have-to-be-static/
//3. return type string is needed
// because we need to fetch the return on the ajax callback
//4. we need to pass TextBoxPicPostCode as a parameter
// because we need to fetch the return on the ajax callback
public static string getadd(string postalCode)
{
string address = "No Address found!";
//_Address.InnerText = _PostCode.Text;
XmlDocument xDoc = new XmlDocument();
var remoteXml = "http://maps.google.com/maps/api/geocode/xml?address="
+ postalCode + "&sensor=false";
xDoc.Load(remoteXml);
XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
if (distanceX.Count > 0)
{
address = distanceX[0].InnerXml;
}
return address;
}
At markup, change the event as onblur="FetchAddress();"
P.S: No time to type all the changes made in detail, so added as comment
.cs is Not Required
and
public void getadd()
Should be Static
so
[System.Web.Services.WebMethod]
public static void getadd()
JScript
<script type="text/javascript">
function submit()
{
$.ajax({
type: "POST",
url: "Establishment_Controller.aspx/getadd",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (result) {
alert("We returned: " + result.d);
}
});
}
</script>
EDIT:
You Can't Use Controls Inside Static method. You nee to Refer This:
Using Jquery Ajax Call
Using AutoCompleteExtender
HTML
Javascript
`
function danish() {
var code = $("#<%=TextBoxPicPostCode.ClientID %>").val();
$.ajax({
type: "POST",
url: "GoogleAPI.aspx/getadd",
contentType: 'application/json; charset=utf-8',
data: '{code: "' + code + '"}',
dataType: 'json',
success: function (result) {
$("#<%=TextBoxPicAddress.ClientID %>").autocomplete({ source: result.d });
}
});
return false;
}
</script>`
Codebehind
using System.Web.Services;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;
[WebMethod]
public static List<string> getadd(string code)
{
string address = "";
List<string> lst = new List<string>();
XmlDocument xDoc = new XmlDocument();
var jsonSerialiser = new JavaScriptSerializer();
try
{
HttpWebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;
xDoc.Load(#"http://maps.google.com/maps/api/geocode/xml?address=" + code + "&sensor=false");
XmlNodeList distanceX = xDoc.GetElementsByTagName("formatted_address");
if (distanceX.Count > 0)
{
for (int i = 0; i < distanceX.Count; i++)
{
lst.Add(distanceX[i].InnerXml);
address = address + distanceX[i].InnerXml;
}
}
}
catch (Exception ex)
{
throw ex;
}
return lst;
}

Cast jsondata to NameValueCollection

I trying to pass JSON from jQuery to .ASHX file.
I want retrieve JSON data in .ASHX file by HttpContext and cats to NameValueCollection.
How do it?
$.ajax({
url: "GetLetterInformationHandler.ashx",
data: "{'Name':'david', 'Family':'logan'}",
contentType: "application/json; charset=utf-8",
type: "Get",
datatype: "json",
onSuccess: function (data) {
}
});
Now I can use the querystring and And cast as follows:
public void ProcessRequest(HttpContext context)
{
HttpResponse response = context.Response;
string cururl = context.Request.Url.ToString();
int iqs = context.Request.Url.ToString().IndexOf('?');
string querystring = (iqs < cururl.Length - 1) ? cururl.Substring(iqs + 1) : String.Empty;
NameValueCollection parameters = HttpUtility.ParseQueryString(querystring);
context.Response.ContentType = "text/plain";
}
I want use json insted of querystring
Try this:
$.map(data.d, function (item) {
return {
name: item.Name,
family: item.Family
};
})
Or if you want each function:
var resultData = data.d;
$.each(resultData, function() {
alert(this)
})
I have made some changes hope this will help you :)
Ajax function
$.ajax({
type: "POST",
url: "GetLetterInformationHandler.ashx",
data: "{'Name':'david', 'Family':'logan'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
if( data != null){
if (data.msg == "SUCCESS"); {
alert( data.msg)
}
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
.ASHX file
public void ProcessRequest(HttpContext context)
{
string outputToReturn = String.Empty; // Set it to Empty Instead of ""
context.Response.ContentType = "text/json";
var getName = String.Empty ;
var getFamily = String.Empty ; // Make sure if the Particular Object is Empty or not
if (!string.IsNullOrEmpty(context.Request["Name"]))
{
getName = context.Request["Name"];
}
if (!string.IsNullOrEmpty(context.Request["Subject"]))
{
getFamily = context.Request["Subject"];
}
NameValueCollection nvc = new NameValueCollection();
nvc.Add(getName, getFamily);
var dict = new Dictionary<string, string>();
foreach (string key in nvc.Keys)
{
dict.Add(key, nvc[key]);
}
string json = new JavaScriptSerializer().Serialize(dict);
Console.WriteLine(json);
}

Can't download base64 encoded files in IE

I've got the following Ajax call:
$.ajax({
type: 'POST',
url: 'AJAX.aspx/DownloadFile',
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data)
{
window.location.href = 'data:txt/octet-stream;base64, ' + data.d;
},
error: function (x, e)
{
alert("The call to the server side failed. " + x.responseText);
}
});
And here's my server side code:
[WebMethod]
public static string DownloadFile(){
HttpResponse response = HttpContext.Current.Response;
response.AppendHeader("Content-Disposition", "attachment;filename=b.txt");
FileStream fs = new FileStream("C:/b.txt", FileMode.OpenOrCreate);
byte[] data=new byte[fs.Length];
fs.Read(data, 0, (int)fs.Length);
fs.Close();
return Convert.ToBase64String(data);
}
I've got two problems here:
In Opera,Firefox and Chrome I can download the file composed of the base64 binary data sent from the server. The only problem with them is that the file name is the browser default.In Opera it's "default", in Chrome "download" and in Firefox something like this:"lpyQswKF.part". How can I assign the name manually?
In IE I get the following error:"The webpage cannot be displayed.Some content or files on this webpage require a program that you don't have installed."
You can assign file name like this:
var a = document.createElement("a");
a.download = "file name";
a.href = 'data:txt/octet-stream;base64,' + data.d;
document.body.appendChild(a);
a.click();
I'm still searching how to make it working in IE

Sending a string Value to the WebMethod

function EmpCode(empCode) {
var queryString = "";
var hasQuerystring = document.URL.indexOf('?');
if (hasQuerystring != -1) {
queryString = document.URL.substring(hasQuerystring + 1, document.URL.length);
if (queryString == 'id=1') {
$.ajax({
type: "POST",
url: "EmployeeBasicInfo.aspx/CheckEmpCode",
data: "{'empCode':" + empCode + "}",// Sending empCode which is a string
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var errorMsg = (msg.d);
if (errorMsg != 'NA') {
alert(errorMsg);
}
}
});
}
}
}
Here is my WebMethod
[WebMethod]
public static string CheckEmpCode(string empCode)
{
string empCod = "";
EmployeeFactory empFactory = new EmployeeFactory();
empCod = empFactory.CheckCode(empCode);
return empCod;
}
When i send the empCode as '11479' 0r any integers from Ajax the web method is calling. when i send the empcode as "C1026" or any string with characters then the webmethod is not getting called..
Please suggest me how to pass empCode which is having string value.
Put quotes around the EmpCode.Currently you are sending:
data: {'empCode': C1026}
You need to send:
data: {'empCode': 'C1026'}

Resources