Why server.mapPath is Invalid report file path in production but local machine is valid? - asp.net

i spend a lot of time to resolve this problem but to working. I use server.mapPath function to specific valid path file. why only local machine is working but not working in production because i this (server.mapPath) is a great function
c#
[WebMethod]
public string getDocument(string id, string location)
{
ReportDocument report = new ReportDocument();
report.Load(Server.MapPath("~/Reports/report1.rpt"));
Stream stream = report.ExportToStream(ExportFormatType.PortableDocFormat);
MemoryStream streamReader = new MemoryStream();
stream.CopyTo(streamReader);
return Convert.ToBase64String(streamReader.ToArray());
}
ajax
function printPreview(reqID) {
var base_url = "/Webservice/webService.asmx/getDocument";
$.ajax({
type: "POST",
url: base_url,
data: "{'id': " + reqID + ", 'location':'" + objUser.location + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response.d)
},
error: function (response) {
alert(response.d);
}
});
Check API backend
Look like the problem happen when ReportDocument.Load because i test in production with File.Exists function without ReportDocument.Load and the result return file is exist but cannot load why ? Have any one else know this ?
error exception
Could not load file or assembly 'CrystalDecisions.CrystalReports.Engine, Version=13.0.3500.0, Culture=neutral, PublicKeyToken=692fbea5521e1304' or one of its dependencies. The system cannot find the file specified.
I'm add bindingRedirect from 13.0.2000.0 -> 13.0.3500.0 in web.config and still not working. I'm see in server production C:/Windows/assembly all of (CrystalDecisions.Shared, CrystalDecisions.CrystalReports.Engine, CrystalDecisions.ReportSource) is version 13.0.2000.0 but why another project is working. Please help me, thank you so much.

Try without the tilde and forward slash character.
report.Load(Server.MapPath("Reports/report1.rpt"));
This expects report (.rpt file) to be available in 'Reports' subfolder of your application root folder

You could use System.IO Path.Combine. There you just add your Foldernames and your Filename and get a correctly formatted Path. Could look something like that:
string sPath = Path.Combine(#"\\" + "Reports", "report1.rpt");
You can add string variables (Foldernames) with just a comma.

Related

ReCaptcha v3 works locally, but not on remote server (500 Internal Server Error)

I am unable to get captcha to work on server. It works fine locally and I get it to return a score without issue.
JavaScript after button is clicked.
(function () {
$('#btnLogin').click(function () {
$.ajax({
type: "POST",
url: "/captcha/lasttry.aspx/CaptchaVerify",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var _response = JSON.parse(response.d);
if (_response.score < 0.5) {
$('#status').text("User is not human being! Score = " + _response.score);
$('#status').removeClass('text-info').addClass('text-danger');
}
else {
$('#status').text("User is human being . Score = " + _response.score);
$('#status').removeClass('text-error').addClass('text-success');
}
},
failure: function (response) {
$('#status').text("Error on Server!");
}
});
});
})();
CodeBehind:
[WebMethod]
public static string CaptchaVerify()
{
//It should only call once
if (response.score == 0)
{
var responseString = RecaptchaVerify(Token);
response = JsonConvert.DeserializeObject<ResponseToken>(responseString.Result);
}
return JsonConvert.SerializeObject(response);
}
private static string apiAddress = "https://www.google.com/recaptcha/api/siteverify";
private static async Task<string> RecaptchaVerify(string recaptchaToken)
{
//try/catch omitted to try to see error with customErrors off
String url = $"{apiAddress}?secret={recaptchaSecret}&response={recaptchaToken}";
HttpClient httpClient = new HttpClient();
String responseString = httpClient.GetStringAsync(url).Result;
return responseString;
}
When I run it remotely I get the following error (1st image Google console, 2nd Wireshark):
Firewall is open to Google, I have added the site to captcha admin. Keys are correct. they have been checked and re-checked. I am not sure if I am missing something in the web.config, or if there is a setting in IIS manager that I am missing.
You can't troubleshoot your problem just based on these error messages. You can try the following methods to get more detailed error messages:
Run the site directly on the server – depending on the configuration of your site/server, you may be able to see the real error if you load the site from a browser located on the same server. You may need to turn off 'show friendly http errors.'
Temporarily add the following within the appropriate tags in your web.config file:
<configuration>
<system.webServer>
<httpErrors errorMode="Detailed" />
</system.webServer>
<system.web>
<customErrors mode="Off" />
<compilation debug="true" />
</system.web>
</configuration>
After you have added those, load the page again to see if you can get a more detailed error.
Open up IIS Manager and try to open up some of the different features by clicking on the icon. If there is an error in the web.config file and it can’t even parse it, sometimes you will get a helpful error in IIS Manager when you try to open a feature.
Look in Event Viewer. Sometimes you can find the detailed error logged in there, particularly Application Event Viewer.
Setup Failed Request Tracing. This will often give you details on the 500 error. This is especially helpful if it is an intermittent 500 error.
Look through the web log files. This is especially helpful for an intermittent 500 error. You can often parse the log files to see if there is a trend with a specific page that is throwing a 500 error.
In case someone else comes across this problem in the future, it was the WinHTTP proxy on the production server. The following code fixed my issue:
WebProxy proxyObject = new WebProxy("http://proxyserver:80/",true);
WebRequest req = WebRequest.Create("http://www.contoso.com");
req.Proxy = proxyObject;
More info can be found at https://learn.microsoft.com/en-us/dotnet/api/system.net.webproxy?view=net-5.0

ASP.NET webservice responds with Internal Server Error (500) to post and get requests

The webservice code is simple:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void receiveOrder(string json) {
Context.Response.Write("ok");
}
And the jquery calling the webservice is as follows:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: 'http://localhost:50730/GingerWeb.asmx/receiveOrder',
data: 'test', //JSON.stringify(webOrder),
dataType: "text",
success: function(data){
if(data === "ok")
orderPlaced();
}
});
And yet the chrome console reads in provocative red:
500 (Internal Server Error)
The problem is that ASMX web-service need to find all input parameters in the request. If at least one input parameter will be not found in the request to the server the web service failed with the status code 500 (Internal Server Error).
The reason is that you send the data in the wrong way. The name of the input parameter of the web method is json (see void receiveOrder(string json)). So the data option of the $.ajax should be in the form
data: JSON.stringify({json: webOrder})
if you use type: "POST" instead of data: JSON.stringify(webOrder) which you tried before. In the case in the body of the POST request will be json=theVlue instead of just theValue.
If you would use type: "GET" the format of data parameter should be changed to
data: {json: JSON.stringify(webOrder)}
The value of the dataType should be 'json'. After the changes the $.ajax should work.
Moreover I would recommend you to use relative paths in the url option. I mean to use '/GingerWeb.asmx/receiveOrder' instead of 'http://localhost:50730/GingerWeb.asmx/receiveOrder'. It will save you from same origin policy errors.
Hello Oleg: Your explanation is simple and to the point. I had a similar problem which your explanation solved. I am providing code snippet to help 'searchers' understand what I was facing and how the above helped solve. In short I am issuing a simple jquery (.ajax) from a aspx page. I have created a webservice that gets some data from backend (cache/db) and return's the same in json format.
JS CODE:
var parameters = "{'pageName':'" + sPage + "'}"
var request = $.ajax({
type: "POST",
url: "/NotificationWebService.asmx/GetNotification",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json"
});
ASP.NET Code Behind for Web Service
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetNotification(string pageName)
{
JavaScriptSerializer js = new JavaScriptSerializer();
Notification ns = NotificationCache.GetActiveNotificationForPage(pageName);
if (ns != null)
{
NotificationJSData nJSData = new NotificationJSData();
nJSData.Code = ns.Code;
nJSData.displayFreq = (short)ns.DisplayFreq;
nJSData.expiryDate = ns.ToDateStr;
return js.Serialize(nJSData);
}
return null;
}
It is ABSOLUTELY necessary to ensure that you match 'pageName' variable name specified in web service code with what is sent in your data parameter of the ajax request. I had them different and changed it to be the same, after spending hours, I finally found the right solution, thanks to this post. Also, in my case I am only passing a single "name:value" pair so I didn't even have to use some json De-serialization function to get the value, pageName above gives me only the value.

Problem retrieving XML data from an ASP.NET Web service

I am trying to call a Web service to retrieve some XML data from a database. The Ajax call works fine if I use a static file e.g. like this:
$.ajax({
type: "GET",
url: "test2.xml",
data: buildXMLDataRequestObject(),
dataType: "xml",
success: getXMLDataSucceeded,
error: getXMLDataFailed
});
but fails when I try to call the Web service e.g. like this:
$.ajax({
type: "POST",
url: "Services/CheckOutService.svc/GetXMLData",
data: buildXMLDataRequestObject(),
dataType: "xml",
success: getXMLDataSucceeded,
error: getXMLDataFailed
});
The error I get is:
"The incoming message has an
unexpected message format 'Raw'. The
expected message formats for the
operation are 'Xml', 'Json'. This can
be because a WebContentTypeMapper has
not been configured on the binding.
See the documentation of
WebContentTypeMapper for more
details."
The GetXMLData method looks like this:
// Interface
[OperationContract]
[WebInvoke(ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
string GetXMLData(XMLDataRequest request);
...
// Implementation
public string GetXMLData(XMLDataRequest request)
{
request.ShopperId = ShopperId;
return checkOutManager.GetXMLData(request);
}
The GetXMLData method has been configured to return XML and the Ajax call has its datatype set as XML so I'm very confused as to what is causing the error.
EDIT: If I alter the $.ajax() call slightly so that the contentType is specified I get this error:
The data at the root level is invalid.
Line 1, position 1.
I've tried contentType: "text/xml" and contentType: "application/xml" and both give the same error.
EDIT: Yesterday (Aug 30th) I noticed that the service call would succeed if I omitted the data parameter of the ajax call. I guess there is something about the JSON object that is causing a problem. For now I have implemented this functionality on the server side of the application but I do intend to revisit this when I get some time.
My first guess would be that the content type was wrong. What do you see when you look at the stream using Fiddler or similar?

Getting "401 Unauthorized" error consistently with jquery call to webmethod

I have been struggling to get my jquery call to a webmethod to work. I am being bounced by the server with a "401 Unauthorized" response. I must have an incorrect setting in the web.config or somewhere else that would be preventing a successful call.
Your insight is appreciated!
Call to js function the invokes the jquery call
button.OnClickAction = "PageMethod('TestWithParams', ['a', 'value', 'b', 2], 'AjaxSucceeded', 'AjaxFailed'); return false;";
JavaScript function that makes the jquery call
function PageMethod(fn, paramArray, successFn, errorFn) {
var pagePath = window.location.pathname;
var urlPath = pagePath + "/" + fn;
//Create list of parameters in the form:
//{"paramName1":"paramValue1","paramName2":"paramValue2"}
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
//Call the page method
$.ajax({
type: "POST",
url: pagePath + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
timeout: 10000,
dataType: "json",
success: function(result) { alert('Overjoyed'); },
error: function(result) { alert('No joy'); }
});
}
Web method in page
public partial class WebLayout : System.Web.UI.Page
{
[WebMethod()]
public static int TestNoParams()
{
return 1;
}
[WebMethod()]
public static string TestWithParams(string a, int b)
{
return a + b.ToString();
}
...
Response as seen in Firebug console
json: {"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
and
"NetworkError: 401 Unauthorized - http://localhost/Care-Provider-Home/Profile/Personal-Profile.aspx/TestWithParams" TestWithParams
I have looked at and read the usual sites on the subject (Encosia, et al), but to avail. Either I am missing a critical piece, or there are some subtleties in the security parameters of my environment that preventing a call.
Here are some other potentially useful tidbits that may impact your diagnosis:
Webmethods in codebehind
Using Sitecore CMS (Does not seem to intefere, never know)
IIS7
.NET 3.5
jQuery 1.3.2
I look forward to your insights and direction--thank you!
Yes, it did get working! Since Sitecore CMS does perform URL rewriting to generate friendly URLs (it assembles the pages in layers, dynamically, similar to Master Page concept), it occurred to me that it may be causing some problem the initially caused the 401 error. I verified this by creating a separate project with a single ASPX--and with some work I was able call the web methods and get values using the jquery. I then created nearly identical ASPX in my web root, but told Sitecore to ignore it when a request is made to it (IgnoreUrlPrefixes in the web.config), after some work I was able also get it to work successfully! Thanks for your help.
The json response from the Firebug Console provides the most telling clue IMO. The System.InvalidOperationException (which strangely rides on a 401 response) suggests something more is at work.
First, googling on "InvalidOperationException webmethod jquery" returns articles which suggest serialization problems can throw this exception. To rule this out, temporarily change "data: paramList" to "data: '{}'". In addition, attach a debugger and see if the exception happens before the method executes or after it completes and attempts to serialize the result.
If the steps above come up empty, you may want to try resetting to a clean web.config or read more of the results that come back from the "InvalidOperationException webmethod" search
What form of authentication are you using, if any? The first thing that comes to mind is to make sure that your webApp in IIS is set to allow anonymous users (if you indeed desire to make the call as an anonymous user). Also that your Authentication mode in web.config is not set to Windows by mistake. If you cannot allow anonymous users and are using forms authentication, then the user will have to be logged in before this call is made from your page.
If the above are properly set, then try making a regular call to the service from server side to make sure the problem is consistent regardless of the point of invocation of the service.
Post more settings if the problem is not resolved. Hope this helps.

JQuery AJAX Web Service call on SSL WebServer

I am making a POST to a webservice that is local to the webserver. Everything works great until I host the site at my SSL enabled webserver. The webservice path is relative, meaning, I am making no reference to the protocol. eg. /webservices/method.asmx
The POST results in a runtime error. Has anyone seen this before?
$.ajax({
type: "POST",
url: theURL + "/" + method,
data: body,
success: function (msg) {
alert("Data Saved: " + msg);
},
error: function (msg) {
alert("Broken: " + theURL + "/" + method + msg.responseText);
}
});
What happens if you specify an absolute url, including the protocol https:// piece... I usually put a javascript variable in my masterpages/template for "baseURL" for the prot://host:port/apppath/ reference... where port is only included if not the default. Haven't, iirc, seen such an issue.
Because this project is done in .NET 2.0.. the web method seems to handle the input data differantly. I was able to get around this by just construction a query sting and passing it rather than a JSON object.

Resources