Returning Custom Class from WCF Method? - wcf

There are so many question about that but there is no solution for my problem. I want to return a custom class which has datacontract key and it's members have datamember key. I am getting this error while I testing it;
When I call it from my windows phone application, it returns "The remote server not found"
It returns not found but it runs methods that return types are void, bool, list.
[OperationContract]
BaseModel Login(string userName, string password);
[DataContract]
public class UserModel
{
private int userID;
[DataMember]
public int UserID
{
get { return userID; }
set { userID = value; }
}
private string userName;
[DataMember]
public string UserName
{
get { return userName; }
set { userName = value; }
}
private string password;
[DataMember]
public string Password
{
get { return password; }
set { password = value; }
}
private string email;
[DataMember]
public string Email
{
get { return email; }
set { email = value; }
}
private int securityQuestionID;
[DataMember]
public int SecurityQuestionID
{
get { return securityQuestionID; }
set { securityQuestionID = value; }
}
private string securityQuestionAnswer;
[DataMember]
public string SecurityQuestionAnswer
{
get { return securityQuestionAnswer; }
set { securityQuestionAnswer = value; }
}
private string sex;
[DataMember]
public string Sex
{
get { return sex; }
set { sex = value; }
}
private string gsmNo;
[DataMember]
public string GSMNo
{
get { return gsmNo; }
set { gsmNo = value; }
}
private DateTime birthDate;
[DataMember]
public DateTime BirthDate
{
get { return birthDate; }
set { birthDate = value; }
}
private string registeredDeviceUniqueID;
[DataMember]
public string RegisteredDeviceUniqueID
{
get { return registeredDeviceUniqueID; }
set { registeredDeviceUniqueID = value; }
}
private string registrationType;
[DataMember]
public string RegistrationType
{
get { return registrationType; }
set { registrationType = value; }
}
private string registeredDeviceType;
[DataMember]
public string RegisteredDeviceType
{
get { return registeredDeviceType; }
set { registeredDeviceType = value; }
}
private string registeredApplication;
[DataMember]
public string RegisteredApplication
{
get { return registeredApplication; }
set { registeredApplication = value; }
}
private DateTime registeredDate;
[DataMember]
public DateTime RegisteredDate
{
get { return registeredDate; }
set { registeredDate = value; }
}
private string registeredGSM;
[DataMember]
public string RegisteredGSM
{
get { return registeredGSM; }
set { registeredGSM = value; }
}
private string profilePictureURL;
[DataMember]
public string ProfilePictureURL
{
get { return profilePictureURL; }
set { profilePictureURL = value; }
}
}
[DataContract]
public class BaseModel
{
private string errorMessage;
[DataMember]
public string ErrorMessage
{
get { return errorMessage; }
set { errorMessage = value; }
}
private string informationMessage;
[DataMember]
public string InformationMessage
{
get { return informationMessage; }
set { informationMessage = value; }
}
private string warningMessage;
[DataMember]
public string WarningMessage
{
get { return warningMessage; }
set { warningMessage = value; }
}
private string succeedMessage;
[DataMember]
public string SucceedMessage
{
get { return succeedMessage; }
set { succeedMessage = value; }
}
private object returnObject;
[DataMember]
public object ReturnObject
{
get { return returnObject; }
set { returnObject = value; }
}
private bool isSucceed;
[DataMember]
public bool IsSucceed
{
get { return isSucceed; }
set { isSucceed = value; }
}
}
And the method is;
public BaseModel Login(string userName, string password)
{
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand("SELECT * FROM UserBaseInformations WITH (NOLOCK) Where UserName=#userName", connection))
{
command.Parameters.Add(new SqlParameter("#userName", userName));
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = command;
DataTable dt = new DataTable();
adapter.Fill(dt);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
connection.Close();
if (dt.Rows.Count == 0)
return new BaseModel() { IsSucceed = false, ErrorMessage = "Geçersiz bir kullanıcı adı girdiniz." };
else if (!dt.Rows[0]["Password"].ToString().Equals(password))
return new BaseModel() { IsSucceed = false, ErrorMessage = "Şifrenizi yanlış girdiniz." };
else
return new BaseModel()
{
IsSucceed = true,
ReturnObject = new UserModel()
{
Email = dt.Rows[0]["Email"].ToString(),
Password = dt.Rows[0]["Password"].ToString(),
UserID = (int)dt.Rows[0]["UserID"],
UserName = dt.Rows[0]["UserName"].ToString(),
SecurityQuestionID = (int)dt.Rows[0]["SecurityQuestionID"],
SecurityQuestionAnswer = dt.Rows[0]["SecurityQuestionAnswer"].ToString()
}
};
}
}
}

I have found solution.
Returning an object type can be problem in WCF so I changed it to a base class for returning my classes and added KnownType attribute to BaseModel.

Related

How to return different types of responses from WCF service application method?

I have a WCF service application with a method
public PersonResponse(PersonRequest request)
{
return new PersonResponse { Id = 1, Name = "Mark" };
}
I have 2 different responses possible for that method
[DataContract]
public class PersonResponse
{
int id;
string name;
[DataMember]
public int Id
{
get { return id; }
set { id = value; }
}
[DataMember]
public string Name
{
get { return name; }
set { name = value; }
}
}
and
[DataContract]
public class ErrorResponse
{
int errorCode;
string errorText;
[DataMember]
public int? ErrorCode
{
get { return errorCode; }
set { errorCode = value; }
}
[DataMember]
public string ErrorText
{
get { return errorText; }
set { errorText = value; }
}
}
Is it possible to write a method that could return either of those responses but not both at the same time?
I Could do something like
[DataContract]
public class Response
{
PersonResponse personResponse;
ErrorResponse errorResponse;
[DataMember]
public bool PersonResponse
{
get { return personResponse; }
set { personResponse= value; }
}
[DataMember]
public string ErrorResponse
{
get { return errorResponse; }
set { errorResponse= value; }
}
}
public Response(PersonRequest request)
{
return new Response{ PersonResponse = New PersonResponse { Id = 1, Name = "Mark" }, ErrorResponse = new ErrorResponse { ErrorCode = null, ErrorText = null } };
}
But I only need 1 type of the response to be returned, not both.
I've tried
public PersonResponse(PersonRequest request)
{
throw new WebFaultException<ErrorResponse>(new ErrorResponse { ErrorCode = 103 ErrorText = "Try again later" }, HttpStatusCode.Conflict);
}
But it seems that this way it only returns the exception and not the ErrorResponse.
I've also tried adding and interface layer to the response like so and then returning that interface as a response
public interface IResponse {}
[DataContract]
public class PersonResponse : IResponse
{
int id;
string name;
[DataMember]
public int Id
{
get { return id; }
set { id = value; }
}
[DataMember]
public string Name
{
get { return name; }
set { name = value; }
}
}
[DataContract]
public class ErrorResponse : IResponse
{
int errorCode;
string errorText;
[DataMember]
public int? ErrorCode
{
get { return errorCode; }
set { errorCode = value; }
}
[DataMember]
public string ErrorText
{
get { return errorText; }
set { errorText = value; }
}
}
public IResponse(PersonRequest request)
{
return new PersonResponse { Id = 1, Name = "Mark" };
}
But when I add this service as a reference to another project id doesn't generate any of the response type (Iresponse, ErrorResonse or PersonResponse) and throws an error when I try to call the method (Exception message https://ibb.co/Zdsbr9p)
I think you can try to use FaultContractAttribute. Fault contracts allow you to specify alternate responses that will be returned in a SOAP fault.
Example interface:
[ServiceContract]
interface IService
{
[OperationContract]
[FaultContract(typeof(ErrorResponse))]
PersonResponse GetResponse();
}
Service:
class Service : IService
{
public PersonResponse GetResponse()
{
if (success)
{
return new PersonResponse();
}
else
{
throw new FaultException<ErrorResponse>(new ErrorResponse()
{
ErrorMessage = "Something Happened"
})
}
}
}
The client can then handle the fault by catching FaultException<ErrorResponse>:
var serviceProxy = new ServiceProxy();
try
{
var dataObj = serviceProxy.GetResponse();
}
catch (FaultException<ErrorResponse> error)
{
ErrorResponse detail = error.Detail;
Console.WriteLine(detail.ErrorMessage);
}
source:How best should a Wcf service return different objects for the same method
resemblance:Return different Object (List or error class) from WCF service

WCF SOAP service give an error An error occurred while receiving the HTTP response to http://localhost/Service1.svc

when i make the client and call the getNews it goes into service but after the return its give me this error
System.ServiceModel.CommunicationException: 'An error occurred while receiving the HTTP response to http://localhost/Service1.svc. This could be due to the service endpoint binding not using the HTTP protocol. This could also be due to an HTTP request context being aborted by the server (possibly due to the service shutting down). See server logs for more details.'
Interface is :
[ServiceContract , XmlSerializerFormat]
public interface IService1
{
[OperationContract]
// string getNews(getNewsRequest request);
// GetNewsOutputStructure getNews (getNewsRequest request);
// getNewsResponseStructure getNews(getNewsRequest request);
getNewsResponse getNews();
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDataUsingDataContract(CompositeType composite);
// TODO: Add your service operations here
}
the implementation is
public getNewsResponse getNews()
{
getNewsResponse response = null;
List<NewsListStructure> newsList = new List<NewsListStructure>();
NewsStructure news = null;
for (int i = 0; i < 2; i++)
{
news = new NewsStructure();
news.NewsText = "Test";
news.NewsId = "22";
news.NewsDate = DateTime.Now;
MediaExtentionsArrayStructure[] mediaExtentionsArrayStructures = null;
news.MediaExtentionsArrayObject = mediaExtentionsArrayStructures; //nnList[i].NewsDate;
news.NewsClassificationObject = new NewsClassificationStructure { NewsClassificationId = 1.ToString(), NewsClassificationDescription = "g" };
// news.MediaArrayObject = nnList[i].NewsDate;
NewsListStructure newsStructure = new NewsListStructure();
newsStructure.NewsObject = news;
newsList.Add(newsStructure);
}
// return newsList;
GetNewsOutputStructure getNewsOutputStructure = new GetNewsOutputStructure();
getNewsOutputStructure.NewsListObject = newsList.ToArray();
getNewsOutputStructure.ResponseStatus = ResponseStatusType.Success;
getNewsOutputStructure.DataSchemaVersion = 1;
getNewsOutputStructure.FaildReasonListObject = new FaildReasonListStructure[1] ;
var fdf = new ErrorStructure() { Item = "hh" , ItemElementName = ItemChoiceType.ErrorMessage};
getNewsOutputStructure.FaildReasonListObject[0] = new FaildReasonListStructure();
getNewsOutputStructure.FaildReasonListObject[0].Item = fdf;
// return getNewsOutputStructure;
getNewsResponseStructure getNewsResponseStructure = new getNewsResponseStructure();
getNewsResponseStructure.Item = getNewsOutputStructure;
// return getNewsResponseStructure;
// response = new getNewsResponse(getNewsResponseStructure);
response = new getNewsResponse();
response.getNewsResponseObject = getNewsResponseStructure;
response.getNewsResponseObject.Item = newsList;
return response;
}
after return response i got an error
and this is the object i will return
[DataContract]
public class getNewsResponse
{
// [System.ServiceModel.MessageBodyMemberAttribute()]
[XmlElement]
[DataMember]
public getNewsResponseStructure getNewsResponseObject;
public getNewsResponse()
{
}
public getNewsResponse(getNewsResponseStructure getNewsResponseObject)
{
this.getNewsResponseObject = getNewsResponseObject;
}
}
[DataContract]
public class getNewsResponseStructure
{
// [DataMember]
private object itemField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("getNewsResponseDetailObject", typeof(GetNewsOutputStructure))]
// [System.Xml.Serialization.XmlElementAttribute("ServiceError", typeof(CommonErrorStructure))]
[XmlElement]
[DataMember]
public object Item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
}
[DataContract]
public partial class GetNewsOutputStructure
{
private ResponseStatusType responseStatusField;
private NewsListStructure[] newsListObjectField;
private FaildReasonListStructure[] faildReasonListObjectField;
private decimal dataSchemaVersionField;
// [System.Xml.Serialization.XmlElementAttribute(Order = 0)]
[XmlElement]
/// <remarks/>
[DataMember]
public ResponseStatusType ResponseStatus
{
get
{
return this.responseStatusField;
}
set
{
this.responseStatusField = value;
}
}
[XmlElement]
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("NewsListObject", Order = 1)]
[DataMember]
public NewsListStructure[] NewsListObject
{
get
{
return this.newsListObjectField;
}
set
{
this.newsListObjectField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("FaildReasonListObject", Order = 2)]
[DataMember]
[XmlElement]
public FaildReasonListStructure[] FaildReasonListObject
{
get
{
return this.faildReasonListObjectField;
}
set
{
this.faildReasonListObjectField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 3)]
[DataMember]
[XmlElement]
public decimal DataSchemaVersion
{
get
{
return this.dataSchemaVersionField;
}
set
{
this.dataSchemaVersionField = value;
}
}
}
[DataContract]
[Flags]
public enum ResponseStatusType
{
// [System.Runtime.Serialization.EnumMemberAttribute()]
[EnumMember]
/// <remarks/>
Success,
// [System.Runtime.Serialization.EnumMemberAttribute()]
[EnumMember]
/// <remarks/>
Fail,
}
[DataContract]
public partial class NewsListStructure
{
private NewsStructure newsObjectField;
[DataMember]
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 0)]
[XmlElement]
public NewsStructure NewsObject
{
get
{
return this.newsObjectField;
}
set
{
this.newsObjectField = value;
}
}
}
[DataContract]
public partial class FaildReasonListStructure
{
private ErrorStructure itemField;
[DataMember]
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("ErrorObject", Order = 0)]
[XmlElement]
public ErrorStructure Item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
}
[DataContract]
public partial class ErrorStructure
{
private string itemField;
private ItemChoiceType itemElementNameField;
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("ErrorCode", typeof(string), Order = 0)]
// [System.Xml.Serialization.XmlElementAttribute("ErrorMessage", typeof(string), Order = 0)]
// [System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemElementName")]
[DataMember]
[XmlElement]
public string Item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 1)]
// [System.Xml.Serialization.XmlIgnoreAttribute()]
[XmlElement]
public ItemChoiceType ItemElementName
{
get
{
return this.itemElementNameField;
}
set
{
this.itemElementNameField = value;
}
}
}
[DataContract]
[Flags]
public enum ItemChoiceType
{
// [System.Runtime.Serialization.EnumMemberAttribute()]
[EnumMember]
/// <remarks/>
ErrorCode,
// [System.Runtime.Serialization.EnumMemberAttribute()]
[EnumMember]
/// <remarks/>
ErrorMessage,
}
[DataContract]
public partial class NewsStructure
{
private string newsIdField;
private NewsClassificationStructure newsClassificationObjectField;
private string newsTextField;
private MediaArrayStructure[] mediaArrayObjectField;
private MediaExtentionsArrayStructure[] mediaExtentionsArrayObjectField;
private System.DateTime newsDateField;
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 0)]
[DataMember]
[XmlElement]
public string NewsId
{
get
{
return this.newsIdField;
}
set
{
this.newsIdField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 1)]
[DataMember]
[XmlElement]
public NewsClassificationStructure NewsClassificationObject
{
get
{
return this.newsClassificationObjectField;
}
set
{
this.newsClassificationObjectField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 2)]
[DataMember]
[XmlElement]
public string NewsText
{
get
{
return this.newsTextField;
}
set
{
this.newsTextField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("MediaArrayObject", Order = 3)]
[DataMember]
[XmlElement]
public MediaArrayStructure[] MediaArrayObject
{
get
{
return this.mediaArrayObjectField;
}
set
{
this.mediaArrayObjectField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("MediaExtentionsArrayObject", Order = 4)]
[DataMember]
[XmlElement]
public MediaExtentionsArrayStructure[] MediaExtentionsArrayObject
{
get
{
return this.mediaExtentionsArrayObjectField;
}
set
{
this.mediaExtentionsArrayObjectField = value;
}
}
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(DataType = "date", Order = 5)]
[DataMember]
[XmlElement]
public System.DateTime NewsDate
{
get
{
return this.newsDateField;
}
set
{
this.newsDateField = value;
}
}
}
[DataContract]
public partial class MediaExtentionsArrayStructure
{
private string itemField;
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("MediaExtentions", Order = 0)]
[DataMember]
[XmlElement]
public string Item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
}
[DataContract]
public partial class MediaArrayStructure
{
private byte[] itemField;
[DataMember]
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute("Media", DataType = "base64Binary", Order = 0)]
[XmlElement]
public byte[] Item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
}
[DataContract]
public partial class NewsClassificationStructure
{
private string newsClassificationIdField;
private string newsClassificationDescriptionField;
[DataMember]
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 0)]
[XmlElement]
public string NewsClassificationId
{
get
{
return this.newsClassificationIdField;
}
set
{
this.newsClassificationIdField = value;
}
}
[DataMember]
/// <remarks/>
// [System.Xml.Serialization.XmlElementAttribute(Order = 1)]
[XmlElement]
public string NewsClassificationDescription
{
get
{
return this.newsClassificationDescriptionField;
}
set
{
this.newsClassificationDescriptionField = value;
}
}
}
//[System.Diagnostics.DebuggerStepThroughAttribute()]
//[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
//[System.Xml.Serialization.XmlSchemaProviderAttribute("ExportSchema")]
//[System.Xml.Serialization.XmlRootAttribute]
[DataContract]
public partial class CommonErrorStructure : object, System.Xml.Serialization.IXmlSerializable
{
private System.Xml.XmlNode[] nodesField;
private static System.Xml.XmlQualifiedName typeName = new System.Xml.XmlQualifiedName();
[DataMember]
[XmlElement]
public System.Xml.XmlNode[] Nodes
{
get
{
return this.nodesField;
}
set
{
this.nodesField = value;
}
}
public void ReadXml(System.Xml.XmlReader reader)
{
this.nodesField = System.Runtime.Serialization.XmlSerializableServices.ReadNodes(reader);
}
public void WriteXml(System.Xml.XmlWriter writer)
{
System.Runtime.Serialization.XmlSerializableServices.WriteNodes(writer, this.Nodes);
}
public System.Xml.Schema.XmlSchema GetSchema()
{
return null;
}
public static System.Xml.XmlQualifiedName ExportSchema(System.Xml.Schema.XmlSchemaSet schemas)
{
System.Runtime.Serialization.XmlSerializableServices.AddDefaultSchema(schemas, typeName);
return typeName;
}
}
client code is
ServiceReference2.Service1Client client = new ServiceReference2.Service1Client();
ServiceReference2.getNewsRequest k = new ServiceReference2.getNewsRequest();
k.getNewsRequestObject = new ServiceReference2.GetNewsRequestStructure();
k.getNewsRequestObject.LastReceivedNewsItemId = "10000";
k.getNewsRequestObject.NumberOfRequestedNews = "5";
k.getNewsRequestObject.ServiceToken = "";
k.getNewsRequestObject.SPAGovernmentSectorKey = "";
k.getNewsRequestObject.SubServiceObject = new ServiceReference2.SubServicesStructure { SubServiceId = "1", SubServiceDescription = "desc" };
k.getNewsRequestObject.TypeOfData = ServiceReference2.TypeOfDataType.All;
k.yefiSOAPHeaderElement = new ServiceReference2.YefiHeader();
k.yefiSOAPHeaderElement.ServiceID = "1";
k.yefiSOAPHeaderElement.SourceID = "2";
k.yefiSOAPHeaderElement.SourceName = "genral";
var t = client.getNews( k);
// Always close the client.
client.Close();
This is because you pass List<NewsListStructure> to response.getNewsResponseObject.Item. According to the definition of your class, response.getNewsResponseObject.Item can only accept Object type, not List<Object> type.
There are two solutions. The first is to modify the getNewsResponseStructure class, as shown below:
public class getNewsResponseStructure
{
// [DataMember]
private List<Object> itemField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("getNewsResponseDetailObject", typeof(GetNewsOutputStructure))]
// [System.Xml.Serialization.XmlElementAttribute("ServiceError", typeof(CommonErrorStructure))]
[XmlElement]
[DataMember]
public List<Object> Item
{
get
{
return this.itemField;
}
set
{
this.itemField = value;
}
}
}
The second is to create NewsListStructure and pass it to response.getNewsResponseObject.Item:
NewsListStructure news = new NewsListStructure();
response.getNewsResponseObject.Item = news;
the problem was in my Client i tried to sent a diffrent type of object that i cast it in the service
this the wrong
response.getNewsResponseObject.Item = newsList;
this is true
response.getNewsResponseObject.Item = getNewsOutputStructure;
becouse in service i told it i will sent to you an
GetNewsOutputStructure object not List<NewsListObject>
in service
[System.Xml.Serialization.XmlElementAttribute("getNewsResponseDetailObject", typeof(GetNewsOutputStructure), Form = System.Xml.Schema.XmlSchemaForm.Unqualified, Order = 0)]

How to add List<int> to a DataContract of a web service

I want to create a DataContract that is a class with 2 different List members. When I try to start the web service, I get the error that my method, SendEmail, is not supported by the Test WCF Client.
This is my Data Contract:
[DataContract]
[KnownType(typeof(int[]))]
public class EmailInfo
{
private string strFromUserID = string.Empty;
private string strFromAddress = string.Empty;
private string strFromName = string.Empty;
private object lstIndividualIDs = null;
private object lstGroupIDs = null;
private string strSubject = string.Empty;
private string strMessage = string.Empty;
[DataMember]
public string FromUserID
{
get { return strFromUserID; }
set { strFromUserID = value; }
}
[DataMember]
public string FromAddress
{
get { return strFromAddress; }
set { strFromAddress = value; }
}
[DataMember]
public string FromName
{
get { return strFromName; }
set { strFromName = value; }
}
[DataMember]
public object IndividualIDs
{
get { return lstIndividualIDs; }
set { lstIndividualIDs = value; }
}
[DataMember]
public object GroupIDs
{
get { return lstGroupIDs; }
set { lstGroupIDs = value; }
}
[DataMember]
public string Subject
{
get { return strSubject; }
set { strSubject = value; }
}
[DataMember]
public string Message
{
get { return strMessage; }
set { strMessage = value; }
}
}
This is my method that uses the DataContract:
public string SendEmail(EmailInfo emailInfo)
{
string tstrErrorMsg = string.Empty;
SqlConnection SqlConn = null;
try
{
return tstrErrorMsg;
}
catch (Exception ex)
{
return null;
}
finally
{
if (SqlConn != null)
{
SqlConn.Close();
}
}
}
I would like to have a DataMember in the DataContract that is of type List. How do I add that type to a DataContract?
I got the web service to run by changing the lstIndividualIDs and listGroupIDs to List.
I thought I had to use objects.
In case anybody else has this problem...
object lstIndividualIDs -> List listIndividualIDs
same with GroupIDs.
This allowed the Test client to run the service..

How to assign value to Address , Country and City

Here is classes
-Person
-User
-City
-Country
-Address
Person has complex properties of (Address),
Address has complex Properties of (Country , City)
Class User inherited from Person class
scenario:-
I want to create a signup view inwhich i want to assign values to Address , country , city. How can i do it.
Below is the detail of classes
public class Person
{
public Person()
{ }
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private Gender gender;
public virtual Gender Gender
{
get { return gender; }
set { gender = value; }
}
private ICollection<ContactNumber> contactNumber;
public virtual ICollection<ContactNumber> ContactNumber
{
get { return contactNumber; }
set { contactNumber = value; }
}
private Address address;
public virtual Address Address
{
get { return address; }
set { address = value; }
}
private DateTime dateOfBirth;
public DateTime DateOfBirth
{
get { return dateOfBirth; }
set { dateOfBirth = value; }
}
private string picture;
public string Picture
{
get { return picture; }
set { picture = value; }
}
}
public class User : Person
{
public User() : base()
{ }
private ICollection<Role> roles;
public virtual ICollection<Role> Roles
{
get { return roles; }
set { roles = value; }
}
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string email;
[Required()]
[RegularExpression(#"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*")]
[Display(Name = "Email Address")]
public string Email
{
get { return email; }
set { email = value; }
}
private string loginId;
[Required()]
[Display(Name = "Login")]
public string LoginId
{
get { return loginId; }
set { loginId = value; }
}
private string password;
[Required()]
[Display(Name = "Password")]
[DataType(DataType.Password)]
public string Password
{
get { return password; }
set { password = value; }
}
private string repassword;
[Required()]
[Display(Name = "Confirm Password")]
[Compare("Password")]
public string Repassword
{
get { return repassword; }
set { repassword = value; }
}
private string secretQuestion;
[Required()]
[Display(Name = "Secret Question")]
public string SecretQuestion
{
get { return secretQuestion; }
set { secretQuestion = value; }
}
private string secretAnswer;
[Required()]
[Display(Name = "Answer")]
public string SecretAnswer
{
get { return secretAnswer; }
set { secretAnswer = value; }
}
private string photoUrl;
[Display(Name = "Image")]
public string PhotoUrl
{
get { return photoUrl; }
set { photoUrl = value; }
}
}
public class Country
{
public Country()
{ }
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
//private string flagUrl;
}
public class City
{
public City()
{ }
private int id;
public int Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private Country country;
public virtual Country Country
{
get { return country; }
set { country = value; }
}
}
Thanx in Advance.
If you right click on your action method for your signup page in your controller and select Add View In the dialog that appears you can choose to make the view strongly typed. Select your User class and visual studio will scaffold a lot of the code needed.
If you need more help in working with MVC here is a good place to start.

NHibernate FetchMode.Lazy

I have an object which has a property on it that has then has collections which i would like to not load in a couple situations. 98% of the time i want those collections fetched but in the one instance i do not. Here is the code I have... Why does it not set the fetch mode on the properties collections?
[DataContract(Name = "ThemingJob", Namespace = "")]
[Serializable]
public class ThemingJob : ServiceJob
{
[DataMember]
public virtual Query Query { get; set; }
[DataMember]
public string Results { get; set; }
}
[DataContract(Name = "Query", Namespace = "")]
[Serializable]
public class Query : LookupEntity<Query>, DAC.US.Search.Models.IQueryEntity
{
[DataMember]
public string QueryResult { get; set; }
private IList<Asset> _Assets = new List<Asset>();
[IgnoreDataMember]
[System.Xml.Serialization.XmlIgnore]
public IList<Asset> Assets { get { return _Assets; } set { _Assets = value; } }
private IList<Theme> _Themes = new List<Theme>();
[IgnoreDataMember]
[System.Xml.Serialization.XmlIgnore]
public IList<Theme> Themes { get { return _Themes; } set { _Themes = value; } }
private IList<Affinity> _Affinity = new List<Affinity>();
[IgnoreDataMember]
[System.Xml.Serialization.XmlIgnore]
public IList<Affinity> Affinity { get { return _Affinity; } set { _Affinity = value; } }
private IList<Word> _Words = new List<Word>();
[IgnoreDataMember]
[System.Xml.Serialization.XmlIgnore]
public IList<Word> Words { get { return _Words; } set { _Words = value; } }
}
using (global::NHibernate.ISession session = NHibernateApplication.GetCurrentSession())
{
global::NHibernate.ICriteria criteria = session.CreateCriteria(typeof(ThemingJob));
global::NHibernate.ICriteria countCriteria = session.CreateCriteria(typeof(ThemingJob));
criteria.AddOrder(global::NHibernate.Criterion.Order.Desc("Id"));
var qc = criteria.CreateCriteria("Query");
qc.SetFetchMode("Assets", global::NHibernate.FetchMode.Lazy);
qc.SetFetchMode("Themes", global::NHibernate.FetchMode.Lazy);
qc.SetFetchMode("Affinity", global::NHibernate.FetchMode.Lazy);
qc.SetFetchMode("Words", global::NHibernate.FetchMode.Lazy);
pageIndex = Convert.ToInt32(pageIndex) - 1; // convert to 0 based paging index
criteria.SetMaxResults(pageSize);
criteria.SetFirstResult(pageIndex * pageSize);
countCriteria.SetProjection(global::NHibernate.Criterion.Projections.RowCount());
int totalRecords = (int)countCriteria.List()[0];
return criteria.List<ThemingJob>().ToPagedList<ThemingJob>(pageIndex, pageSize, totalRecords);
}