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);
}
Related
var obj = (from r in db.Module_Completion
.Where(r => r.star_id == User.Identity.Name)
select new
{
r.adv_stud_success,
r.important_policies,
r.technology,
r.finances,
r.resources,
r.student_life,
r.next_steps
}).FirstOrDefault();
obj = {true, false, false , true,...};
This is only one record that I query from database by using Linq
The reason is I would like to display Finsished 2 of 7 , that is why I need to count items in a record.
Thank you in advance!
public partial class Module_Completion
{
public int module_completionId { get; set; }
[StringLength(10)]
public string star_id { get; set; }
public bool adv_stud_success { get; set; }
public bool important_policies { get; set; }
public bool technology { get; set; }
public bool finances { get; set; }
public bool resources { get; set; }
public bool student_life { get; set; }
public bool next_steps { get; set; }
}
After I can store numbers in variable, then I would like to display like this"Finished 2 of 7"
So Every ModuleCompletion contains several Boolean properties. If the value of such a property is true, you consider the item to be "finished".
You want to count the number of finished items in a ModuleCompletion.
The proper method would be to add a property to class ModuleCompletion.
public int FinishedCount => ...
If you can't do this, for instance because ModuleCompletion represents the columns of a table in a database, then consider to add an extension method. If you are not familiar with extension methods, read Extension Methods demystified
public static int CountFinished(this ModuleCompletion moduleCompletion)
{
// TODO: implement
}
Usage would be:
ModuleCompletion x = ...
int finished = x.CountFinished();
This would work if your ModuleCompletion is in local process. However, if you want to do this database side (as queryable), this won't work: your database wouldn't know method CountFinished.
If you want to let the database do this, you could change your Select method:
int finishedCount = db.ModuleCompletions
.Where(completion => completion.star_id == User.Identity.Name)
.Select(completion =>
completion.adv_stud_success ? 1 : 0 +
completion.important_policies ? 1 : 0 +
completion.technology : 1 : 0 +
...)
.FirstOrDefault();
This looks rather ugly. Luckily we can create an extension method of IQueryable<ModuleCompletion>, such that you can use it as any other LINQ method:
public static IQueryable<int> ToFinishedCount(this IQueryable<ModuleCompletion> moduleCompletions)
{
return moduleCompletions.Select(completion =>
completion.adv_stud_success ? 1 : 0 +
completion.important_policies ? 1 : 0 +
completion.technology : 1 : 0 +
...);
}
This query can be translated into a language that your DBMS understands. Usage would be much easier to understand, much easier to reuse, unit test and modify:
int finishedCount = db.ModuleCompletions
.Where(completion => completion.star_id == User.Identity.Name)
.ToFinishedCount()
.FirstOrDefault();
My solution involves 2 parts first. Create a ViewModel to get the number of completed object that associates with the class that goes:
public class ModuleCompletesVM
{
public Module_Completion Module_Completion { get; set; }
public int Completed { get
{
return (Convert.ToInt32(Module_Completion.stud_success) +
Convert.ToInt32(Module_Completion.important_policies) +
Convert.ToInt32(Module_Completion.technology) +
Convert.ToInt32(Module_Completion.finances) +
Convert.ToInt32(Module_Completion.resources) +
Convert.ToInt32(Module_Completion.next_steps) +
Convert.ToInt32(Module_Completion.student_life));
}
}
}
Note that this View Model would calculate the number of completed subject of each Module_Completion Class and then from your controller. You just need to do something like this
var model= from s in db.Module_Completion
select new ModuleCompletesVM
{
Module_Completion = s
};
You can also achieve this by creating a function in SQL database as well. Another piece of advice is that, do consider stop using underscrore in your data table and data field. Follow the latest convention, the next person who take over your code will appreciate that.
I have an approach where you can have the total finished as property. Here is an example
public partial class Module_Completion
{
private bool _adv_stud_success;
private bool _important_policies;
private bool _technology;
private bool _finances;
private bool _resources;
private bool _student_life;
private bool _next_steps;
public int module_completionId { get; set; }
[StringLength(10)]
public string star_id { get; set; }
public bool adv_stud_success
{
get { return _adv_stud_success; }
set {
_adv_stud_success = value;
if (_adv_stud_success)
{
total_finsihed += 1;
}
}
}
public bool important_policies
{
get { return _important_policies; }
set
{
_important_policies = value;
if (_important_policies)
{
total_finsihed += 1;
}
}
}
public bool technology
{
get { return _technology; }
set
{
_technology = value;
if (_technology)
{
total_finsihed += 1;
}
}
}
public bool finances
{
get { return _finances; }
set
{
_finances = value;
if (_finances)
{
total_finsihed += 1;
}
}
}
public bool resources
{
get { return _resources; }
set
{
_resources = value;
if (_resources)
{
total_finsihed += 1;
}
}
}
public bool student_life
{
get { return _student_life; }
set
{
_student_life = value;
if (_student_life)
{
total_finsihed += 1;
}
}
}
public bool next_steps
{
get { return _next_steps; }
set
{
_next_steps = value;
if (_next_steps)
{
total_finsihed += 1;
}
}
}
/* This property is storing the finished count */
/* using System.ComponentModel.DataAnnotations.Schema; */
[NotMapped]
public int total_finsihed { get; set; }
}
After that you can do the following
var obj = (from r in db.Module_Completion
.Where(r => r.star_id == User.Identity.Name)
select new
{
r.total_finsihed
}).FirstOrDefault();
/* if the technology, finance, resources are true then */
/* obj = {3}; */
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)]
I'm trying to figure out how to pull values from a SQL database and display this in a razor view.
I have the following class using Entity Framework (I believe)
public class EventLog
{
[Key]
public int Id { get; set; }
public int EventId { get; set; }
public int MaxDelegates { get; set; }
public string Code { get; set; }
public DateTime End { get; set; }
public string Title { get; set; }
}
And I want to map title to DBTitle in the following model:
public class CourseDetailVM : CourseDetailSummaryVM
{
public EventLog DBTitle { get; set; }
}
I then want to see this in the following view:
#using TSW.Web.Helpers
#model TSW.Web.ViewModels.CourseDetailVM
#{
Layout = "~/Views/_Master.cshtml";
}
#Model.DBTitle.Title;
I have the following controller already in place (sorry for the length I plan to reduce this down):
public class CourseDetailController : BaseRenderController<CourseDetailPageDT>
{
private readonly ISitePageFactory _pageFactory = null;
private readonly IEventService _eventService = null;
public CourseDetailController(IEventService eventService, ISitePageFactory pageFactory)
{
_pageFactory = pageFactory;
_eventService = eventService;
}
public async Task<ActionResult> CourseDetail()
{
var homepage = _pageFactory.GetCurrentHomepage();
var model = Mapper.Map<CourseDetailVM>(CurrentContent);
model.Email = homepage.ContactEmail;
model.PhoneNumber = homepage.HeaderPhoneNumber;
model.InnerPageHeader.ShowHeading = true;
model.InnerPageHeader.Title = model.PageTitle;
if (model.Categories.Count == 1)
{
var categoryTagId = model.Categories.First().Id;
var contentTypeAlias = DocumentTypeHelper.GetDocumentTypeAlias<CourseListingPageDT>();
var courseCategoryPage = Umbraco.TypedContentAtXPath($"//{contentTypeAlias}")
.FirstOrDefault(x => x.GetPropertyValue<int>(Constants.DocumentTypes.CourseListingPage.Category) == categoryTagId);
if (courseCategoryPage != null)
{
model.InnerPageHeader.BackLink = Mapper.Map<LinkItem>(courseCategoryPage.Id);
}
}
try
{
model.Events = await _eventService.GetEventsForCourse(CurrentContent.AdministrateId);
}
catch (Exception ex)
{
model.Events = new StaticPagedList<Event>(Enumerable.Empty<Event>(), 1, 1, 0);
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
if (CurrentContent.Graphic != 0)
{
model.InnerPageHeader.Graphic = Mapper.Map<CtaItem>(CurrentContent.Graphic);
}
return View(model);
}
}
I've tried every suggestion I can google to add the mapping in the controlling but can't get my head around this simple function of pulling the value from a SQL database into the razor view.
Could anyone help me out?
I have two data contracts of same contents in two different namespaces. i have copied one datacontract to another and
passed to a particular method. but it is giving the below error and throwing exception. it is not going into that method.
Please let me know any ideas /suggestions on how to resolve this.Appreciate your help:
Exception errror:
{"Type 'System.Collections.Generic.List`1[[GlobalWcfServiceLib.TopicDetailsInfo, GlobalWcfContracts, Version=1.2.2.0, Culture=neutral,
PublicKeyToken=17c64733a9775004]]' with data contract name 'ArrayOfTopicDetailsInfo:http://CName.GlobalService/11.1/2010/11'
is not expected. Consider using a DataContractResolver or add any types not known statically to the list of
known types - for example, by using the KnownTypeAttribute attribute or by
adding them to the list of known types passed to DataContractSerializer."}
Message = "There was an error while trying to serialize parameter
http://CName.SharedServices.DBServiceLib:subscriptionDataContract.
The InnerException message was 'Type 'System.Collections.Generic.List`1
[[GlobalWcfServiceLib.TopicDetailsInfo,
GlobalWcfContra...
//////
Here is my scenario : i am copying the data from dc to new data contract as below. after copying , when i am executing the createsubscriptions method i am getting the above mentioned error. i have given the details of data contract and error attached to this question. please refer to that as well.
Method1(SubscriptionDataContracts dc)
{
SubscriptionDataContract subscriptionDataContract = new SubscriptionDataContract();
List<SubscriptionTopicInfo> topicsInfo = dc.TopicList;
List<SubscriptionTopic> newTopicsList = new List<SubscriptionTopic>();
subscriptionDataContract.ExtensionData = dc.ExtensionData;
subscriptionDataContract.UserID = dc.UserID;
for (int i = 0; i < topicsInfo.Count; i++)
{
SubscriptionTopic topic = new SubscriptionTopic();
topic.DBHandle = topicsInfo[i].DBHandle;
topic.Topic = topicsInfo[i].Topic;
topic.Target = topicsInfo[i].Target;
newTopicsList.Add(topic);
}
subscriptionDataContract.TopicList = newTopicsList;
CreateSubscriptions(subscriptionDataContract); //getting the above mentioned error in another dll after going into this method
}
////////////////////////////////
//My data contract
[DataContract(Name = "TopicDetailsInfo", Namespace = "http://CName.GlobalService")]
[Serializable]
public class TopicDetailsInfo
{
protected object topic;
protected object baseObjectType;
[DataMember]
public object BaseObjectType
{
get
{
return baseObjectType;
}
set
{
baseObjectType = value;
}
}
[DataMember]
public object TopicID
{
get
{
return topic;
}
set
{
topic = value;
}
}
static public TopicDetailsInfo CreateTopic<T, mT>(IComparable<T> objectType, IComparable<mT> objectID)
{
var topicDetails = new TopicDetailsInfo();
topicDetails.BaseObjectType = objectType;
topicDetails.TopicID = objectID;
return topicDetails;
}
}
[DataContract(Name = "SubscriptionTopicInfo", Namespace = "http://CName.GlobalService")]
[KnownType(typeof(List<TopicDetailsInfo>))]
[Serializable]
public class SubscriptionTopicInfo
{
private object topic;
private object target;
private object creator;
[DataMember]
public object Topic
{
get
{
return topic;
}
set
{
topic = value;
}
}
[DataMember]
public object Target
{
get
{
return target;
}
set
{
target = value;
}
}
[DataMember]
public object DBHandle
{
get
{
return creator;
}
set
{
creator = value;
}
}
static public SubscriptionTopicInfo CreateSubscriptions<T, mT, nT>(IList<TopicDetailsInfo> topic, IComparable<mT> target, IComparable<nT> handle)
{
var subscriptionTopic = new SubscriptionTopicInfo();
subscriptionTopic.Target = target;
subscriptionTopic.Topic = topic;
subscriptionTopic.DBHandle = handle;
return subscriptionTopic;
}
}
[DataContract(Name = "SubscriptionData", Namespace = "http://CName.GlobalService")]
[KnownType(typeof(List<SubscriptionTopicInfo>))]
[Serializable]
public class SubscriptionDataContracts : IExtensibleDataObject
{
private ExtensionDataObject extensionDataObjectValue;
[DataMember]
public string UserID
{
get;
set;
}
[DataMember]
public string ProjectID
{
get;
set;
}
[DataMember]
public string FromDiscipline
{
get;
set;
}
[DataMember]
public string ModuleID
{
get;
set;
}
[DataMember]
public string SessionID
{
get;
set;
}
[DataMember]
public List<SubscriptionTopicInfo> TopicList
{
get;
set;
}
public ExtensionDataObject ExtensionData
{
get
{
return extensionDataObjectValue;
}
set
{
extensionDataObjectValue = value;
}
}
}
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.