Why Can't I See Classes in .net 2010 Web Service? - web-services

In .net 2010 I have a fairly simple class with 1 function I need to expose through a web service. It uses several basic custom classes which the consumer would, in theory, populate with data and send back to me. The problem is, after I create a WebService and then try to consume the service, it only sees the function and the two top level classes that are mentioned in the function. None of the classes that make properties of the top level classes are available.
I've done this in vs 2005 and the proxy would generate a reference.vb file that would spell out that classes used. But I don't see that file in 2010.
Here is an example. Below the main class Application is availble to the proxy, but none of its property classes are.
<Serializable()> _
Public Class Income
Public Property monthly() As Integer
Public Property wages() As Integer
Public Property taxableInterest() As Integer
Public Property taxExemptInterest() As Integer
Public Property taxableRefunds() As Integer
Public Property alimony() As Integer
Public Property capitalGains() As Integer
Public Property pensions() As Integer
Public Property farmIncome() As Integer
Public Property unemployment() As Integer
Public Property other() As Integer
Public Property MAGIDeductions() As Integer
End Class
<Serializable()> _
Public Class Applicant
Public Sub New()
_relationships = New ArrayList
_income = New Income
End Sub
Public Property isApplicant() As String
Public Property disabled() As String
Public Property student() As String
Public Property eligible() As String
Public Property incarcerated() As String
Public Property livesInState() As String
Public Property claimedByNonApplicant() As String
Public Property longTermCare() As String
Public Property hasInsurance() As String
Public Property stateEmployeeHealthBenefits() As String
Public Property priorInsuranceIndicator() As String
Public Property pregnant() As String
Public Property pregnantThreeMonths() As String
Public Property formerlyFosterCare() As String
Public Property incomeTaxesRequired() As String
Public Property citizen() As String
Public Property id() As String
Public Property age() As Int32
Public Property hours() As Int32
Public Property temporarilyOutOfState As String
Public Property noFixedAddress As String
Public Property claimerIsOutOfState As String
Public Property endDate As String
Public Property numberOfChildrenExpected As String
Public Property hadMedicaid As String
Public Property ageLeftFosterCare As String
Public Property state As String
Public Property legalPermanentResident As String
Public Property lawful As String
Public Property fiveYearBar As String
Public Property fortyQuarters As String
Public Property fiveYearBarMet As String
Public Property refugeeMedicalAssistanceEligible As String
Public Property humanTraffickingVictim As String
Public Property startDate As String
Public Property qualified As String
Public Property deportWithheldDate As String
Public Property entryDate As String
Public Property statusGrantDate As String
Public Property income() As Income
Public Property relationships() As ArrayList
End Class
<Serializable()> _
Public Class Resident
Public Property id() As String
End Class
<Serializable()> _
Public Class Household
Public Sub New()
_People = New ArrayList
End Sub
Public Property HouseholdID() As String
Public Property People() As ArrayList
End Class
<Serializable()> _
Public Class Filer
Public Property id() As String
End Class
<Serializable()> _
Public Class taxReturn
Public Sub New()
_Filers = New ArrayList
_Dependents = New ArrayList
End Sub
Private _Filers As ArrayList
Private _Dependents As ArrayList
Public Property Filers() As ArrayList
Get
Return _Filers
End Get
Set(value As ArrayList)
_Filers = value
End Set
End Property
Public Property Dependents() As ArrayList
Get
Return _Dependents
End Get
Set(value As ArrayList)
_Dependents = value
End Set
End Property
End Class
<Serializable()> _
Public Class Application
Public Sub New()
_People = New ArrayList
_PhysicalHouseholds = New ArrayList
_TaxReturns = New ArrayList
End Sub
Private _applicationID As String = "TEST
Public Property State() As String
Public Property Name() As String
Get
Return _applicationID
End Get
Set(value As String)
_applicationID = value
End Set
End Property
Public Property People() As ArrayList
Public Property PhysicalHouseholds() As ArrayList
Public Property TaxReturns() As ArrayList
End Class

Related

AutoMapper's AssertConfigurationIsValid and EF navigation properties

I discovered AutoMapper's Configuration Validation feature today and it looks very promising. Using it I should be able to get rid of all our manually written unit tests for our AutoMapper profiles. We use AutoMapper to map between Entity Framework entity classes and View Model classes.
Imagine I have the following entity:
public class Article
{
public int Id { get; set; }
public string Name { get; set; }
public int TypeId { get; set; }
[ForeignKey("TypeId")]
[InverseProperty("Article")]
public ArticleType Type { get; set; }
}
And the corresponding View Model:
public class ArticleViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public int TypeId { get; set; }
public string TypeName { get; set; }
}
I have left out ArticleType for brevity.
Now, in my AutoMapper profile I would have these mappings:
CreateMap<ArticleViewModel, Article>()
CreateMap<Article, ArticleViewModel>()
.ForMember(dest => dest.TypeName, options => options.MapFrom(src => src.Type.Name))
If I call AssertConfigurationIsValid on a MapperConfiguration with this profile in it AutoMapper will complain that Type is not mapped. That is true, but I do not need to map it since Entity Framework will automatically figure it out from the foreign key TypeId.
I know I can add an Ignore for Type, like below, to get rid of this error:
CreateMap<ArticleViewModel, Article>()
.ForMember(dest => dest.Type, options => options.Ignore())
But we have entities with a lot of navigation properties to other entities and having to ignore them all becomes tedious.
The other alternative I came up with is to use the source's members to validate the mapping, like this:
CreateMap<ArticleViewModel, Article>(MemberList.Source)
Is there a best practice for this?

Spring boot application-test.properties not initializes inside the tested component

I'm writing a test for a component that takes values from the application.properties.
In the test itself the values are picked up correctly from the application-test.properies.
I used #TestPropertySource(locations = "classpath:application-test.properties")
However in the tested class the values are NOT getting picked up and are null.
The test:
#RunWith(SpringJUnit4ClassRunner.class)
#TestPropertySource(locations = "classpath:application-test.properties")
public class ArtifactAssociationHandlerTest {
private InputStream inputStreamMock;
private ArtifactEntity artifactMock;
private ArtifactDeliveriesRequestDto requestDto;
#Value("${sdc.be.endpoint}")
private String sdcBeEndpoint;
#Value("${sdc.be.protocol}")
private String sdcBeProtocol;
#Value("${sdc.be.external.user}")
private String sdcUser;
#Value("${sdc.be.external.password}")
private String sdcPassword;
#Mock
private RestTemplate restClientMock;
#Mock
private RestTemplateBuilder builder;
#InjectMocks
private ArtifactAssociationService associationService;
#Before
public void setUp() throws IOException {
inputStreamMock = IOUtils.toInputStream("some test data for my input stream", "UTF-8");
artifactMock = new ArtifactEntity(FILE_NAME, inputStreamMock);
requestDto = new ArtifactDeliveriesRequestDto("POST",END_POINT);
MockitoAnnotations.initMocks(this);
associationService = Mockito.spy(new ArtifactAssociationService(builder));
associationService.setRestClient(restClientMock);
}
The Tested component:
#Component("ArtifactAssociationHandler")
public class ArtifactAssociationService {
#Value("${sdc.be.endpoint}")
private String sdcBeEndpoint;
#Value("${sdc.be.protocol}")
private String sdcBeProtocol;
#Value("${sdc.be.external.user}")
private String sdcUser;
#Value("${sdc.be.external.password}")
private String sdcPassword;
private RestTemplate restClient;
#Autowired
public ArtifactAssociationService(RestTemplateBuilder builder) {
this.restClient = builder.build();
}
void setRestClient(RestTemplate restClient){
this.restClient = restClient;
}
How can I properly test this with application-test.properties?
Your setup method is creating the instance of ArtifactAssociationService. This means that it isn't a Spring bean and, therefore, doesn't have any dependency injection performed. This includes injection into fields annotated with #Value.
If you want the #Value-annotated fields to have their values injected, you will have to make your ArtifactAssociationService instance a bean, for example by creating it using a #Bean method in a #Configuration class.

Sitecore Glass data model inheritence

I am using the Glass Mapper on a Sitecore instance where I have a basic data template structure of
Base
BaseWithList
BaseWithExtraContent
BaseWithExtraContentAndCallToActionLink
I have added model classes in my project to follow this structure too. My class names match my template names.
[SitecoreType(TemplateId = "{5D19BD92-799E-4DC1-9A4E-1DDE3AD68DAD}", AutoMap = true)]
public class Base
{
public virtual string Title {get;set;}
public virtual string Content {get;set;}
}
[SitecoreType(TemplateId = "{0491E3D6-EBAA-4E21-B255-80F0607B176D}", AutoMap = true)]
public class BaseWithExtraContent : Base
{
public virtual string ExtraContent {get;set;}
}
[SitecoreType(TemplateId = "{95563412-7A08-46A3-98CB-ABC4796D57D4}", AutoMap = true)]
public class BaseWithExtraContentAndCallToActionLink : BaseWithExtraContent
{
public virtual string CallToActionLink {get;set;}
}
These data models are used from another class that has a list of base type, I want to be able to store any derived type in here so I added attributes as detailed in this tutorial
[SitecoreType(AutoMap = true)]
public class HomePage
{
[SitecoreChildren(InferType = true)]
[SitecoreField(FieldName = "Widgets")]
public virtual IEnumerable<Base> Widgets { get; set; }
}
According to the tutorial this should work. However the list of widget just contains class of the base type.
I then found a later tutorial that said that if you have separated out the models to a different assemblies than the one Glass is installed in you have to add an AttributeConfigurationLoader pointing to the assembly your models are in. The base and derived types are all in the same assembly so I wasn't sure this would solve the issue, but I tried it anyway.
My custom loader config looks like this:
public static class GlassMapperScCustom
{
public static void CastleConfig(IWindsorContainer container)
{
var config = new Config {UseWindsorContructor = true};
container.Install(new SitecoreInstaller(config));
}
public static IConfigurationLoader[] GlassLoaders()
{
var attributes = new AttributeConfigurationLoader("Project.Data");
return new IConfigurationLoader[] {attributes};
}
public static void PostLoad(){
//Remove the comments to activate CodeFist
/* CODE FIRST START
var dbs = Sitecore.Configuration.Factory.GetDatabases();
foreach (var db in dbs)
{
var provider = db.GetDataProviders().FirstOrDefault(x => x is GlassDataProvider) as GlassDataProvider;
if (provider != null)
{
using (new SecurityDisabler())
{
provider.Initialise(db);
}
}
}
* CODE FIRST END
*/
}
}
Upon doing the custom loader config I now get an "Ambiguous match found" exception. I have checked to see if there are any other non Glass attributes set in the classes in that assembly and there aren't.
Any ideas? I guess there are 2 questions.
Why does using the inferred type attribute not load the correct types and only the base types?
Why when I attempt to solve this by adding a custom attribute loader do I get the exception?
Widgets property has two attributes - it's either mapped to the children elements of the item, or a field, can't be both.

Trouble with my first RESTful Web Services

i'm developing my firts RestFul webServices in javaEE6.
This is my Entity Bean
#XmlRootElement
#Entity
public class MyEntity implements Serializable {
#Id
#GeneratedValue
private long idEntity;
private String name;
private String description;
#OneToMany(mappedBy = "entity" , fetch = FetchType.EAGER)
private List<EntityB> list;
//Get and set
}
#Entity
public class EntityB {
#Id
#GeneratedValue
private long idCategoria;
#ManyToOne
private MyEntity myEntity;
}
this is my webServices
#Path("myentity")
#Produces( {MediaType.APPLICATION_XML , MediaType.APPLICATION_JSON })
#Consumes( {MediaType.APPLICATION_XML , MediaType.APPLICATION_JSON })
#Stateless
public class MyEntityService {
#Inject
MyEntityDao entityDao;
#GET
#Path("{id}/")
public MyEntity findById(#PathParam("id") Long id){
return entityDao.findById(id);
}
}
Finally i configured Jersey
#ApplicationPath("ws")
public class ApplicationConfig extends Application {
}
Now , if i try a invoke my web services (localhost:8080/xxxx/ws/myentity) i get this error:
HTTP Status 500 - javax.xml.bind.MarshalException - with linked exception: [com.sun.istack.SAXException2: A cycle is detected in the object graph. This will cause infinitely deep XML
You have a cyclic Graph of objects, which is not allowed , as it would result in an "infinite" XML.
MyEntity Holds a reference to EntityB , which holds a reference that goes back to MyEntity.
The marshaller will try to marshall MyEntity > EntityB > MyEntity > EntityB and so on.
You can mark MyEntity in EntityB as #XmlTransient, to avoid this.
However, It might not be a good idea to try to use the same Classes of objects across all your project (From persistence layers to communication layers).

Cast objects of different type

I have wrote a class (a snippet is below) which have some data members where i put data from the Client Side. I should send this data through Web Services where is a class which includes my data members, but has more data members that my class.
I should cast from my type into another type.
The problem is that i don't know how to access data members to take data from.
all my data are into this object "OBJ":
__XtraInvoiceInfo OBJ = new __XtraInvoiceInfo();
and , the Web Services's type is "InvoiceWithEntriesInfo"
var convertedObj = new InvoiceWithEntriesInfo()
{
invoiceNumber = OBJ.BasicInfo.InvoiceNumber --> member is not access.
| Equals
Visual Studio suggests | GetHashCode
only these methods | GetType
| ToString
invoiceDate = OBJ.BasicInfo.InvoiceDate *--> member is not accessible
firstName = OBJ.Payer.FirstName *-->> not accessible
lastName = OBJ.Payer.LastName *-->> not accessible
catem = OBJ.Payer.Catem *-->> not accessible
};
error "member is not accessible" means *--> 'object' does not contain a definition for 'InvoiceDate' and no extension method 'InvoiceDate' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)
public sealed class __XtraInvoiceInfo
{
private long _payerType = -1;
public long PayerType
{
get
{
return this._payerType;
}
set
{
this._payerType = value;
if (value == Constants.NATURAL_PAYER)
{
this.Payer = new __NaturalInvoiceInfo();
}
}
}
public object Payer
{
get; set;
}
public object BasicInfo
{
get; set;
}
//-- Nested Types --
public sealed class __NaturalInvoiceInfo
{
public string FirstName
{
get; set;
}
public string LastName
{
get; set;
}
public long Catem
{
get; set;
}
}
public sealed class __BasicInvoiceInfo
{
public long InvoiceNumber
{
get; set;
}
public DateTime? InvoiceDate
{
get; set;
}
}
}
I made properties Payer and BasicInfo because through them i take data from Client and i made a subbinding into my members like this way:
model.BindModel(xii =>
{
var bindModel = new ValidationFrameBindModel<__XtraInvoiceInfo.__BasicInvoiceInfo>();
this.BindControls(bindModel);
model.BindModel<__XtraInvoiceInfo.__BasicInvoiceInfo>((x,b) => x.BasicInfo = b, bindModel);
});
Thank you so much!!! if you have the power to answer my question.
I'm ready to say more details if it is required.
Well this is the problem:
public object Payer { get; set; }
public object BasicInfo { get; set; }
You're only declaring the properties as being of type object - why not give them more useful types? If you don't know the types, how do you know what properties will be there? Can you create abstract base class or interface which declares all the properties you want to guarantee will be there? (It's fairly hard to tell what you're trying to do, to be honest.)
If you're using C# 4 and .NET 4 you could just make them dynamic:
public dynamic Payer { get; set; }
public dynamic BasicInfo { get; set; }
Then accessing sub-properties will be bound at execution time against the actual type of object.
On a side-note, please don't prefix type names with __ - the C# specification reserves identifiers using __ for compiler-specific features. From section 2.4.2:
Identifiers containing two consecutive underscore characters (U+005F) are reserved for use by the implementation. For example, an implementation might provide extended keywords that begin with two underscores.