WCF Property wont set in response - c#

i have a problem with WCF service.. i am using service reference in windows app project. In Reply to one of my wcf methods there is a class which has a propety ID int (datacontract) it always comes 0. When i try from code it works. but when i actually installl the wcf service and try it comes 0. any idea guys ? some settings with proxy? anything at all?
[DataMember(Order = 1)]
public int ID { get; set; }
[DataMember(Order = 2)]
public int Quantity { get; set; }
now quantiy is populated, but ID is always 0. I chekcd the database calls, ID and quantiyt is returned. also mapping are all correct. From code i get both values but when i install setup this ID field never retuned

This problem was related to multilingual application. This code worked fine for English, but in other language login it failed.
Reason being, In request parameter dates were passed, and for login other than english, date comparison used to fail.

Related

ASP.net Core API : ValidationVisitor exceeded the maximum configured validation depth '32'

AS am running an ASP.Net core web API from docker container , it throws a validation error :
System.InvalidOperationException: ValidationVisitor exceeded the maximum configured validation depth '32' when validating type 'ClassName'. This may indicate a very deep or infinitely recursive object graph. Consider modifying 'MvcOptions.MaxValidationDepth' or suppressing validation on the model type.
The only place I could find a discussion about this issue is in
here , where it seems that a fix has been provided on the latest version of ASP.net core . I updated my .net core version to the latest , but still facing the same issue.
Here is the code of the class where the validation is causing the issue :
[Required]
[Range(1, long.MaxValue)]
public long Id { get; set; }
[Required(AllowEmptyStrings = false)]
[StringLength(1000)]
public string Name { get; set; }
[Required(AllowEmptyStrings = false)]
[StringLength(200)]
public string Category { get; set; }
[Required(AllowEmptyStrings = false)]
[StringLength(13)]
public string Division { get; set; }
Important : Am the only one facing the issue , as the rest of my team is running the project successfully , any help is highly appreciated.
It is a bug in Asp.Net Core ModelBinding Validation affecting MVC and Web Api
https://github.com/dotnet/aspnetcore/issues/13778
One workaround is to increase MaxModelValidationErrors in Startup.ConfigureServices:
services.AddMvc()
.AddMvcOptions(options => {
options.MaxModelValidationErrors = 999999;
})
Increasing MaxModelValidationErrors didn't fix things for me, I had to change a different value (MaxValidationDepth) to get things to work. Wanted to add it here in case anyone had the same problem as I did.
.AddMvcOptions(options =>
{
options.MaxValidationDepth = 999;
});
You could increase MaxModelValidationErrors in Startup.ConfigureServices:
services.AddControllers(options =>
{
options.MaxModelValidationErrors = 999999;
});
I cannot recommend SuppressChildValidationMetadataProvider anymore.
But you can use this attribute:
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
[ValidateNever]
public List<ToNotValidateSet> ToNotValidateSet { get; set; }
...on all the virtual properties that should not get validated.
I am in the process of upgrading a project to .NET 6 and ran into this error message. The above solutions did not fix it. The validation error was referring to a virtual Subproperty and a validated something that I did not even want to be validated at this point.
This fixed it for me:
services.AddMvc(option => {
//fix: max validation depth error in TryValidateModel(model) since .NET6
option.ModelMetadataDetailsProviders.Add(new SuppressChildValidationMetadataProvider(typeof(MyVirtualSubpropertyClassThatShouldNotBeValidated)));
});
Disclaimer: I am well aware that this is a quickfix and potentially has sideeffects. Also I cannot spend a week on properly fixing it and just want a working version for now.
The issue for me was that I was using lazy loading with Entity Framework Core.
The validator would traverse the model recursively and fetch all bound properties through the lazy loading. 
Since my model has a lot of loops it would validate it indefinitely but by default the validator stops at recursion depth level 32 and throws an exception.
You can increase the number of levels by setting the MaxValidationDepth but it would just work longer yielding the same result.  
It would be nice if we could tell the validator to just stop (without throwing the error) at some level but there is no such option.
In fact all I wanted to validate was just the first level properties of my model without going any deeper.
Getting detached models in the first place would fix the problem but my API would not allow it.
So here is the workaround I'm using now:
public T GetDetachedModel<T>(T model) where T : new()
{
T detachedModel = new T();
foreach (var p in typeof(T).GetProperties())
{
if (!(p.GetAccessors()?[0].IsVirtual ?? false))
{
p.SetValue(detachedModel, p.GetValue(model, null));
}
}
return detachedModel;
}
Lazy loading requires all mapped properties to be declared virtual.
We exploit that fact by creating the new object and member copying non virtual properties.
The "detached" model can be used in place of the original one.

WCF DataContract mismatch

We have this middle tier (WCF) deployed in a IIS. Sometime, DataContact changes property data type. i.e (StudentID)
From:
[DataContact]
public class Student
{
public int StudentID { get; set; }
public string Name { get; set; }
}
To:
[DataContact]
public class Student
{
public string StudentID { get; set; }
public string Name { get; set; }
}
Question: Is there a way to tell the client or send a message (error) to client that the DataContract changed?
WCF support versioning capabilities.
However, when you Modify return value types then An exception will occur if the return value from the service cannot be converted to the expected data type in the client version of the operation signature.
The important distinction to understand is that there are certain changes which are breaking and other non-breaking changes. For e.g. If you add a new method to the WCF Service, then it's a Non-Breaking change, but if you remove the method it's a breaking change for the clients.
For Additional reading, read here at msdn
During the design for WCF Services, it is recommended to Services version tolerant, so that client on different version can work with the Service. Also, you would need to communicate the changes using email/document etc. I do not believe there is out of box support for Managing notifications. It appears to be an administrative work for which you can otherwise do using other communication medium like emails etc.

Azure Mobile Services Identity Column Not Assigned While Offline

I'm using the Azure Mobile Services .NET backend with Xamarin.Forms and I'm having an issue with using int identity ID columns. When in an offline scenario, I can successfully add the record to the DB, but the CustomerId column which is an identity remains at 0. Once online, when I sync, the value is set by SQL server and populated on the mobile device.
As the ID is required as I also need to create related data in another table, the question is, how can I get/set an ID for an entity before it's sync'd with the server? I can't set it manually as it may clash with another client. I am suing an existing SQL database, so would prefer not to have to entirely change the scheme to change the ID to use strings or guid's.
public class Customer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CustomerId { get; set; }
public string Name { get; set; }
....
}
public async Task SaveCustomer(Customer item) {
await CustomerTable.InsertAsync (item);
}
The scenario you are mentioning is exactly why Azure Mobile Apps uses strings for IDs. If you use a string, you can generate a GUID for the ID and use that prior to sync.
The only way to get the Id that is generated by the database is to sync the table.

Send logic over Http

I'm trying to send a class that contains a Function over http.
Can this be accomplished?
Its supposed to work like this:
1) Client contacts Web.API.
2) Web.API returns class with the Function
3) Client executes Function.
Class will look a bit like this :
public class UploadTicket
{
public string url { get; set; }
public List<Tuple<string, string>> Headers { get; set; }
public Func<string> SpecialFunction { get; set; }
}
I need this function to alter the uploadurl by appending an ID every time a package is sent - but only if it's to certain dataproviders, and in other cases uploadurls must be modified in other ways. I need to do it this way, so i can keep the client side code as general as possible.
Sounds a little goofy but yeah you can, on the condition that you send source to the client and not some pre-compiled version (otherwise it'd really be a gaping security hole). Just use the C# runtime compiler. But it implies the client is C#, that's why it sounds goofy.
This is actually a common pattern everybody uses every day. Think of the web browser that hits a web server and gets a page with javascript in it. The same thing happens. The browser compiles the JS and executes it, even though the source was produced remotely.

Azure MobileServiceInvalidOperation Exception has been thrown

I am working with the xamarin.forms app generated when you download the sample for working with Azure Mobile Services. I have made some modifications. Firstly, I have changed Todo, to entry.cs:
public class entry
{
string id;
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("Time")]
public int Time { get; set; }
[JsonProperty("Percentage")]
public int Percentage { get; set; }
//I have omitted Device, Replacement, Use_profile, Longitude, Latitude, Battery
}
I try to add a new line to the table in my SQL database, by calling the following code from my page in cs:
var data = new entry{ Longitude = await GetLongitude(), Latitude = await GetLatitude(), Percentage = bpm }; // initialise new data entry
await AddItem (data);
When this is called, the app crashes.
Here is a gist of the log when the exception is thrown. It gives a Microsoft.WindowsAzure.MobileServices.MobileServiceInvalidOpperationException has been thrown
Explanation:
The resource you are looking for has been removed, had it's name changed, or is temporarily unavailable
This is thrown on the UIApplication.Main (args, null, "AppDelegate"); line in main.cs under the ios project.
Any thoughts on why this is happening would be much appreciated.
UPDATE:
Just to add a little more info, I have a web service setup at http://project.azurewebsites.net this is the address referenced in the constants section of the mobile application I am building in xamarin. However, the SQL database is at http://project-db.database.windows.net how do I get around this? Can I create a database on the original domain, or change the reference in the app?
It looks like you are getting a 404 error when you are calling your Mobile Backend. You need to add a new Table Controller to handle the "entry" class, because your client will be trying to post to https://yourservice.azurewebsites.net/tables/entry, which doesn't exist.
In your server project, you need to add a new class Entry that inherits from EntityData. Then you add this type to your DbContext class and add a table controller. This tutorial for Mobile Services controllers might be helpful. If you're using Mobile Apps, you would use Add -> New Scaffolded Item -> Azure Mobile Apps -> Mobile Apps Table Controller.
Then, deploy your server project so that the new REST endpoint is available and then your client app should be able to connect.
Edited to add: you specify the connect to the SQL Database in the MS_TableConnectionString setting in web.config. Whatever value is the Connection Strings section of the Azure Portal will override this. For more information, see https://azure.microsoft.com/en-us/documentation/articles/web-sites-configure/.

Categories