I have a class like this:
public class Document
{
public int DocumentType{get;set;}
[Required]
public string Name{get;set;}
[Required]
public string Name2{get;set;}
}
Now if I put a [Required] data annotation on the Name and Name2 properties, then everything is ok and if Name or Name2 are empty, validation will throw an error.
But I want Name field only to be required if DocumentType is equal to 1
and Name2 only required if DocumentType is equal to 2 .
public class Document
{
public int DocumentType{get;set;}
[Required(Expression<Func<object, bool>>)]
public string Name{get;set;}
[Required(Expression<Func<object, bool>>)]
public string Name2{get;set;}
}
but I know I can't, it causes an error. What should I do for this requirement?
RequiredIf validation attribute
I've written a RequiredIfAttribute that requires a particular property value when a different property has a certain value (what you require) or when a different property has anything but a specific value.
This is the code that may help:
/// <summary>
/// Provides conditional validation based on related property value.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class RequiredIfAttribute : ValidationAttribute
{
#region Properties
/// <summary>
/// Gets or sets the other property name that will be used during validation.
/// </summary>
/// <value>
/// The other property name.
/// </value>
public string OtherProperty { get; private set; }
/// <summary>
/// Gets or sets the display name of the other property.
/// </summary>
/// <value>
/// The display name of the other property.
/// </value>
public string OtherPropertyDisplayName { get; set; }
/// <summary>
/// Gets or sets the other property value that will be relevant for validation.
/// </summary>
/// <value>
/// The other property value.
/// </value>
public object OtherPropertyValue { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether other property's value should match or differ from provided other property's value (default is <c>false</c>).
/// </summary>
/// <value>
/// <c>true</c> if other property's value validation should be inverted; otherwise, <c>false</c>.
/// </value>
/// <remarks>
/// How this works
/// - true: validated property is required when other property doesn't equal provided value
/// - false: validated property is required when other property matches provided value
/// </remarks>
public bool IsInverted { get; set; }
/// <summary>
/// Gets a value that indicates whether the attribute requires validation context.
/// </summary>
/// <returns><c>true</c> if the attribute requires validation context; otherwise, <c>false</c>.</returns>
public override bool RequiresValidationContext
{
get { return true; }
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="RequiredIfAttribute"/> class.
/// </summary>
/// <param name="otherProperty">The other property.</param>
/// <param name="otherPropertyValue">The other property value.</param>
public RequiredIfAttribute(string otherProperty, object otherPropertyValue)
: base("'{0}' is required because '{1}' has a value {3}'{2}'.")
{
this.OtherProperty = otherProperty;
this.OtherPropertyValue = otherPropertyValue;
this.IsInverted = false;
}
#endregion
/// <summary>
/// Applies formatting to an error message, based on the data field where the error occurred.
/// </summary>
/// <param name="name">The name to include in the formatted message.</param>
/// <returns>
/// An instance of the formatted error message.
/// </returns>
public override string FormatErrorMessage(string name)
{
return string.Format(
CultureInfo.CurrentCulture,
base.ErrorMessageString,
name,
this.OtherPropertyDisplayName ?? this.OtherProperty,
this.OtherPropertyValue,
this.IsInverted ? "other than " : "of ");
}
/// <summary>
/// Validates the specified value with respect to the current validation attribute.
/// </summary>
/// <param name="value">The value to validate.</param>
/// <param name="validationContext">The context information about the validation operation.</param>
/// <returns>
/// An instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult" /> class.
/// </returns>
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (validationContext == null)
{
throw new ArgumentNullException("validationContext");
}
PropertyInfo otherProperty = validationContext.ObjectType.GetProperty(this.OtherProperty);
if (otherProperty == null)
{
return new ValidationResult(
string.Format(CultureInfo.CurrentCulture, "Could not find a property named '{0}'.", this.OtherProperty));
}
object otherValue = otherProperty.GetValue(validationContext.ObjectInstance);
// check if this value is actually required and validate it
if (!this.IsInverted && object.Equals(otherValue, this.OtherPropertyValue) ||
this.IsInverted && !object.Equals(otherValue, this.OtherPropertyValue))
{
if (value == null)
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
// additional check for strings so they're not empty
string val = value as string;
if (val != null && val.Trim().Length == 0)
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
}
Conditionally required property using data annotations
[RequiredIf(dependent Property name, dependent Property value)]
e.g.
[RequiredIf("Country", "Ethiopia")]
public string POBox{get;set;}
// POBox is required in Ethiopia
public string Country{get;set;}
[RequiredIf("destination", "US")]
public string State{get;set;}
// State is required in US
public string destination{get;set;}
public class RequiredIfAttribute : ValidationAttribute
{
RequiredAttribute _innerAttribute = new RequiredAttribute();
public string _dependentProperty { get; set; }
public object _targetValue { get; set; }
public RequiredIfAttribute(string dependentProperty, object targetValue)
{
this._dependentProperty = dependentProperty;
this._targetValue = targetValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var field = validationContext.ObjectType.GetProperty(_dependentProperty);
if (field != null)
{
var dependentValue = field.GetValue(validationContext.ObjectInstance, null);
if ((dependentValue == null && _targetValue == null) || (dependentValue.Equals(_targetValue)))
{
if (!_innerAttribute.IsValid(value))
{
string name = validationContext.DisplayName;
string specificErrorMessage = ErrorMessage;
if (specificErrorMessage.Length < 1)
specificErrorMessage = $"{name} is required.";
return new ValidationResult(specificErrorMessage, new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
else
{
return new ValidationResult(FormatErrorMessage(_dependentProperty));
}
}
}
Out of the box I think this is still not possible.
But I found this promising article about Mvc.ValidationToolkit (also here, unfortunately this is only alpha, but you probably could also just extract the method(s) you need from this code and integrate it on your own), it contains the nice sounding attribute RequiredIf which seems to match exactly your cause:
you download the project from the linked zip and build it
get the built dll from your build folder and reference it in the project you are using
unfortunately this seems to require reference to MVC, too (easiest way to have that is starting an MVC-Project in VS or install-package Microsoft.AspNet.Mvc)
in the files where you want to use it, you add using Mvc.ValidationToolkit;
then you are able to write things like [RequiredIf("DocumentType", 2)] or [RequiredIf("DocumentType", 1)], so objects are valid if neither name or name2 are supplied as long as DocumentType is not equal to 1 or 2
Check out Fluent Validation
https://www.nuget.org/packages/FluentValidation/
Project Description
A small validation library for .NET that uses a fluent interface and lambda expressions for building validation rules for your business objects.
https://github.com/JeremySkinner/FluentValidation
I have always used implemented IValidatableObject from System.ComponentModel.DataAnnotations;
Example below
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (this.SendInAppNotification)
{
if (string.IsNullOrEmpty(this.NotificationTitle) || string.IsNullOrWhiteSpace(this.NotificationTitle))
{
yield return new ValidationResult(
$"Notification Title is required",
new[] { nameof(this.NotificationTitle) });
}
}
check out the ExpressiveAnnotations .net library
Git reference
It has 'RequiredIf' and 'AssertThat' validation attributes
Check out MVC Foolproof validation. It has data annotation in model like RequiredIf (dependent Property, dependent value) if I remember correctly. You can download Foolproof from:
Visual Studio(2017) -> Tools -> Nuget Package Manager -> Manage Nuget Packages for Solution. Reference mvcfoolproof.unobtrusive.min.js in addition to the jquery files.
I solved this by extending the RequiredAttribute class, borrowing some logic from the CompareAttribute and Robert's excellent solution:
/// <summary>
/// Provides conditional <see cref="RequiredAttribute"/>
/// validation based on related property value.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class RequiredIfAttribute : RequiredAttribute
{
/// <summary>
/// Gets or sets a value indicating whether other property's value should
/// match or differ from provided other property's value (default is <c>false</c>).
/// </summary>
public bool IsInverted { get; set; } = false;
/// <summary>
/// Gets or sets the other property name that will be used during validation.
/// </summary>
/// <value>
/// The other property name.
/// </value>
public string OtherProperty { get; private set; }
/// <summary>
/// Gets or sets the other property value that will be relevant for validation.
/// </summary>
/// <value>
/// The other property value.
/// </value>
public object OtherPropertyValue { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="RequiredIfAttribute"/> class.
/// </summary>
/// <param name="otherProperty">The other property.</param>
/// <param name="otherPropertyValue">The other property value.</param>
public RequiredIfAttribute(string otherProperty, object otherPropertyValue)
: base()
{
OtherProperty = otherProperty;
OtherPropertyValue = otherPropertyValue;
}
protected override ValidationResult IsValid(
object value,
ValidationContext validationContext)
{
PropertyInfo otherPropertyInfo = validationContext
.ObjectType.GetProperty(OtherProperty);
if (otherPropertyInfo == null)
{
return new ValidationResult(
string.Format(
CultureInfo.CurrentCulture,
"Could not find a property named {0}.",
validationContext.ObjectType, OtherProperty));
}
// Determine whether to run [Required] validation
object actualOtherPropertyValue = otherPropertyInfo
.GetValue(validationContext.ObjectInstance, null);
if (!IsInverted && Equals(actualOtherPropertyValue, OtherPropertyValue) ||
IsInverted && !Equals(actualOtherPropertyValue, OtherPropertyValue))
{
return base.IsValid(value, validationContext);
}
return default;
}
}
Example usage:
public class Model {
public bool Subscribe { get; set; }
[RequiredIf(nameof(Subscribe), true)]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
}
This way, you get all the standard Required validation features.
N.B.: I am using .NET 5, but I tried to remove language features added in c# 9.0 for wider compatibility.
I wrote a simple custom validation attribute that it's very readable.
using System;
using System.ComponentModel.DataAnnotations;
namespace some.namespace
{
public class RequiredIfAttribute : ValidationAttribute
{
public string PropertyName { get; set; }
public object Value { get; set; }
public RequiredIfAttribute(string propertyName, object value = null, string errorMessage = "")
{
PropertyName = propertyName;
Value = value;
ErrorMessage = errorMessage;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (PropertyName == null || PropertyName.ToString() == "")
{
throw new Exception("RequiredIf: you have to indicate the name of the property to use in the validation");
}
var propertyValue = GetPropertyValue(validationContext);
if (HasPropertyValue(propertyValue) && (value == null || value.ToString() == ""))
{
return new ValidationResult(ErrorMessage);
}
else
{
return ValidationResult.Success;
}
}
private object GetPropertyValue(ValidationContext validationContext)
{
var instance = validationContext.ObjectInstance;
var type = instance.GetType();
return type.GetProperty(PropertyName).GetValue(instance);
}
private bool HasPropertyValue(object propertyValue)
{
if (Value != null)
{
return propertyValue != null && propertyValue.ToString() == Value.ToString();
}
else
{
return propertyValue != null && propertyValue.ToString() != "";
}
}
}
}
You can use it like this
public class Document
{
public int DocumentType{get;set;}
[RequiredIf("DocumentType", "1", ErrorMessage = "The field is required.")]
public string Name{get;set;}
[RequiredIf("DocumentType", "2", ErrorMessage = "The field is required.")]
public string Name2{get;set;}
}
I know this question is from a long time ago but someone asked in the comments section of Robert's answer how to use unobtrusive as part of the solution.
I wanted client side validation as well so I'm sharing my revised code to Robert's original code. It's essentially the same code except it implements IClientModelValidator and has an additional AddValidation method. The client validation still respects the IsInverted property.
Implement IClientModelValidator
public sealed class RequiredIfAttribute : ValidationAttribute, IClientModelValidator
New AddValidation method
public void AddValidation(ClientModelValidationContext context)
{
var viewContext = context.ActionContext as ViewContext;
var modelType = context.ModelMetadata.ContainerType;
var instance = viewContext?.ViewData.Model;
var model = instance?.GetType().Name == modelType.Name
? instance
: instance?.GetType()?.GetProperties().First(x => x.PropertyType.Name == modelType.Name)
.GetValue(instance, null);
object otherValue = modelType.GetProperty(this.OtherProperty)?.GetValue(model, null);
object value = modelType.GetProperty(context.ModelMetadata.Name)?.GetValue(model, null);
string displayName = context.ModelMetadata.DisplayName ?? context.ModelMetadata.Name;
string errorMessage = null;
// check if this value is actually required and validate it
if (!this.IsInverted && object.Equals(otherValue, this.OtherPropertyValue) ||
this.IsInverted && !object.Equals(otherValue, this.OtherPropertyValue))
{
if (value == null)
{
errorMessage = this.FormatErrorMessage(displayName);
}
// additional check for strings so they're not empty
string val = value as string;
if (val != null && val.Trim().Length == 0)
{
errorMessage = this.FormatErrorMessage(displayName);
}
}
if (!string.IsNullOrWhiteSpace(errorMessage))
{
context.Attributes.Add("data-val", "true");
context.Attributes.Add("data-val-required", errorMessage);
}
}
Full Code
/// <summary>
/// Provides conditional validation based on related property value.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class RequiredIfAttribute : ValidationAttribute, IClientModelValidator
{
#region Properties
/// <summary>
/// Gets or sets the other property name that will be used during validation.
/// </summary>
/// <value>
/// The other property name.
/// </value>
public string OtherProperty { get; private set; }
/// <summary>
/// Gets or sets the display name of the other property.
/// </summary>
/// <value>
/// The display name of the other property.
/// </value>
public string OtherPropertyDisplayName { get; set; }
/// <summary>
/// Gets or sets the other property value that will be relevant for validation.
/// </summary>
/// <value>
/// The other property value.
/// </value>
public object OtherPropertyValue { get; private set; }
/// <summary>
/// Gets or sets a value indicating whether other property's value should match or differ from provided other property's value (default is <c>false</c>).
/// </summary>
/// <value>
/// <c>true</c> if other property's value validation should be inverted; otherwise, <c>false</c>.
/// </value>
/// <remarks>
/// How this works
/// - true: validated property is required when other property doesn't equal provided value
/// - false: validated property is required when other property matches provided value
/// </remarks>
public bool IsInverted { get; set; }
/// <summary>
/// Gets a value that indicates whether the attribute requires validation context.
/// </summary>
/// <returns><c>true</c> if the attribute requires validation context; otherwise, <c>false</c>.</returns>
public override bool RequiresValidationContext
{
get { return true; }
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="RequiredIfAttribute"/> class.
/// </summary>
/// <param name="otherProperty">The other property.</param>
/// <param name="otherPropertyValue">The other property value.</param>
public RequiredIfAttribute(string otherProperty, object otherPropertyValue)
: base("'{0}' is required because '{1}' has a value {3}'{2}'.")
{
this.OtherProperty = otherProperty;
this.OtherPropertyValue = otherPropertyValue;
this.IsInverted = false;
}
#endregion
public void AddValidation(ClientModelValidationContext context)
{
var viewContext = context.ActionContext as ViewContext;
var modelType = context.ModelMetadata.ContainerType;
var instance = viewContext?.ViewData.Model;
var model = instance?.GetType().Name == modelType.Name
? instance
: instance?.GetType()?.GetProperties().First(x => x.PropertyType.Name == modelType.Name)
.GetValue(instance, null);
object otherValue = modelType.GetProperty(this.OtherProperty)?.GetValue(model, null);
object value = modelType.GetProperty(context.ModelMetadata.Name)?.GetValue(model, null);
string displayName = context.ModelMetadata.DisplayName ?? context.ModelMetadata.Name;
string errorMessage = null;
// check if this value is actually required and validate it
if (!this.IsInverted && object.Equals(otherValue, this.OtherPropertyValue) ||
this.IsInverted && !object.Equals(otherValue, this.OtherPropertyValue))
{
if (value == null)
{
errorMessage = this.FormatErrorMessage(displayName);
}
// additional check for strings so they're not empty
string val = value as string;
if (val != null && val.Trim().Length == 0)
{
errorMessage = this.FormatErrorMessage(displayName);
}
}
if (!string.IsNullOrWhiteSpace(errorMessage))
{
context.Attributes.Add("data-val", "true");
context.Attributes.Add("data-val-required", errorMessage);
}
}
/// <summary>
/// Applies formatting to an error message, based on the data field where the error occurred.
/// </summary>
/// <param name="name">The name to include in the formatted message.</param>
/// <returns>
/// An instance of the formatted error message.
/// </returns>
public override string FormatErrorMessage(string name)
{
return string.Format(
CultureInfo.CurrentCulture,
base.ErrorMessageString,
name,
this.OtherPropertyDisplayName ?? this.OtherProperty,
this.OtherPropertyValue,
this.IsInverted ? "other than " : "of ");
}
/// <summary>
/// Validates the specified value with respect to the current validation attribute.
/// </summary>
/// <param name="value">The value to validate.</param>
/// <param name="validationContext">The context information about the validation operation.</param>
/// <returns>
/// An instance of the <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult" /> class.
/// </returns>
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (validationContext == null)
{
throw new ArgumentNullException("validationContext");
}
PropertyInfo otherProperty = validationContext.ObjectType.GetProperty(this.OtherProperty);
if (otherProperty == null)
{
return new ValidationResult(
string.Format(CultureInfo.CurrentCulture, "Could not find a property named '{0}'.", this.OtherProperty));
}
object otherValue = otherProperty.GetValue(validationContext.ObjectInstance);
// check if this value is actually required and validate it
if (!this.IsInverted && object.Equals(otherValue, this.OtherPropertyValue) ||
this.IsInverted && !object.Equals(otherValue, this.OtherPropertyValue))
{
if (value == null)
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
// additional check for strings so they're not empty
string val = value as string;
if (val != null && val.Trim().Length == 0)
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
}
return ValidationResult.Success;
}
}
This should just work, provided you have included jquery.js, jquery.validate.js and jquery.validate.unobtrusive.js script files (in that order) to your layout or razor view.
I can't give you exactly what you're asking for, but have you considered something like the following?
public abstract class Document // or interface, whichever is appropriate for you
{
//some non-validted common properties
}
public class ValidatedDocument : Document
{
[Required]
public string Name {get;set;}
}
public class AnotherValidatedDocument : Document
{
[Required]
public string Name {get;set;}
//I would suggest finding a descriptive name for this instead of Name2,
//Name2 doesn't make it clear what it's for
public string Name2 {get;set;}
}
public class NonValidatedDocument : Document
{
public string Name {get;set;}
}
//Etc...
Justification being the int DocumentType variable. You could replace this with using concrete subclass types for each "type" of document you need to deal with. Doing this gives you much better control of your property annotations.
It also appears that only some of your properties are needed in different situations, which could be a sign that your document class is trying to do too much, and supports the suggestion above.
I' using ASP.net Core and swagger, I have created the following method and verbose documentation:
/// <summary>Creates a package with the requested information.</summary>
/// <param name="createPackage">The package information to create.</param>
/// <response code="201" cref="PackageCreatedExample">Created</response>
/// <returns><see cref="PackageCreated"/> package created.</returns>
[HttpPost]
[SwaggerResponse(201, "Package created", typeof(PackageCreated))]
[SwaggerResponse(400, "Validation failure", typeof(ApiErrorResult))]
[SwaggerResponseExample(201, typeof(PackageCreatedExample))]
public async Task<IActionResult> CreatePackage(PackageCreate createPackage)
{
if (!ModelState.IsValid)
{
return BadRequest(new ApiErrorResult(ModelState));
}
var createdPackageInfo = new PackageCreated();
// Created item and location returned.
return CreatedAtAction(nameof(GetPackage), new { createdPackageInfo.Id, Version = "2" }, createdPackageInfo);
}
I am trying to get an example response to appear in swagger but it always defaults the response sample as follows:
As you can see from the code above, I created a "PackageCreatedExample" class that I want to be picked up and used in swagger but it's just being ignored. I tried using comments response code="201" cref="PackageCreatedExample" and wrote the SwaggerResponseExample attribute, but neither get picked up. Here's my example code:
public class PackageCreatedExample : IExamplesProvider<PackageCreated>
{
public PackageCreated GetExamples()
{
return new PackageCreated {
Outcome = "PackageCreated",
Reference = "6178",
ShippingDocumentation = new List<Documentation> {
new Documentation {
Document = "JVBERi0xLjMNCjEgMCBvYmoNCjw8DQovVHlwZSAvQ2F...",
Format = "Pdf",
Type = DocumentationType.TYPE3
}
},
ReturnsDocumentation = new List<Documentation> {
new Documentation {
Document = "YmoNCjw8DQovVHlwZSAvQ2F0YWxvZw0KL1BhZ2VzIDQgMJVBERi0xLjMNCjEgMCBv...",
Format = "doc",
Type = DocumentationType.TYPE4
}
}
};
}
}
What am I doing wrong?
Thanks in advance for any pointers!
According to the author, this method should not be used anymore (link). This section of the official readme describes the way how the descriptions and examples should be handled.
In short, you have to
Remove all the annotations and use the followings instead:
/// <summary>Creates a package with the requested information.</summary>
/// <param name="createPackage">The package information to create.</param>
/// <returns>package created.</returns>
/// <response code="201">Created</response>
/// <response code="400">Validation failure</response>
[HttpPost]
[ProducesResponseType(typeof(PackageCreated), 201)]
[ProducesResponseType(typeof(ApiErrorResult), 400)]
public async Task<IActionResult> CreatePackage(PackageCreate createPackage)
Enable generating XML documentation under Project -> Properties -> Build tab -> Check XML documentation file in the Output section
Configure swagger to use the generated XML file
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1",
new OpenApiInfo
{
Title = "My API - V1",
Version = "v1"
}
);
var filePath = Path.Combine(System.AppContext.BaseDirectory, "MyApi.xml");
c.IncludeXmlComments(filePath);
}
Add example comments to the properties of your input model classes:
PackageCreate.cs
public PackageCreate
{
// Built-in type
/// <summary>
/// Outcome value
/// </summary>
/// <example>PackageCreated</example>
public string Outcome { get; set; }
// Custom class -> comment its properties in Documentation.cs
public Documentation { get; set; }
// Array type -> comment the properties in Documentation.cs
public IList<Documentation> { get; set; }
}
Documentation.cs:
public Documentation
{
/// <summary>
/// Document name
/// </summary>
/// <example>YmoNCjw8DQovVHlwZSAvQ2F0YWxvZw0KL1BhZ2VzIDQgMJVBERi0xLjMNCjEgMCBv</example>
public string Document { get; set; }
/// <summary>
/// Document format
/// </summary>
/// <example>doc</example>
public string Format { get; set; }
}
I'm using Fluent NHibernate. I have an object at runtime with lazy collections/properties that may or may not have been populated. I plan on serializing that object and need all the collections/properties to be populated before I do so. How can I "eager-load" my object at runtime?
If you already have the relationships set in you mappings you do not need to specify how to join in your query, you could simply use Fetch (even deep fetch) to specify the path to be loaded eaderly:
session.QueryOver<MasterEnt>()
.Where(x => x.Id == 2)
.Fetch(x => x.DetailEntList)
.Eager().List();
You can use ICriteria and manipulate the load through NHibernate.ICriteria.SetFetchMode(string, NHibernate.FetchMode).
Example:
DetailEnt.cs:
using System;
using System.Collections.Generic;
using System.Text;
namespace FetchTest
{
public class DetailEnt
{
private Int32? id;
/// <summary>
/// Entity key
/// </summary>
public virtual Int32? Id
{
get { return id; }
set { id = value; }
}
private String description;
/// <summary>
/// Description
/// </summary>
public virtual String Description
{
get { return description; }
set { description = value; }
}
private MasterEnt rIMaster;
/// <summary>
/// Gets or sets the RI master.
/// </summary>
/// <value>
/// The RI master.
/// </value>
public virtual MasterEnt RIMaster
{
get { return rIMaster; }
set { rIMaster = value; }
}
}
}
MasterEnt.cs:
using System;
using System.Collections.Generic;
using System.Text;
namespace FetchTest
{
public class MasterEnt
{
private Int32? id;
/// <summary>
/// Entity key
/// </summary>
public virtual Int32? Id
{
get { return id; }
set { id = value; }
}
private String description;
/// <summary>
/// Description
/// </summary>
public virtual String Description
{
get { return description; }
set { description = value; }
}
private ICollection<DetailEnt> detailEntList;
/// <summary>
/// <see cref="RIDetailEnt"/> one-to-many relationship.
/// </summary>
public virtual ICollection<DetailEnt> DetailEntList
{
get { return detailEntList; }
set { detailEntList = value; }
}
}
}
Forcing eager load at runtime:
NHibernate.ISession ss = GetSessionFromSomeWhere();
NHibernate.ICriteria crt = ss.CreateCriteria<MasterEnt>();
crt
.Add(NHibernate.Criterion.Expression.IdEq(17))
//here is "force eager load at runtime"
.SetFetchMode("DetailEntList", NHibernate.FetchMode.Join);
MasterEnt mEnt = crt.UniqueResult<MasterEnt>();
In this case I used "hbm". But the logic should be the same.
EDITED:
With "NHibernate 2.1.2" and "NHibernate.Linq"
INHibernateQueryable<MasterEnt> nhq = null;
IList<MasterEnt> masterList = null;
nhq = (INHibernateQueryable<MasterEnt>)(
from master in session.Linq<MasterEnt>()
where master.Id == 2
select master);
nhq.Expand("DetailEntList");
masterList = nhq.ToList<MasterEnt>();
with QueryOver<T>Left.JoinQueryOver from NHibernate 3:
IQueryOver<MasterEnt> query = session.QueryOver<MasterEnt>()
.Left.JoinQueryOver<DetailEnt>(m => m.DetailEntList)
.Where(m => m.Id == 2);
masterList = query.List<MasterEnt>();
These queries work this way independently if using "FluentNHibernate" or "hbm".
I made some code for it, soon I'll post the links to the files.
EDITED 2:
I've posted the code on q_10303345_1350308.7z (runnable by NUnit). There are explanations about the dependencies in the "dependencies \ readme.txt". The dll dependencies are loaded by NuGet.
I'm pulling feeds for my RSS project and I am running into a problem of not knowing how to allow the user to load more items into the collection. At the current moment, everything loads at once. While this is in some cases all right, I would like the user to be able to choose how things get loaded in case they have a slow mobile connection.
This is borrowed code and thus it only adds to my confusion.
Where could i be able to inject code into this sample to allow a dynamic loading of items, say, 30 at a time?
Rss Class:
namespace MyRSSService
{
public class RssService
{
/// Gets the RSS items.
/// <param name="rssFeed">The RSS feed.</param>
/// <param name="onGetRssItemsCompleted">The on get RSS items completed.</param>
/// <param name="onError">The on error.</param>
public static void GetRssItems(string rssFeed, Action<IList<RssItem>> onGetRssItemsCompleted = null, Action<Exception> onError = null, Action onFinally = null)
{
WebClient webClient = new WebClient();
// register on download complete event
webClient.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)
{
try
{
// report error
if (e.Error != null)
{
if (onError != null)
{
onError(e.Error);
}
return;
}
// convert rss result to model
IList<RssItem> rssItems = new List<RssItem>();
Stream stream = e.Result;
XmlReader response = XmlReader.Create(stream);
{
SyndicationFeed feeds = SyndicationFeed.Load(response);
foreach (SyndicationItem f in feeds.Items)
{
RssItem rssItem = new RssItem(f.Title.Text, f.Summary.Text, f.PublishDate.ToString(), f.Links[0].Uri.AbsoluteUri);
rssItems.Add(rssItem);
}
}
// notify completed callback
if (onGetRssItemsCompleted != null)
{
onGetRssItemsCompleted(rssItems);
}
}
finally
{
// notify finally callback
if (onFinally != null)
{
onFinally();
}
}
};
webClient.OpenReadAsync(new Uri(rssFeed));
}
}
}
items setting class:
namespace MyRSSService
{
public class RssItem
{
/// <summary>
/// Initializes a new instance of the <see cref="RssItem"/> class.
/// </summary>
/// <param name="title">The title.</param>
/// <param name="summary">The summary.</param>
/// <param name="publishedDate">The published date.</param>
/// <param name="url">The URL.</param>
public RssItem(string title, string summary, string publishedDate, string url)
{
Title = title;
Summary = summary;
PublishedDate = publishedDate;
Url = url;
// Get plain text from html
PlainSummary = HttpUtility.HtmlDecode(Regex.Replace(summary, "<[^>]+?>", ""));
}
public string Title { get; set; }
public string Summary { get; set; }
public string PublishedDate { get; set; }
public string Url { get; set; }
public string PlainSummary { get; set; }
}
}
the binding C# to the page to display the feeds
public partial class FeedPage : PhoneApplicationPage
{
private const string WindowsPhoneBlogPosts = "http://feeds.bbci.co.uk/news/rss.xml";
public FeedPage()
{
InitializeComponent();
RssService.GetRssItems(WindowsPhoneBlogPosts, (items) => { listbox.ItemsSource = items; }, (exception) => { MessageBox.Show(exception.Message); }, null);
}
}
Unless the server where the feed is hosted provides an API to limit the number of returned items (for example, this practice is used for the Xbox Marketplace), you will be downloading the entire feed, even if you decide to only show a part of it.
I am a newbie to C#. I have a java REST service which returns a xml response and I am trying to deserialize the xml document using C# XmlSerializer. A sample xml document response is pasted below.
<?xml version="1.0" encoding="UTF-8"
standalone="yes" ?> <ns2:Document
xmlns:ns2="http://hxps.honeywell.com/model/impl"
xmlns:ns3="http://hxps.honeywell.com/datatypes/impl"
type="PS">
<docId>SamplePSDocument1</docId>
<fields
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ns5="http://jaxb.dev.java.net/array"
xsi:type="ns5:anyTypeArray"> <item
xsi:type="ns3:scalarFieldImpl"
key="Name">
<value xmlns:xs="http://www.w3.org/2001/XMLSchema"
xsi:type="xs:string">HXPS A4</value>
</item> <item
xsi:type="ns3:scalarFieldImpl"
key="Creation Date">
<value xmlns:xs="http://www.w3.org/2001/XMLSchema"
xsi:type="xs:string">20 April
2007</value> </item> </fields>
<id>fb92f871-1f3d-4fa4-ba24-5ae3af0a493f</id>
<revision>1-c75f688e212fb5341ebdbd22a3867c14</revision>
- <version> <majorVersionNumber>1</majorVersionNumber>
<minorVerisonNumber>5</minorVerisonNumber>
</version> </ns2:document>
It works fine when I deserialize this xml document into Document object. My document class is pasted below
[System.SerializableAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://hxps.honeywell.com/model/impl", TypeName = "PSDocument")]
[System.Xml.Serialization.SoapTypeAttribute(Namespace = "http://hxps.honeywell.com/model/impl", TypeName = "PSDocument")]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "http://hxps.honeywell.com/model/impl", ElementName = "Document")]
public partial class PSDocument
{
private Com.Honeywell.Hxps.Sdk.Model.DocumentType _type;
private string _description;
private string _displayName;
private string _docId;
private Com.Honeywell.Hxps.Sdk.Model.Impl.VersionImpl _version;
private object _fields;
private string _revision;
private string _id;
/// <summary>
/// (no documentation provided)
/// </summary>
[System.Xml.Serialization.XmlAttributeAttribute(AttributeName = "type")]
[System.Xml.Serialization.SoapAttributeAttribute(AttributeName = "type")]
public Com.Honeywell.Hxps.Sdk.Model.DocumentType Type
{
get
{
return this._type;
}
set
{
this._type = value;
}
}
/// <summary>
/// Property for the XML serializer indicating whether the "Type" property should be included in the output.
/// </summary>
[System.Xml.Serialization.XmlIgnoreAttribute]
[System.Xml.Serialization.SoapIgnoreAttribute]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public bool TypeSpecified
{
get
{
return this._type != Com.Honeywell.Hxps.Sdk.Model.DocumentType.NULL;
}
set
{
if (!value)
{
this._type = Com.Honeywell.Hxps.Sdk.Model.DocumentType.NULL;
}
}
}
/// <summary>
/// (no documentation provided)
/// </summary>
[System.Xml.Serialization.XmlElementAttribute(ElementName = "description", Namespace = "")]
[System.Xml.Serialization.SoapElementAttribute(ElementName = "description")]
public string Description
{
get
{
return this._description;
}
set
{
this._description = value;
}
}
/// <summary>
/// (no documentation provided)
/// </summary>
[System.Xml.Serialization.XmlElementAttribute(ElementName = "displayName", Namespace = "")]
[System.Xml.Serialization.SoapElementAttribute(ElementName = "displayName")]
public string DisplayName
{
get
{
return this._displayName;
}
set
{
this._displayName = value;
}
}
/// <summary>
/// (no documentation provided)
/// </summary>
[System.Xml.Serialization.XmlElementAttribute(ElementName = "docId", Namespace = "")]
[System.Xml.Serialization.SoapElementAttribute(ElementName = "docId")]
public string DocId
{
get
{
return this._docId;
}
set
{
this._docId = value;
}
}
/// <summary>
/// (no documentation provided)
/// </summary>
[System.Xml.Serialization.XmlElementAttribute(ElementName = "version", Namespace = "")]
[System.Xml.Serialization.SoapElementAttribute(ElementName = "version")]
public Com.Honeywell.Hxps.Sdk.Model.Impl.VersionImpl Version
{
get
{
return this._version;
}
set
{
this._version = value;
}
}
/// <summary>
/// (no documentation provided)
/// </summary>
[System.Xml.Serialization.XmlElementAttribute(ElementName = "fields", Namespace = "")]
[System.Xml.Serialization.SoapElementAttribute(ElementName = "fields")]
public object Fields
{
get
{
return this._fields;
}
set
{
this._fields = value;
}
}
/// <summary>
/// (no documentation provided)
/// </summary>
[System.Xml.Serialization.XmlElementAttribute(ElementName = "revision", Namespace = "")]
[System.Xml.Serialization.SoapElementAttribute(ElementName = "revision")]
public string Revision
{
get
{
return this._revision;
}
set
{
this._revision = value;
}
}
/// <summary>
/// (no documentation provided)
/// </summary>
[System.Xml.Serialization.XmlElementAttribute(ElementName = "id", Namespace = "")]
[System.Xml.Serialization.SoapElementAttribute(ElementName = "id")]
public string Id
{
get
{
return this._id;
}
set
{
this._id = value;
}
}
}
}
In my main program, I get an array of xmlNodes when I try
Array fields = (Array)doc.Fields;
In the server side java REST service implementation, fields is actually a arraylist which will contain instances of three implementations of an interface. (List may contain ScalarFieldImpl or ArrayFieldImpl which are custom business objects).
I want to deserialize this xml fields into ScalarFieldImpl or ArrayFieldImpl using XmlSerializer. I want to know whether it is possible? If so, how do I do that?
As far as I know this isn't possible with the ootb xml (de-)serializer, I think you'll have to write your own XmlSerializer. Or try to use LINQ to XML.
I got this working. I did few changes in my PSDocument class.
private object _fields; -> private ArrayList _fields;
Also I changed get/set method and added new metadata
[System.Xml.Serialization.XmlArray(ElementName = "fields", Namespace = "")]
[System.Xml.Serialization.XmlArrayItem(ElementName="item")]
public ArrayList Fields
{
get
{
return this._fields;
}
set
{
this._fields = value;
}
}
Previously I had the following lines in my PSDocument class
[System.Xml.Serialization.XmlElementAttribute(ElementName = "fields", Namespace = "")]
[System.Xml.Serialization.SoapElementAttribute(ElementName = "fields")]
public object Fields
{
get
{
return this._fields;
}
set
{
this._fields = value;
}
}
So while deserializing fields in PSDocument, I get an arraylist with items as elements.
Hope this helps someone.