Silverlight error while calling a service - asp.net

I am trying to call a service from a silverlight application, but I am getting the following error.
Uncaught Error: Unhandled Error in Silverlight Application An exception occurred during the operation, making the result invalid. Check InnerException for exception details.
This works fine locally. I don't know if it make any sense, but locally if I add the url of the webservice on a browser, I am getting the details page of the service. In the other hand, on production server, it prompts me to download it.
Does anyone know something about this?
Thanks
public MainPage() {
InitializeComponent();
Loaded += new System.Windows.RoutedEventHandler(MainPage_Loaded);
}
private void MainPage_Loaded(object sender, System.Windows.RoutedEventArgs e) {
var newsFeedWcfClient = new NewsFeedWCFClient();
newsFeedWcfClient.GetNewsFeedItemsCompleted += newsFeedWcfClient_GetNewsFeedItemsCompleted;
newsFeedWcfClient.GetNewsFeedItemsAsync();
}
void newsFeedWcfClient_GetNewsFeedItemsCompleted(object sender, GetNewsFeedItemsCompletedEventArgs e) {
var source = (IList<NewsFeed>)e.Result;
IList<CustomNewsFeed> customNewsFeeds = new List<CustomNewsFeed>();
foreach (var item in source) {
customNewsFeeds.Add(new CustomNewsFeed() {
ProductID = item.Products.ProductID,
ProductTitle = item.Products.Title,
Status = item.Text,
Thumb = string.Format("{0}/{1}", item.Products.Product_Photos.Select(pp => pp.PhotoPath).FirstOrDefault(), item.Products.Product_Photos.Select(pp => pp.PhotoName).FirstOrDefault()),
UserID = item.User.Id,
UserName = item.User.Username
});
}
NewsFeedLB.ItemsSource = customNewsFeeds;
}

The fact that on the production server it "prompts you to download" would suggest that the production web server doesn't know what to do with your .svc or .asmx file. It is treating it like a normal file (.txt, .pdf etc).
Have you got all of the required items installed in production. For instance, you need the correct .NET runtime to be installed. Also, ASP.NET needs to be installed and then enabled.
To determine exactly what is happening I would recommend installing Fiddler and using it to trace what is happening when the Silverlight app calls the server. I have found this approach to be invaluable when troubleshooting Silverlight to Web Service communication problems.

Related

.NET Core Error 1053 the service did not respond to the start or control request in a timely fashion

I created a Windows Service starting from my .NET Core project following this
After this, I installed correctly it on my working machine and started it.
This is my service class:
using System;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading.Tasks;
namespace xxx
{
public class WindowsService
{
static void Main(string[] args)
{
System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);
using (var service = new Service())
{
ServiceBase.Run(service);
}
}
}
internal class Service : ServiceBase
{
public Service()
{
ServiceName = "...";
}
protected override void OnStart(string[] args)
{
try
{
base.OnStart(args);
Task.Run(() => xxxx);
}
catch (Exception ex)
{
EventLog.WriteEntry("Application", ex.ToString(), EventLogEntryType.Error);
}
}
protected override void OnStop()
{
base.OnStop();
}
protected override void OnPause()
{
base.OnPause();
}
}
}
So, I copied the file and installed it also on a server. Here, when I try to start it, I get:
After this, I start a lot of googling... for example, I tried the following steps :
Go to Start > Run > and type regedit
Navigate to: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
With the control folder selected, right click in the pane on the right and - select new DWORD Value
Name the new DWORD: ServicesPipeTimeout
Right-click ServicesPipeTimeout, and then click Modify
Click Decimal, type '180000', and then click OK
Restart the computer
The weird point here is that the voice ServicesPipeTimeout didn't exist and I created it. Comparing the server with my working machine, there are also other value not present in the server. They are:
ServicesPipeTimeout
OsBootstatPath
Here the screenshot of regedit from the server:
Are these relevant?
I also tried to reinstall the service, recompile my files... how can I fix this problem? The error appears immediatly, it doesn't wait any timeout!
I had this problem when I switched my project to another location.
When I moved the project, I had copied the files in bin/debug folder too. The issue was resolved after I cleared the debug folder and created a new build.
See if this works!
It's a bit old question but someone may find this useful.
So I had the following code in Program.cs:
builder.SetBasePath(Environment.CurrentDirectory).AddJsonFile("appsettings.json")
Changed it to:
builder.SetBasePath(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location)).AddJsonFile("appsettings.json")
This seemed to fix the problem for me.
The problem with this error is that it is super generic.
Hopefully MS will give us some log in the future.
if you check the windows event viewer under applications it tells you what exactly is the exception that causes this error.
in my case the problem was i published the service in net6 and tried to run it on a pc with net7 installed. apparently it requires the exact major version that was used to publish the app.

Is there a tool in VS2015 to debug webapi routes?

In Visual Studio 2015 (Enterprise), is there still no built-in tool that will dissect and display the routing information for WebAPI calls?
WebApi Route Debugger does not seem to work for ASP.NET 5 (and mangles the default Help page in the template)
Glimpse does not offer the "Launch Now!" button anymore from what I can tell (http://blog.markvincze.com/use-glimpse-with-asp-net-web-api/).
RouteDebugger is good for figuring out which routes will/will not be hit.
http://nuget.org/packages/routedebugger but you are saying it doesn't work. After some googling I found another solution to your problem,
Add an event handler in Global.asax.cs to pick up the incoming request and then look at the route values in the VS debugger. Override the Init method as follows:
public override void Init()
{
base.Init();
this.AcquireRequestState += showRouteValues;
}
...
protected void showRouteValues(object sender, EventArgs e)
{
var context = HttpContext.Current;
if (context == null)
return;
var routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(context));
}
Then set a breakpoint in showRouteValues and look at the contents of routeData.
Keep in mind that in a Web Api project, the Http routes are in WebApiConfig.cs ... not RouteConfig.cs
but that's not a tool. may be digging up some thread would help you resolve your issue.
Reference: Is there a way I can debug a route in ASP. MVC5?

Uploaded 'multipart/form-data' to ASP.NET Web API action, not readable in bufferless mode

I'm building an ASP.NET Web API endpoint that accepts 'multipart/form-data' requests. I implemented it as described in this article using .NET Framework 4.5 and Web API 2.1. A simplified version of the action method I created, looks like this:
public async Task<HttpResponseMessage> PostFile()
{
if (!Request.Content.IsMimeMultipartContent()) throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
var rootPath = System.Configuration.ConfigurationManager.AppSettings["StorageLocation"].ToString();
var provider = new MultipartFormDataStreamProvider(rootPath);
var response = Request.CreateResponse(HttpStatusCode.OK);
try
{
await Request.Content.ReadAsMultipartAsync(provider);
// Imagine awesome logic here, unicorns and rainbows! Instead of that, we do the following:
response.Content = new StringContent("You uploaded " + provider.FileData.Count.ToString() + " files.");
}
catch (Exception e) { throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e)); }
return response;
}
Because the uploaded files can be very big (up to 2GiB), I want my requests to not be buffered by ASP.NET, thus avoiding high memory usage. To realize this I told Web API to stream incoming requests, instead of buffering them, as described in this article. The custom WebHostBufferPolicySelector looks something like this:
public class CustomWebHostBufferPolicySelector : WebHostBufferPolicySelector
{
public override bool UseBufferedInputStream(object hostContext)
{
System.Web.HttpContextBase contextBase = hostContext as System.Web.HttpContextBase;
if (contextBase != null && contextBase.Request.ContentType != null && contextBase.Request.ContentType.Contains("multipart")) return false;
else return base.UseBufferedInputStream(hostContext);
}
public override bool UseBufferedOutputStream(System.Net.Http.HttpResponseMessage response)
{
return base.UseBufferedOutputStream(response);
}
}
I load this guy in the Global.asax, at application start, like this:
protected void Application_Start(object sender, EventArgs e)
{
// Here, other stuff got did.
GlobalConfiguration.Configuration.Services.Replace(typeof(IHostBufferPolicySelector), new CustomWebHostBufferPolicySelector());
}
Alright, the board is set, lets get the pieces moving. If I don't use my CustomWebHostBufferPolicySelector, everything works just fine. However, when its used, I get the following exception:
Message: "An error has occurred."
ExceptionMessage: "Error reading MIME multipart body part."
ExceptionType: "System.IO.IOException"
StackTrace: " at System.Net.Http.HttpContentMultipartExtensions.<ReadAsMultipartAsync>d__0`1.MoveNext()\ \ --- End of stack trace from previous location where exception was thrown ---\ \ at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\ \ at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\ \ at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\ \ at ..."
With the following inner exception:
Message: "An error has occurred."
ExceptionMessage: "Unable to read the entity body in Bufferless mode. The request stream has already been buffered."
ExceptionType: "System.InvalidOperationException"
StackTrace: " at System.Web.Http.WebHost.HttpControllerHandler.<>c__DisplayClass13.<GetStreamContent>b__10()\ \ at System.Web.Http.WebHost.HttpControllerHandler.LazyStreamContent.get_StreamContent()\ \ at System.Web.Http.WebHost.HttpControllerHandler.LazyStreamContent.CreateContentReadStreamAsync()\ \ at System.Net.Http.HttpContent.ReadAsStreamAsync()\ \ at System.Net.Http.HttpContentMultipartExtensions.<ReadAsMultipartAsync>d__0`1.MoveNext()"
It looks like the request is still buffered somehow, by something else. Is there another place in the ASP.NET pipeline I should be looking? Or even IIS maybe? What are the other places in this request's lifecycle where it can be buffered, and how do I control them?
In an attempt to make the problem more clear and shareable with others, I created a simple project to try and reproduce the problem. While doing this I found the answer: disable all kinds of tracing.
In my case I had ASP.NET's own tracing functionality enabled, and also Glimpse. Both of these buffer the request before it arrives at the Web API action.
For completeness' sake, here the proper way to turn them off in your Web.Config, while testing and in production.
<configuration>
<system.web>
<trace enabled="false" />
</system.web>
<glimpse defaultRuntimePolicy="Off">
</glimpse>
</configuration>
In my case, these two were the culprits, but I can imagine there may be others, so be wary of this.

How to specify credentials from a Java Web Service in PTC Windchill PDMLink

I am currently investigating the possibility of using a Java Web Service (as described by the Info*Engine documentation of Windchill) in order to retrieve information regarding parts. I am using Windchill version 10.1.
I have successfully deployed a web service, which I consume in a .Net application. Calls which do not try to access Windchill information complete successfully. However, when trying to retrieve part information, I get a wt.method.AuthenticationException.
Here is the code that runs within the webService (The web service method simply calls this method)
public static String GetOnePart(String partNumber) throws WTException
{
WTPart part=null;
RemoteMethodServer server = RemoteMethodServer.getDefault();
server.setUserName("theUsername");
server.setPassword("thePassword");
try {
QuerySpec qspec= new QuerySpec(WTPart.class);
qspec.appendWhere(new SearchCondition(WTPart.class,WTPart.NUMBER,SearchCondition.LIKE,partNumber),new int[]{0,1});
// This fails.
QueryResult qr=PersistenceHelper.manager.find((StatementSpec)qspec);
while(qr.hasMoreElements())
{
part=(WTPart) qr.nextElement();
partName = part.getName();
}
} catch (AuthenticationException e) {
// Exception caught here.
partName = e.toString();
}
return partName;
}
This code works in a command line application deployed on the server, but fails with a wt.method.AuthenticationException when performed from within the web service. I feel it fails because the use of RemoteMethodServer is not what I should be doing since the web service is within the MethodServer.
Anyhow, if anyone knows how to do this, it would be awesome.
A bonus question would be how to log from within the web service, and how to configure this logging.
Thank you.
You don't need to authenticate on the server side with this code
RemoteMethodServer server = RemoteMethodServer.getDefault();
server.setUserName("theUsername");
server.setPassword("thePassword");
If you have followed the documentation (windchill help center), your web service should be something annotated with #WebServices and #WebMethod(operationName="getOnePart") and inherit com.ptc.jws.servlet.JaxWsService
Also you have to take care to the policy used during deployment.
The default ant script is configured with
security.policy=userNameAuthSymmetricKeys
So you need to manage it when you consume your ws with .Net.
For logging events, you just need to call the log4j logger instantiated by default with $log.debug("Hello")
You can't pre-authenticate server side.
You can write the auth into your client tho. Not sure what the .Net equivilent is, but this works for Java clients:
private static final String USERNAME = "admin";
private static final String PASSWORD = "password";
static {
java.net.Authenticator.setDefault(new java.net.Authenticator() {
#Override
protected java.net.PasswordAuthentication getPasswordAuthentication() {
return new java.net.PasswordAuthentication(USERNAME, PASSWORD.toCharArray());
}
});
}

Thread aborting issue with Sharp Svn with C#.Net 4.0

I have developed ASP.net application using VS-2010, C#.Net 4.0 with SharpSvn dll. When I'm working with dev server(don't have 3-Tier Architecture), it works fine. But when we are working with QA environment(have 3-Tier Architecture) it gives thread abort exception most of the time.Following shows the code and error log I have. Any help on this really appreciate.
public bool Checkout(string svnurl, string target)
{
try
{
using (_client = new SharpSvn.SvnClient())
{
_client.LoadConfiguration(Path.Combine(Path.GetTempPath(), "Svn"), true);
_client.Authentication.DefaultCredentials = new TNetworkCredential(_username, _password);
_client.Authentication.SslServerTrustHandlers += SvnSslOveride;
var targetsvn = new SvnUriTarget(svnurl);
if (_client.CheckOut(targetsvn, target))
{
Log.Info("Successfully checked out to following location : " );
Log.Info(target);
return true;
}
}
Log.Info("Unable to checkout "+ svnurl +" Svn location to target location : ");
Log.Info(target);
return false;
}
catch (Exception ee)
{
Log.Error("Error:SvnClient checkout....");
Log.Error(ee);
throw ee;
return false;
}
}
private static void SvnSslOveride(object sender, SvnSslServerTrustEventArgs e)
{
e.AcceptedFailures = e.Failures;
e.Save = true;
}
error log
ERROR 2013-08-12 12:13:37,714 3223821ms SvnClient Checkout -
Error:SvnClient checkout.... ERROR 2013-08-12 12:13:37,730 3223837ms
SvnClient Checkout - System.Threading.ThreadAbortException: Thread was
being aborted. at svn_client_checkout3(Int32* , SByte* , SByte* ,
svn_opt_revision_t* , svn_opt_revision_t* , svn_depth_t , Int32 ,
Int32 , svn_client_ctx_t* , apr_pool_t* ) at
SharpSvn.SvnClient.CheckOut(SvnUriTarget url, String path,
SvnCheckOutArgs args, SvnUpdateResult& result) at
SharpSvn.SvnClient.CheckOut(SvnUriTarget url, String path)
I missed <httpRuntime executionTimeout="(time in seconds)">
tag in web config and it automatically set by IIS server. The default is 110 seconds.
Note :In the .NET Framework 1.0 and 1.1, the default is 90 seconds.
After I added following line to web.config and it works fine.
<httpRuntime executionTimeout="600">
Previously it works sometimes because the time taken to SVN checkout in DEV server is less than in other environment because of the size of the repositories and network connections. Thanks all for your answers
As per my comment above, I've seen this issue. It appears to be related to plink authentication.
I resolved it by upgrading to the latest build of SharpSVN v1.7, at which point the error changed from a null-ref exception in the C++, to an SVN exception with the message "Can't create tunnel: The parameter is incorrect".
There are a few articles which explain how to resolve this, the best of which I've found here:
SVN+SSH and Sourceforge
In my case, changing the backslashes to forwardslashes in the SVN_SSH env var resolved the problem. Worth giving a shot.

Resources