Powershell WCF service DateTime property always DateTime.Min (01.01.0001) - wcf

i've detected a strange behavior calling a WCF Service from a Powershell script. Using the command 'New-WebServiceProxy' from Powershell 2.0 get's you the abillity to send requests to a Webservice from a PS script. But i got some problems with System.DateTime objects on the service side, the value on the server side is always DateTime.Min.
So i created a small test service an script and i can reproduce this error. I used a 'standard' WCF-Project from VS2010 and extedended the 'DataContract' Class with a DateTime Property:
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
[DataMember]
public DateTime Datum { get; set; }
}
Powershell script to call the service:
cls
$serv = New-WebServiceProxy -uri 'http://localhost:50176/TestService.svc?wsdl' - Namespace wt
$data = [wt.CompositeType](New-Object wt.CompositeType)
$data.StringValue = "abcd"
$data.BoolValue = $true
$data.Datum = Get-Date
$serv.GetDataUsingDataContract($data)
If needed, i can send you a dropbox link for the zipped project.
Regards Uwe

I've never used powershell before but thought I'd take a long overdue look at it for this question!
The proxy object $data can have a date property set but, despite what your code looks like its doing, $data isn't the real object, just an XML proxy of it.
If you enter command "$data" you'll see what looks like an XmlSerialized version of the object (has xxSpecified properties for the bool and DateTime). It does reflect changes made by e.g. "$data.Datum = Get-Date".
The proxy is deserialised back to an instance of MyCompositeType when you call GetUsingDataContract (as its passed as a parameter and sent using XML) which you can see by putting breakpoints on the property get/setters prior to calling it.
As part of this deserialization, only the StringValue makes it which is because the Xml serialization for the other properties will only include values where "xxxSpecified" is true.
If you set the "xxxSpecified" properties in the proxy they will serialize back correctly.
But the best fix is to change their DataMember attribute to:
[DataMember(IsRequired=true)]
Which should just work with the code you've got.

Related

Save complex object to session ASP .NET CORE 2.0

I am quite new to ASP .NET core, so please help. I would like to avoid database round trip for ASP .NET core application. I have functionality to dynamically add columns in datagrid. Columns settings (visibility, enable, width, caption) are stored in DB.
So I would like to store List<,PersonColumns> on server only for actual session. But I am not able to do this. I already use JsonConvert methods to serialize and deserialize objects to/from session. This works for List<,Int32> or objects with simple properties, but not for complex object with nested properties.
My object I want to store to session looks like this:
[Serializable]
public class PersonColumns
{
public Int64 PersonId { get; set; }
List<ViewPersonColumns> PersonCols { get; set; }
public PersonColumns(Int64 personId)
{
this.PersonId = personId;
}
public void LoadPersonColumns(dbContext dbContext)
{
LoadPersonColumns(dbContext, null);
}
public void LoadPersonColumns(dbContext dbContext, string code)
{
PersonCols = ViewPersonColumns.GetPersonColumns(dbContext, code, PersonId);
}
public static List<ViewPersonColumns> GetFormViewColumns(SatisDbContext dbContext, string code, Int64 formId, string viewName, Int64 personId)
{
var columns = ViewPersonColumns.GetPersonColumns(dbContext, code, personId);
return columns.Where(p => p.FormId == formId && p.ObjectName == viewName).ToList();
}
}
I would like to ask also if my approach is not bad to save the list of 600 records to session? Is it better to access DB and load columns each time user wants to display the grid?
Any advice appreciated
Thanks
EDIT: I have tested to store in session List<,ViewPersonColumns> and it is correctly saved. When I save object where the List<,ViewPersonColumns> is property, then only built-in types are saved, List property is null.
The object I want to save in session
[Serializable]
public class UserManagement
{
public String PersonUserName { get; set; }
public Int64 PersonId { get; set; }
public List<ViewPersonColumns> PersonColumns { get; set; } //not saved to session??
public UserManagement() { }
public UserManagement(DbContext dbContext, string userName)
{
var person = dbContext.Person.Single(p => p.UserName == userName);
PersonUserName = person.UserName;
PersonId = person.Id;
}
/*public void PrepareUserData(DbContext dbContext)
{
LoadPersonColumns(dbContext);
}*/
public void LoadPersonColumns(DbContext dbContext)
{
LoadPersonColumns(dbContext, null);
}
public void LoadPersonColumns(DbContext dbContext, string code)
{
PersonColumns = ViewPersonColumns.GetPersonColumns(dbContext, code, PersonId);
}
public List<ViewPersonColumns> GetFormViewColumns(Int64 formId, string viewName)
{
if (PersonColumns == null)
return null;
return PersonColumns.Where(p => p.FormId == formId && p.ObjectName == viewName).ToList();
}
}
Save columns to the session
UserManagement userManagement = new UserManagement(_context, user.UserName);
userManagement.LoadPersonColumns(_context);
HttpContext.Session.SetObject("ActualPersonContext", userManagement);
HttpContext.Session.SetObject("ActualPersonColumns", userManagement.PersonColumns);
Load columns from the session
//userManagement build-in types are set. The PersonColumns is null - not correct
UserManagement userManagement = session.GetObject<UserManagement>("ActualPersonContext");
//The cols is filled from session with 600 records - correct
List<ViewPersonColumns> cols = session.GetObject<List<ViewPersonColumns>>("ActualPersonColumns");
Use list for each column is better than use database.
you can't create and store sessions in .net core like .net framework 4.0
Try Like this
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
//services.AddDbContext<GeneralDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().AddSessionStateTempDataProvider();
services.AddSession();
}
Common/SessionExtensions.cs
sing Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace IMAPApplication.Common
{
public static class SessionExtensions
{
public static T GetComplexData<T>(this ISession session, string key)
{
var data = session.GetString(key);
if (data == null)
{
return default(T);
}
return JsonConvert.DeserializeObject<T>(data);
}
public static void SetComplexData(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
}
}
Usage
==> Create Session*
public IActionResult Login([FromBody]LoginViewModel model)
{
LoggedUserVM user = GetUserDataById(model.userId);
//Create Session with complex object
HttpContext.Session.SetComplexData("loggerUser", user);
return Json(new { status = result.Status, message = result.Message });
}
==> Get Session data*
public IActionResult Index()
{
//Get Session data
LoggedUserVM loggedUser = HttpContext.Session.GetComplexData<LoggedUserVM>("loggerUser");
}
Hope this is helpful. Good luck.
This is an evergreen post, and even though Microsoft has recommended serialisation to store the object in session - it is not a correct solution unless your object is readonly, I have a blog explaining all scenario here and i have even pointed out the issues in GitHub of Asp.Net Core in issue id 18159
Synopsis of the problems are here:
A. Serialisation isn't same as object, true it will help in distributed server scenario but it comes with a caveat that Microsoft have failed to highlight - that it will work without any unpredictable failures only when the object is meant to be read and not to be written back.
B. If you were looking for a read-write object in the session, everytime you change the object that is read from the session after deserialisation - it needs to be written back to the session again by calling serialisation - and this alone can lead to multiple complexities as you will need to either keep track of the changes - or keep writing back to session after each change in any property. In one request to the server, you will have scenarios where the object is written back multiple times till the response is sent back.
C. For a read-write object in the session, even on a single server it will fail, as the actions of the user can trigger multiple rapid requests to the server and not more than often system will find itself in a situation where the object is being serialised or deserialised by one thread and being edited and then written back by another, the result is you will end up with overwriting the object state by threads - and even locks won't help you much since the object is not a real object but a temporary object created by deserialisation.
D. There are issues with serialising complex objects - it is not just a performance hit, it may even fail in certain scenario - especially if you have deeply nested objects that sometimes refer back to itself.
The synopsis of the solution is here, full implementation along with code is in the blog link:
First implement this as a Cache object, create one item in IMemoryCache for each unique session.
Keep the cache in sliding expiration mode, so that each time it is read it revives the expiry time - thereby keeping the objects in cache as long as the session is active.
Second point alone is not enough, you will need to implement heartbeat technique - triggering the call to session every T minus 1 min or so from the javascript. (This we anyways used to do even to keep the session alive till the user is working on the browser, so it won't be any different
Additional Recommendations
A. Make an object called SessionManager - so that all your code related to session read / write sits in one place.
B. Do not keep very high value for session time out - If you are implementing heartbeat technique, even 3 mins of session time out will be enough.

Service Reference fails to deserialize correctly and puts null in fields (asp.net to asp.net)

So i'm having a weird issue with my service reference in my VS2010 project that i can't really figure out.
Any time i rebuild the soap service that the service reference is attached to i can no longer deserialize the data from one of the methods. All of the other methods work but one in particular just gets filled with null/default values instead of the correct values. I can confirm that the web service is still returning good data and looks to be in the correct format. Once i update the service reference it all works again until i rebuild.
When i go and look at the diff of the structure i see that the following files are now different:
Configuration.svcinfo
Configuration91.svcinfo
Reference.cs
Reference.svcmap
MyService.disco
MyService.wsdl
When i look in the wsdl it looks almost like the fields were re-ordered. But i don't see how that is possible.
Here is the header information for my web service
[WebService(Namespace = http://myservice/)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[Policy("ServerPolicy")]
Anyone know why this is happening with each rebuild?
EDIT: Here is an example.
For example here is a random change that was made, this class was not changed but only recompiled:
Before:
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=0)]
public string Userid {
get {
return this.useridField;
}
set {
this.useridField = value;
this.RaisePropertyChanged("Userid");
}
}
After:
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=2)]
public string Userid {
get {
return this.useridField;
}
set {
this.useridField = value;
this.RaisePropertyChanged("Userid");
}
}

PowerShell and Webservice - Add header

I used the PowerShell New-WebServiceProxy commandlet to get a connection with a WebService(WCF/SOAP). It´s possible to connect to the WebService but when I want to execute a methode I´m getting a access denied. The access denied is because the WebService needs a custom message header. But this is not possible with New-WebServiceProxy.
Question: What is the easiest way to connect/use the WebService and add the message header? Is there a PowerShell example script?
(My prefered language is PowerShell in that case)
BTW: Yes I know that there is a Question very similar to my: Add custom SOAP header in PowerShell using New-WebServiceProxy
Thank you in advance!
This is more of a workaround, but maybe it works for you. Instead of using the cmdlet, create a C# oder VB.NET Project, add the WCF service reference as it is intended to be used. Then create a class that has a method for every service method you want to call and exposes the arguments you need to use in PowerShell.
class MyProxy
{
public string Url { get; set; }
public string SomeParameterForTheHeader { get; set; }
public string CallSomeMethod(string input1, string input2)
{
// create WCF context using this.Url
// create MessageHeader using this.SomeParameterForTheHeader and add it to the context
// call SomeMethod on the context using input1 and input2
}
}
Compile it and use the assembly and class in your PowerShell script.
[System.Reflection.Assembly]::LoadWithPartialName("MyAssembly") > $null
$ref = New-Object MyNamespace.MyProxy()
$ref.Url = "http://..."
$ref.SomeParameterForTheHeader = "your value here"
$ref.CallSomeMethod("input1", "input2")

wcf and Validation Application Block unit testing

I'm trying to test validation that I've setup for my wcf service. What's the best way to do it?
[ServiceContract]
[ValidationBehavior]
public interface IXmlSchemaService
{
[OperationContract(Action = "SubmitSchema")]
[return: MessageParameter(Name = "SubmitSchemaReturn")]
[FaultContract(typeof(ValidationFault))]
JobData SubmitSchema([XmlStringValidator] string xmlString);
}
XmlStringValidator is a custom validator I've created. Ideally I want something like:
XmlSchemaService service = new XmlSchemaService();
service.SubmitSchema();
But in this case, validation isn't called.
By definition, this sort of test is an integration test, not a unit test. The VAB validation will only take place if the service operation is invoked via the WCF pipeline.
While you could perhaps force your calls through the WCF pipeline without creating a client proxy, wouldn't it make more sense to test this from a client proxy in order to ensure that the client is seeing exactly the fault you wish to publish from your service when the validation fails?
You can test out the validation in isolation. While it is not feasible to have validation invoked when running the service code directly, the Validation Application Block has two methods for testing your code (that I am aware of).
Using the ValidatorFactory to create a validator for your input type and Assert that the validation results contain the expected errors.
Instantiating the Validator directly and testing it with various input.
In practice I end up using a combination of the two techniques. I use method one to test for validation errors on complex input types. As an example:
[DataContract]
public class Product
{
[DataMember, NotNullValidator]
public string Name { get; set; }
[DataMember, RangeValidator(0.0, RangeBoundaryType.Exclusive,
double.MaxValue, RangeBoundaryType.Ignore,
ErrorMessage = "The value cannot be less than 0.")]
public double Price { get; set; }
}
[TestMethod]
public void InvalidProduct_ReturnsValidationErrors()
{
Product request = new Product()
{
Price = -10.0
};
var validatorFactory = EnterpriseLibraryContainer.Current
.GetInstance<ValidatorFactory>();
var validator = validatorFactory.CreateValidator<Product>();
var results = validator.Validate(request);
Assert.IsTrue(results.Any(vr => vr.Key == "Name"
&& vr.Message == "The value cannot be null."));
Assert.IsTrue(results.Any(vr => vr.Key == "Price"
&& vr.Message == "The value cannot be less than 0."));
}
For method 2 I would have tests that cover my use case scenarios for Validators I've created. As another example:
[TestMethod]
public void XmlStringValidator_ReturnsErrors_OnInvalidInput()
{
var validator = new XmlStringValidator();
var results = validator.Validate("Your input goes here");
Assert.IsTrue(results.Any(vr => vr.Key == "[KeyNameInValidator]" &&
vr.Message == "[Expected error message based on input]"));
}
Method 2 will allow you to create as many test scenarios as you would like for your XmlStringValidator.
You can find more information about these methods in this article: Chapter 6 - Banishing Validation Complication

Can I stop my WCF generating ArrayOfString instead of string[] or List<string>

I am having a minor problem with WCF service proxies where the message contains List<string> as a parameter.
I am using the 'Add Service reference' in Visual Studio to generate a reference to my service.
// portion of my web service message
public List<SubscribeInfo> Subscribe { get; set; }
public List<string> Unsubscribe { get; set; }
These are the generated properties on my MsgIn for one of my web methods.
You can see it used ArrayOfString when I am using List<string>, and the other takes List<SubscribeInfo> - which matches my original C# object above.
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false)]
public System.Collections.Generic.List<DataAccess.MailingListWSReference.SubscribeInfo> Subscribe {
get {
return this.SubscribeField;
}
set {
if ((object.ReferenceEquals(this.SubscribeField, value) != true)) {
this.SubscribeField = value;
this.RaisePropertyChanged("Subscribe");
}
}
}
[System.Runtime.Serialization.DataMemberAttribute(EmitDefaultValue=false)]
publicDataAccess.MailingListWSReference.ArrayOfString Unsubscribe {
get {
return this.UnsubscribeField;
}
set {
if ((object.ReferenceEquals(this.UnsubscribeField, value) != true)) {
this.UnsubscribeField = value;
this.RaisePropertyChanged("Unsubscribe");
}
}
}
The ArrayOfString class generated looks like this. This is a class generated in my code - its not a .NET class. It actually generated me a class that inherits from List, but didn't have the 'decency' to create me any constructors.
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "3.0.0.0")]
[System.Runtime.Serialization.CollectionDataContractAttribute(Name="ArrayOfString", Namespace="http://www.example.com/", ItemName="string")]
[System.SerializableAttribute()]
public class ArrayOfString : System.Collections.Generic.List<string> {
}
The problem is that I often create my message like this :
client.UpdateMailingList(new UpdateMailingListMsgIn()
{
Email = model.Email,
Name = model.Name,
Source = Request.Url.ToString(),
Subscribe = subscribeTo.ToList(),
Unsubscribe = unsubscribeFrom.ToList()
});
I really like the clean look this gives me.
Now for the actual problem :
I cant assign a List<string> to the Unsubscribe property which is an ArrayOfString - even though it inherits from List. In fact I cant seem to find ANY way to assign it without extra statements.
I've tried the following :
new ArrayOfString(unsubscribeFrom.ToList()) - this constructor doesn't exist :-(
changing the type of the array used by the code generator - doesn't work - it always gives me ArrayOfString (!?)
try to cast List<string> to ArrayOfString - fails with 'unable to cast', even though it compiles just fine
create new ArrayOfString() and then AddRange(unsubscribeFrom.ToList()) - works, but I cant do it all in one statement
create a conversion function ToArrayOfString(List<string>), which works but isn't as clean as I want.
Its only doing this for string, which is annoying.
Am i missing something? Is there a way to tell it not to generate ArrayOfString - or some other trick to assign it ?
Any .NET object that implements a method named "Add" can be initialized just like arrays or dictionaries.
As ArrayOfString does implement an "Add" method, you can initialize it like this:
var a = new ArrayOfString { "string one", "string two" };
But, if you really want to initialize it based on another collection, you can write a extension method for that:
public static class U
{
public static T To<T>(this IEnumerable<string> strings)
where T : IList<string>, new()
{
var newList = new T();
foreach (var s in strings)
newList.Add(s);
return newList;
}
}
Usage:
client.UpdateMailingList(new UpdateMailingListMsgIn()
{
Email = model.Email,
Name = model.Name,
Source = Request.Url.ToString(),
Subscribe = subscribeTo.ToList(),
Unsubscribe = unsubscribeFrom.To<ArrayOfString>()
});
I prefer not to return generic types across a service boundary in the first place. Instead return Unsubscribe as a string[], and SubscriptionInfo as SubscriptionInfo[]. If necessary, an array can easily be converted to a generic list on the client, as follows:
Unsubscribe = new List<string>(unsubscribeFrom);
Subscribe = new List<SubscriptionInfo>(subscribeTo);
Too late but can help people in the future...
Use the svcutil and explicitly inform the command line util that you want the proxy class to be serialized by the XmlSerializer and not the DataContractSerializer (default). Here's the sample:
svcutil /out:c:\Path\Proxy.cs /config:c:\Path\Proxy.config /async /serializer:XmlSerializer /namespace:*,YourNamespace http://www.domain.com/service/serviceURL.asmx
Note that the web service is an ASP.NET web service ok?!
If you are using VS 2008 to consume service then there is an easy solution.
Click on the "Advanced..." button on the proxy dialog that is displayed when you add a Service Reference. In the Collection Type drop down you can select System.Generic.List. The methods returning List should now work properly.
(Hope this is what you were asking for, I'm a little tired and the question was a tad difficult for me to read.)