I have a Visual Studio solution with a Silverlight project, and a web project which hosts the Silverlight app. The web project also contains an ASMX web service which is called by the Silverlight ap.
As described below, certain calls to the web service work fine, and yet others cause a CommunicationException to be thrown, wrapping a WebException - both with the message "The server returned the following error: 'not found'".
Firstly, here's my original method, which failed as described above (entity names changed for simplicity):
[WebMethod]
public Customer GetCustomer(int id)
{
CustomerDataContext dc = new CustomerDataContext();
return dc.Customers.SingleOrDefault(x => x.Id == id);
}
Secondly, to debug the problem I took Linq to SQL and the database out of the picture, and the below code worked fine:
[WebMethod]
public Customer GetCustomer(int id)
{
Customer c = new Customer() { ID=1, Name="Bob", History = new EntitySet<CustomerHistory>() };
return c;
}
Third, thinking about this, one difference between the two methods is that the first one would include values in the customer history. I extended the second method to include this, and it started failing again:
[WebMethod]
public Customer GetCustomer(int id)
{
Customer c = new Customer() { ID=1, Name="Bob", History = new EntitySet<CustomerHistory>() };
c.History.Add(new CustomerHistory() { Id=1, CustomerId=1, Text="bla" });
return c;
}
I'm stuck with regards to how to progress - my current thinking is that this could be a deserialization issue on the Silverlight side, when the object graph is deeper. This rationally doesn't make sense, but I can't think of anything else. I've confirmed that the transfer size and buffer size are big enough (2GB by default).
Any pointers would be appreciated.
Ahhhh the famous "Not Found" error, try to get details from that error using the tag in your web.config. That will create a log file providing details of the error.
The following link explains exaclty how to do it :
http://blogs.runatserver.com/lppinson/post/2010/04/15/Debugging-WCF-Web-Services.aspx
Related
I am developing a small instant messaging application that makes use of few DomainServices on the server side. Trying to access the domain service URL, I encounter the following error:
"ContractDescription 'AppInitService' has zero operations; a contract must have at least one operation".
The domain service Url is this one:
http://givemeword.net/chat/Services/IM-Chat-UI-Web-DomainServices-AppInitService.svc
You can find the domain service class below:
namespace Chat.UI.Web.DomainServices
{
[EnableClientAccess()]
public class AppInitService : DomainService
{
private System.Security.Principal.IPrincipal _user;
private readonly Chat.UI.Web.Services.AppInitService _appInitService;
public AppInitService()
{
_appInitService = new Chat.UI.Web.Services.AppInitService();
}
public InitUserSettingsDTO InitUserSettings(Guid userId)
{
var initUserSettingsDTO = new InitUserSettingsDTO();
return initUserSettingsDTO;
}
}
}
As you can see, I am using a complex type as the return type of the only function of the domain service.
What I can not figure out is why on my testing Windows Server 2012 (not a development machine, just a virtual machine used for testing) or on my development machine everything runs without any problem, but on the hosting account it raise the error above.
Does anyone has any idea about this?
Thank you
Try adding the [Invoke] attribute to your InitUserSettings method:
[Invoke]
public InitUserSettingsDTO InitUserSettings(Guid userId)
{
var initUserSettingsDTO = new InitUserSettingsDTO();
return initUserSettingsDTO;
}
Make sure your web.config is set up as described here: http://msdn.microsoft.com/en-us/library/ff426912(v=vs.91).aspx
Being exasperated with this strange situation and the low support I received from the web hosting company, I have tried the same thing with another web provider. As I was thinking, it was working this time with no problems, so my assumption that the original provider had poor support for WCF RIA Services (or maybe other unidentified problem) was correct.
I tried to solve by myself, but... Looks like I need help from people.
I have Business Silverlight application with WCF RIA and EntityFramework. Access to Database I get via LinqToEntites.
Common loading data from database I making by this:
return DbContext.Customers
This code returns full Customers table from DataBase. But sometimes I do not need to show all data. Easy way is use linq filters in client side by next code:
public LoadInfo()
{
...
var LO1 = PublicDomainContext.Load(PublicDomainContext.GetCustomersQuery());
LO1.Completed += LO1Completed;
...
}
private void LO1Completed(object sender, EventArgs eventArgs)
{
...
DatatViewGrid.ItemsSource = null;
DatatViewGrid.ItemsSource = loadOperation.Entities.Where(c=>c ...filtering...);
//or PublicDomainContext.Customers.Where(c=>c ...filtering...)
...
}
However this way has very and very important flaw: all data passing from server to client side via DomainService may be viewed by applications like Fiddler. So I need to come up with another way.
Task: filter recieving data in server side and return this data.
Way #1: LinqToEntites has a beautiful projection method:
//MSDN Example
var query =
contacts.SelectMany(
contact => orders.Where(order =>
(contact.ContactID == order.Contact.ContactID)
&& order.TotalDue < totalDue)
.Select(order => new
{
ContactID = contact.ContactID,
LastName = contact.LastName,
FirstName = contact.FirstName,
OrderID = order.SalesOrderID,
Total = order.TotalDue
}));
But, unfortunately, DomainServices cannot return undefined types, so this way won't work.
Way #2: I found next solution - make separate DTO classes (DataTransferObject). I just read some samples and made on the server side next class:
[DataContract]
public partial class CustomerDTO
{
[DataMember]
public int ISN { get; set; }
[DataMember]
public string FIO { get; set; }
[DataMember]
public string Listeners { get; set; }
}
And based this class I made a row of methods which return filtered data:
[OperationContract]
public List<CustomerDTO> Customers_Common()
{
return DbContext.Customers....Select(c => new CustomerDTO { ISN = c.ISN, FIO = c.FIO, Listeners = c.Listeners }).ToList();
}
And this works fine, all good...
But, there is strange problem: running application locally does not affect any troubles, but after publishing project on the Web Site, DomainService returns per each method HTTP 500 Error ("Not Found" exception). Of course, I cannot even LogIn into my application. DomainService is dead. If I delete last class and new methods from application and republish - all works fine, but without speacial filtering...
The Question: what I do wrong, why Service is dying with new classes, or tell me another way to solve my trouble. Please.
U P D A T E :
Hey, finally I solved this!
There is an answer: Dynamic query with WCF RIA Services
Your best shot is to find out what is causing the error. For that, override the OnError method on the DomainService like this:
protected override void OnError(DomainServiceErrorInfo errorInfo)
{
/* Log the error info to a file. Don't forget inner exceptions.
*/
base.OnError(errorInfo);
}
This is useful, because only two exceptions will be passed to the client, so if there are a lot of nested inner exceptions, you should still be able to see what actually causes the error.
In addition, you can inspect the error by attaching the debugger to the browser instance you are opening the site with. In VS2010 this is done by doing [Debug] -> [Attach to Process] in the menu-bar.
I've been looking for it, for quite and while, and I didn't really find anything that cover how to pull data trough duplex connection for Silverlight (pollingHttpDuplex).
I have setup basic sub/pub application with duplex.
Now I wanted to get list of topics, that are users are connected to. My first thought, was to setup simple DataContract (with only one field TopicName), then get data from Dicionary that I've been using to store current topics.
So I end up with something like this:
[OperationContract]
public List<Topic> GetTopicList()
{
List<Topic> topicList;
topicList = (from p in _sessionIDTopic
select new Topic
{
TopicName = p.Value
}).ToList<Topic>();
return topicList;
}
[DataContract]
public class Topic
{
[DataMember]
public string TopicName { get; set; }
}
I'm doing something wrong here. Because big question is how to send this to the client (Silverlight 4), and bind it to controls ?
Also duplex is essential for application. Changing it for anything else is not an option.
Using a duplex connection here doesn't have any effect on how you get the data to the client. The example you specified looks like simple one way communication. To do that, your client project needs a service reference to the server, and the generated proxy will provide the methods the client needs to access the operations on the server.
I think you should start by looking at a simple WCF example project to see what I mean. If this is not your problem, please rephrase the question.
Having a lot of problems trying to consume a simple service operator in a WCF Data Service from Silverlight. I've verified the following service operator is working by testing it in the browser:
[WebGet]
public IQueryable<SecurityRole> GetSecurityRolesForUser(string userName) {
string currentUsername = HttpContext.Current.User.Identity.Name;
// if username passed in, verify current user is admin and is getting someone else's permissions
if (!string.IsNullOrEmpty(userName)) {
if (!SecurityHelper.IsUserAdministrator(currentUsername))
throw new DataServiceException(401, Properties.Resources.RequiestDeniedInsufficientPermissions);
} else // else nothing passed in, so get the current user's permissions
userName = currentUsername;
return SecurityHelper.GetUserRoles(userName).AsQueryable<SecurityRole>();
}
However no matter how I try using different methods I've found in various online resources, I've been unable to consume the data. I've tried using the BeginExecute() method on boht the DataServiceContext and DataServiceQuery, but I keep getting errors or no data returned in the EndExecute method. I've got to be doing something simple wrong... here's my SL code:
private void InitUserSecurityRoles() {
MyEntities context = new MyEntities(new Uri("http://localhost:9999/MyService.svc"));
context.BeginExecute<SecurityRole>(new Uri("http://localhost:9999/MyService.svc/GetSecurityRolesForUser"), OnComplete, context);
DataServiceQuery<SecurityRole> query = context.CreateQuery<SecurityRole>("GetSecurityRolesForUser");
query.BeginExecute(OnComplete, query);
}
private void OnComplete(IAsyncResult result) {
OnDemandEntities context = result.AsyncState as OnDemandEntities;
var x = context.EndExecute<SecurityRole>(result);
}
Any tips? I'm at a loss right now on how to properly consume a custom service operator from Silverlight (or even sync using my unit test project) from a OData service. I've also verified via Fiddler that I'm passing along the correct authentication stuff as well, even going to far as explicitly set the credentials. Just to be safe, I even removed the logic from the service operator that does the security trimming.
Got it working thanks to #kaevans (http://blogs.msdn.com/b/kaevans):
private void InitUserSecurityRoles() {
DataServiceContext context = new DataServiceContext(new Uri("http://localhost:9999/MyService.svc"));
context.BeginExecute<SecurityRole>(new Uri("/GetSecurityRolesForUser", UriKind.Relative),
(result) => {
SmartDispatcher.BeginInvoke(
() => {
var roles = context.EndExecute<SecurityRole>(result);
UserSecurityRoles = new List<SecurityRole>();
foreach (var item in roles) {
UserSecurityRoles.Add(item);
}
});
}, null);
}
I had to create the SmartDispatcher because this is happening in a ViewModel. Otherwise I could have just used the static Dispatcher.BeginInvoke(). Couldn't get the roles variable to insert into my UserSecurityRoles (type List) directly for sone reason using various techniques, so I just dropped down to adding it manually (code isn't called often nor is it a collection exceeding more than 10 items max... most are <5).
I'm developing my first windows phone 7 app, and I've hit a snag. basically it's just reading a json string of events and binding that to a list (using the list app starting point)
public void Load()
{
// form the URI
UriBuilder uri = new UriBuilder("http://mysite.com/events.json");
WebClient proxy = new WebClient();
proxy.OpenReadCompleted += new OpenReadCompletedEventHandler(OnReadCompleted);
proxy.OpenReadAsync(uri.Uri);
}
void OnReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
var serializer = new DataContractJsonSerializer(typeof(EventList));
var events = (EventList)serializer.ReadObject(e.Result);
foreach (var ev in events)
{
Items.Add(ev);
}
}
}
public ObservableCollection<EventDetails> Items { get; private set; }
EventDetails is my class that wraps the json string. this class has to be correct because it is an exact copy of the class used by that website internally from which the json is generated...
I get the json string correctly from the webclient call (I read the memorystream and the json is indeed there) but as soon as I attempt to deserialize the string, the application exits and the debugger stops.
I get no error message or any indication that anything happen, it just stops. This happens if I type the deserialize method into the watch window as well...
I have already tried using JSON.net in fact I thought maybe it was a problem with JSON.net so I converted it to use the native deserializer in the .net framework but the error is the same either way.
why would the application just quit? shouldn't it give me SOME kind of error message?
what could I be doing wrong?
many thanks!
Firstly, the fact that you have some string there that looks like JSON does not mean that you have a valid JSON. Try converting a simple one.
If your JSON is valid, it might be that your JSON implementation does not know how to convert a list to EventList. Give it a try with ArrayList instead and let me know.
The application closes because an unhandled exception happens. If check the App.xaml.cs file you will find the code that closes your app. What you need to do is try catch your deserialization process and handle it locally. So most likely you have some JSON the DataContractJsonSerializer does not like. I have been having issue with it deserializing WCF JSON and have had to go other routes.
You may want to check to ensure your JSON is valid, just because your website likes it does not mean it is actually valid, the code on your site may be helping to correct the issue. Drop a copy of your JSON object (the string) in http://jsonlint.com/ to see if it is valid or not. Crokford (the guy who created JSON) wrote this site to validate JSON, so I would rely on it more than your site ;) This little site has really helped me out of some issues over the past year.
I ran into this same kind of problem when trying to migrate some existing WM code to run on WP7. I believe that the WP7 app crashes whenever it loads an assembly (or class?) that references something that's not available in WP7. In my case, I think it was Assembly.Load or something in the System.IO namespace, related to file access via paths.
While your case might be something completely different, the symptoms were exactly the same.
The only thing I can recommend is to go through the JSON library and see if it's referencing base classes that are not allowed in WP7. Note that it doesn't even have to hit the line of code that's causing the issue - it'll crash as soon as it tries to hit the class that contains the bad reference.
If you can step into the JSON library, you can get a better idea of which class is causing the problem, because as soon as the code references it, the whole app will crash and the debugger will stop.