The query results cannot be enumerated more than once, MVC WebGrid issue - asp.net-mvc

Error:
System.InvalidOperationException: The query results cannot be enumerated more than once.
Code:
Controller:
namespace EmployeeAttendance_app.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Precise Technology Consultants";
var DataContext = new EmployeeAtdDataContext();
//var EmployeeAtd = DataContext.GetAttendance_Sp();
IEnumerable<GetAttendance_SpResult> EmployeeAtd = DataContext.GetAttendance_Sp();
return View(EmployeeAtd);
}
View:
#using EmployeeAttendance_app.Models
<div>
#{
var grid = new WebGrid(Model, defaultSort: "EmplID");
}
#grid.GetHtml()
</div>
Models:
#pragma warning disable 1591
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.237
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace EmployeeAttendance_app.Models
{
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data;
using System.Collections.Generic;
using System.Reflection;
using System.Linq;
using System.Linq.Expressions;
using System.ComponentModel;
using System;
[global::System.Data.Linq.Mapping.DatabaseAttribute(Name="a1")]
public partial class EmployeeAtdDataContext : System.Data.Linq.DataContext
{
private static System.Data.Linq.Mapping.MappingSource mappingSource = new AttributeMappingSource();
#region Extensibility Method Definitions
partial void OnCreated();
#endregion
public EmployeeAtdDataContext() :
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["a1ConnectionString"].ConnectionString, mappingSource)
{
OnCreated();
}
public EmployeeAtdDataContext(string connection) :
base(connection, mappingSource)
{
OnCreated();
}
public EmployeeAtdDataContext(System.Data.IDbConnection connection) :
base(connection, mappingSource)
{
OnCreated();
}
public EmployeeAtdDataContext(string connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public EmployeeAtdDataContext(System.Data.IDbConnection connection, System.Data.Linq.Mapping.MappingSource mappingSource) :
base(connection, mappingSource)
{
OnCreated();
}
public System.Data.Linq.Table<EmployeeAtd> EmployeeAtds
{
get
{
return this.GetTable<EmployeeAtd>();
}
}
[global::System.Data.Linq.Mapping.FunctionAttribute(Name="dbo.GetAttendance_Sp")]
public ISingleResult<GetAttendance_SpResult> GetAttendance_Sp()
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return ((ISingleResult<GetAttendance_SpResult>)(result.ReturnValue));
}
}
[global::System.Data.Linq.Mapping.TableAttribute(Name="dbo.V_EmployeeAtd")]
public partial class EmployeeAtd
{
private string _EmplID;
private string _EmplName;
private string _RecDate;
private string _RecTime;
private string _DeptName;
public EmployeeAtd()
{
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmplID", DbType="Char(8) NOT NULL", CanBeNull=false)]
public string EmplID
{
get
{
return this._EmplID;
}
set
{
if ((this._EmplID != value))
{
this._EmplID = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmplName", DbType="NVarChar(40) NOT NULL", CanBeNull=false)]
public string EmplName
{
get
{
return this._EmplName;
}
set
{
if ((this._EmplName != value))
{
this._EmplName = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_RecDate", DbType="Char(10)")]
public string RecDate
{
get
{
return this._RecDate;
}
set
{
if ((this._RecDate != value))
{
this._RecDate = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_RecTime", DbType="Char(5)")]
public string RecTime
{
get
{
return this._RecTime;
}
set
{
if ((this._RecTime != value))
{
this._RecTime = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DeptName", DbType="NVarChar(50)")]
public string DeptName
{
get
{
return this._DeptName;
}
set
{
if ((this._DeptName != value))
{
this._DeptName = value;
}
}
}
}
public partial class GetAttendance_SpResult
{
private string _EmplID;
private string _EmplName;
private string _RecDate;
private string _RecTime;
private string _DeptName;
public GetAttendance_SpResult()
{
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmplID", DbType="Char(8) NOT NULL", CanBeNull=false)]
public string EmplID
{
get
{
return this._EmplID;
}
set
{
if ((this._EmplID != value))
{
this._EmplID = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmplName", DbType="NVarChar(40) NOT NULL", CanBeNull=false)]
public string EmplName
{
get
{
return this._EmplName;
}
set
{
if ((this._EmplName != value))
{
this._EmplName = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_RecDate", DbType="Char(10)")]
public string RecDate
{
get
{
return this._RecDate;
}
set
{
if ((this._RecDate != value))
{
this._RecDate = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_RecTime", DbType="Char(5)")]
public string RecTime
{
get
{
return this._RecTime;
}
set
{
if ((this._RecTime != value))
{
this._RecTime = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DeptName", DbType="NVarChar(50) NOT NULL", CanBeNull=false)]
public string DeptName
{
get
{
return this._DeptName;
}
set
{
if ((this._DeptName != value))
{
this._DeptName = value;
}
}
}
}
}
#pragma warning restore 1591
I'm newbie to MVC 3 and Linq to SQL, trying to display data in GRID using WebGrid class but getting error. I have used Linq to Sql class and dropped SP and table into it.

Change you View to accept list of GetAttendance_SpResult bcoz you are passing this model from your controller
#model IEnumerable<GetAttendance_SpResult>

Try converting ur IEnumerable to List. because When you use .ToList() on IEnumerable, all the items in the IEnumerable saved as a List. and when u work with IEnumerable item is accessed from your database
#{
var grid = new WebGrid(Model.ToList(), defaultSort: "EmplID");
}
#grid.GetHtml()

Related

Cannot implicitly convert type 'Note6MVCApplication5.Models.SPGetEmpDetailsByEmpIdJoinResult' to 'Note6MVCApplication5.Models.Emp'

public ActionResult Edit(int? id)
{
Emp emp = db.SPGetEmpDetailsByEmpIdJoin(id).SingleOrDefault();
ViewData["DeptId"] = new SelectList(db.SPGetAllDeptDetails().ToList(), "DeptId", "DeptName", emp.DeptId);
return View(emp);
}
Error : Cannot implicitly convert type 'Note6MVCApplication5.Models.SPGetEmpDetailsByEmpIdJoinResult' to 'Note6MVCApplication5.Models.Emp'
Why this error is coming?
I am posting definition of SPGetEmpDetailsByEmpIdJoinResult() which is present in MVCDemoDB.Designer.cs
public partial class SPGetEmpDetailsByEmpIdJoinResult
{
private int _EmpId;
private string _EmpName;
private string _EmpJob;
private decimal _EmpSalary;
private int _DeptId;
private string _DeptName;
public SPGetEmpDetailsByEmpIdJoinResult()
{
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmpId", DbType="Int NOT NULL")]
public int EmpId
{
get
{
return this._EmpId;
}
set
{
if ((this._EmpId != value))
{
this._EmpId = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmpName", DbType="VarChar(50) NOT NULL", CanBeNull=false)]
public string EmpName
{
get
{
return this._EmpName;
}
set
{
if ((this._EmpName != value))
{
this._EmpName = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmpJob", DbType="VarChar(50) NOT NULL", CanBeNull=false)]
public string EmpJob
{
get
{
return this._EmpJob;
}
set
{
if ((this._EmpJob != value))
{
this._EmpJob = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_EmpSalary", DbType="Money NOT NULL")]
public decimal EmpSalary
{
get
{
return this._EmpSalary;
}
set
{
if ((this._EmpSalary != value))
{
this._EmpSalary = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DeptId", DbType="Int NOT NULL")]
public int DeptId
{
get
{
return this._DeptId;
}
set
{
if ((this._DeptId != value))
{
this._DeptId = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage="_DeptName", DbType="VarChar(50) NOT NULL", CanBeNull=false)]
public string DeptName
{
get
{
return this._DeptName;
}
set
{
if ((this._DeptName != value))
{
this._DeptName = value;
}
}
}
}
It seems to be Type Cast Error. i would suggest declare variable of type 'var' instead of Emp in below statement
Emp emp = db.SPGetEmpDetailsByEmpIdJoin(id).SingleOrDefault();
to something like this
var emp = db.SPGetEmpDetailsByEmpIdJoin(id).SingleOrDefault();
second approach
Define extension method to cast SPGetEmpDetailsByEmpIdJoinResult to Emp some thing like below
sample Emp class
public class Emp
{
public int DeptId { get; set; }
public int EmpId { get; set; }
/*
* define other properties
*/
}
public static Emp ToEmp(this SPGetEmpDetailsByEmpIdJoinResult empResult)
{
return new Emp() {EmpId = empResult.EmpId, DeptId = empResult.DeptId};
}
and call the extension method
Emp emp = db.SPGetEmpDetailsByEmpIdJoin(id).SingleOrDefault().ToEmp();
that would fix your issue. hope this helps :)

Listview Filter with SearchView Using Base Adapter in Xamarin android Error

I am try to filter listview with searchview using Base Adapter in in xamarin Android, My listView Bind in sql server using restfull web service i am stuck in PublishResults which is given an error
Here Is My Code:-
GetHospNames.cs
public class GetHospNames
{
public string HospID { get; set; }
public string HospName { get; set; }
public GetHospNames(string HospID, string HospName)
{
this.HospID = HospID;
this.HospName = HospName;
//this.HospLogo = HospLogo;
}
}
ContListViewHospNameClass.cs
using System.Collections.Generic;
using Android.App;
using Android.Views;
using Android.Widget;
using System;
using Android.Graphics;
using Android.Graphics.Drawables;
using System.IO;
using Android.Content;
using Java.Lang;
using Android.Text;
using Java.Util;
using Oject = Java.Lang.Object;
namespace HSAPP
{
public class ContListViewHospNameClass : BaseAdapter<GetHospNames>, IFilterable
{
public List<GetHospNames> objList;
Activity objActivity;
List<GetHospNames> filterList;
public ContListViewHospNameClass(Activity objMyAct, List<GetHospNames> objMyList) : base()
{
this.objActivity = objMyAct;
objList = objMyList;
this.filterList = objList;
Filter = new CustomFilter(this);
}
public override GetHospNames this[int position]
{
get
{
return objList[position];
}
}
public override int Count
{
get
{
return objList.Count;
}
}
public Filter Filter { get; set; }
public override void NotifyDataSetChanged()
{
base.NotifyDataSetChanged();
}
//This is Inner Class
public class CustomFilter : Filter
{
ContListViewHospNameClass CustomAdapter;
public CustomFilter(ContListViewHospNameClass adapter) : base()
{
this.CustomAdapter = adapter;
}
protected override FilterResults PerformFiltering(ICharSequence constraint)
{
FilterResults result = new FilterResults();
if (constraint != null && constraint.Length() > 0)
{
//Contraint To Upper
List<GetHospNames> filter = new List<GetHospNames>();
foreach (GetHospNames name in CustomAdapter.objList)
{
if (name.HospName.ToUpper().Contains(constraint.ToString().ToUpper()))
{
filter.Add(name);
}
}
Oject[] Name;
Name = new Oject[filter.Count];
for (int i = 0; i < filter.Count; i++)
{
Name[i] = filter[i].HospName.ToString();
}
result.Count = filter.Count;
result.Values = Name;
}
return result;
}
protected override void PublishResults(ICharSequence constraint, Filter.FilterResults result)
{
List<GetHospNames> filteredList = new List<GetHospNames>();
for (int i = 0; i < ((Oject[])result.Values).Length; i++)
{
filteredList.Add((Oject[])result.Values[i]);//Here Is An Error *****Cannot apply indexing with [] to an expression of type 'Object'****
}
CustomAdapter.objList = filteredList;
CustomAdapter.NotifyDataSetChanged();
}
}
public override long GetItemId(int position)
{
return position;
}
public Bitmap getBitmap(byte[] getByte)
{
if (getByte.Length != 0)
{
return BitmapFactory.DecodeByteArray(getByte, 0, getByte.Length);
}
else
{
return null;
}
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = objList[position];
if (convertView == null)
{
convertView = objActivity.LayoutInflater.Inflate(Resource.Layout.ContListViewHospName, null);
}
convertView.FindViewById<TextView>(Resource.Id.tvHospID).Text = item.HospID;
convertView.FindViewById<TextView>(Resource.Id.tvHospName).Text = item.HospName;
return convertView;
}
}
public static class ObjectTypeHelper
{
public static T Cast<T>(this Java.Lang.Object obj) where T : class
{
var propertyInfo = obj.GetType().GetProperty("Instance");
return propertyInfo == null ? null : propertyInfo.GetValue(obj, null) as T;
}
}
}
This is my MainActivity Code
private void BindControl_BindHospCompleted(object sender, BindControl.BindHospCompletedEventArgs e)
{
jsonValue = e.Result.ToString();
try
{
if (jsonValue == null)
{
Toast.MakeText(this, "No Data For Bind", ToastLength.Long).Show();
return;
}
JArrayValue = JArray.Parse(jsonValue);
list = new List<GetHospNames>();
int count = 0;
while (count < JArrayValue.Count)
{
GetHospNames getHospName = new GetHospNames(JArrayValue[count]["HospID"].ToString(), JArrayValue[count]["HospName"].ToString());
list.Add(getHospName);
count++;
}
if (count == 0)
{
Toast.MakeText(this, "No List Of Hospitals", ToastLength.Long).Show();
}
adapter = new ContListViewHospNameClass(this, list);
listView.Adapter = adapter;
search.QueryTextChange += (s, e) =>
{
adapter.Filter.InvokeFilter(e.NewText);
};
listView.ItemClick += ListView_ItemClick;
pBar.Dismiss();
}
catch (Java.Lang.Exception ex)
{
pBar.Dismiss();
//Toast.MakeText(this, ex.ToString(), ToastLength.Long).Show();
Finish();
Intent intent = new Intent(this, typeof(ChkIntConnActivity));
StartActivity(intent);
}
}
Please Help...Thank You

Mvvmcross MvxSimpleTableViewSource Binding

I'm trying to create custom cells for my MvxTableViewController as showed in Stuart Lodge videos N=3 & N=6.5 but it fails to bind data.
Here the working version (the one with basic cells)
using Cirrious.MvvmCross.Binding.BindingContext;
using Cirrious.MvvmCross.Binding.Touch.Views;
using Cirrious.MvvmCross.Touch.Views;
using Cirrious.MvvmCross.ViewModels;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using Next.Client.Application.Core.Entities.Observations;
using Next.Client.Application.Core.ViewModels;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace Next.Client.Application.iOS.Views
{
[Register("ObsSearchView")]
public partial class ObsSearchView : MvxTableViewController
{
public static readonly NSString CellIdentifier = new NSString("ObservationCell");
public ObsSearchView()
{
}
public ObsSearchView(IntPtr handle)
: base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Request = new MvxViewModelRequest<ObsSearchViewModel>(null, null, new MvxRequestedBy());
LoadData();
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
Title = NSBundle.MainBundle.LocalizedString("Liste Observations", "Liste Observations");
}
public override void ViewWillDisappear(bool animated)
{
Title = NSBundle.MainBundle.LocalizedString("Back", "Liste Observations");
base.ViewDidDisappear(animated);
}
public void LoadData()
{
var source = new MvxStandardTableViewSource(
TableView,
UITableViewCellStyle.Subtitle,
CellIdentifier,
"TitleText BrutText; DetailText DateTimeHuman",
UITableViewCellAccessory.DisclosureIndicator
);
TableView.Source = source;
var set = this.CreateBindingSet<ObsSearchView, Core.ViewModels.ObsSearchViewModel>();
set.Bind(source).To(vm => vm.Observations);
set.Bind(source).For(s => s.SelectionChangedCommand).To(vm => vm.SelectedObsCommand);
set.Apply();
TableView.ReloadData();
}
}
}
and here the modified version to add custom cells:
using Cirrious.MvvmCross.Binding.BindingContext;
using Cirrious.MvvmCross.Binding.Touch.Views;
using Cirrious.MvvmCross.Touch.Views;
using Cirrious.MvvmCross.ViewModels;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using Next.Client.Application.Core.Entities.Observations;
using Next.Client.Application.Core.ViewModels;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
namespace Next.Client.Application.iOS.Views
{
[Register("ObsSearchView")]
public partial class ObsSearchView : MvxTableViewController
{
public static readonly NSString CellIdentifier = new NSString("ObservationCell");
public ObsSearchView()
{
}
public ObsSearchView(IntPtr handle)
: base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
Request = new MvxViewModelRequest<ObsSearchViewModel>(null, null, new MvxRequestedBy());
LoadData();
}
public override void ViewWillAppear(bool animated)
{
base.ViewWillAppear(animated);
Title = NSBundle.MainBundle.LocalizedString("Liste Observations", "Liste Observations");
}
public override void ViewWillDisappear(bool animated)
{
Title = NSBundle.MainBundle.LocalizedString("Back", "Liste Observations");
base.ViewDidDisappear(animated);
}
public void LoadData()
{
var source = new MvxSimpleTableViewSource(
TableView,
ObservationCell.Key,
ObservationCell.Key
);
TableView.Source = source;
TableView.ReloadData();
}
}
}
with the custom cell class
using System;
using System.Drawing;
using MonoTouch.Foundation;
using MonoTouch.UIKit;
using Cirrious.MvvmCross.Binding.Touch.Views;
using Cirrious.MvvmCross.Binding.BindingContext;
using Next.Client.Application.Core.ViewModels;
using Next.Client.Application.Core.Entities.Observations;
namespace Next.Client.Application.iOS
{
public partial class ObservationCell : MvxTableViewCell
{
public static readonly UINib Nib = UINib.FromName ("ObservationCell", NSBundle.MainBundle);
public static readonly NSString Key = new NSString ("ObservationCell");
public ObservationCell (IntPtr handle) : base (handle)
{
this.DelayBind(() => {
var set = this.CreateBindingSet<ObservationCell, Observation>();
set.Bind(MainLbl).To(observation => observation.BrutText);
set.Bind(SubLeftLbl).To(observation => observation.DateTimeHuman);
set.Bind(SubRightLbl).To(observation => observation.Praticien.Personne.DisplayFullName);
set.Apply();
});
}
public static ObservationCell Create ()
{
return (ObservationCell)Nib.Instantiate (null, null) [0];
}
}
}
and finally the Observation entity
using Next.Client.Application.Core.Helpers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using Next.Client.Application.Core.Entities;
using System.Globalization;
namespace Next.Client.Application.Core.Entities.Observations
{
public class Observation : Entity
{
#region Constructors
#endregion
#region Constantes
private readonly List<String> _month = new List<String>{
"",
"jan.",
"fev.",
"mars",
"avr.",
"mai",
"juin",
"jui.",
"aout",
"sep.",
"oct.",
"nov.",
"dec."
};
#endregion
#region Simple Properties
#region Foreign keys
private int _praticienId;
public int PraticienId
{
get { return _praticienId; }
set { _praticienId = value; OnPropertyChange(() => PraticienId); }
}
private int _sejourId;
public int SejourId
{
get { return _sejourId; }
set { _sejourId = value; OnPropertyChange(() => SejourId); }
}
private int _categoryId;
public int CategoryId
{
get { return _categoryId; }
set { _categoryId = value; OnPropertyChange(() => CategoryId); }
}
#endregion
private DateTime _dateTime;
public DateTime DateTime
{
get { return _dateTime; }
set { _dateTime = value; OnPropertyChange(() => DateTime); OnPropertyChange(() => DateTimeHuman); }
}
public String DateTimeHuman
{
get
{
CultureInfo culture = new CultureInfo("fr-FR");
return DateTime.ToString("f", culture);
}
}
public string DisplayDateTime
{
get { return string.Format("{0} {1} {2} {3}h{4:00}", _dateTime.Day, _month[_dateTime.Month], _dateTime.Year, _dateTime.Hour, _dateTime.Minute); }
}
private int _status;
public int Status
{
get { return _status; }
set { _status = value; OnPropertyChange(() => Status); }
}
private int _type;
public int Type
{
get { return _type; }
set { _type = value; OnPropertyChange(() => Type); }
}
private bool _private;
public bool Private
{
get { return _private; }
set { _private = value; OnPropertyChange(() => Private); OnPropertyChange(() => DisplayPrivacy); }
}
public string DisplayPrivacy
{
get { if (_private) return "OUI"; else return "NON"; }
}
private string _brutText;
public string BrutText
{
get { return _brutText; }
set { _brutText = value; OnPropertyChange(() => BrutText); }
}
#endregion
#region Navigation Properties
private Praticien _praticien;
public Praticien Praticien
{
get { return _praticien; }
set
{
Praticien old = _praticien;
_praticien = value;
CollectionHelper.ManyToOne(this, old, value, _GetManyToOneCollection);
OnPropertyChange(() => Praticien);
}
}
private Sejour _sejour;
public Sejour Sejour
{
get { return _sejour; }
set
{
Sejour old = _sejour;
_sejour = value;
CollectionHelper.ManyToOne(this, old, value, _GetManyToOneCollection);
OnPropertyChange(() => Sejour);
}
}
private Category _category;
public Category Category
{
get { return _category; }
set
{
Category old = _category;
_category = value;
CollectionHelper.ManyToOne(this, old, value, _GetManyToOneCollection);
OnPropertyChange(() => Category);
}
}
private ObservableCollection<BinaryObservation> _datas;
public ObservableCollection<BinaryObservation> Datas
{
get
{
if (_datas == null)
{
_datas = new ObservableCollection<BinaryObservation>();
CollectionHelper.OneToMany(this, _GetOneToMany, _SetOneToMany, _datas);
}
return _datas;
}
set { _datas = value; OnPropertyChange(() => Datas); }
}
#endregion
#region Association Fixup
private static ObservableCollection<Observation> _GetManyToOneCollection(Sejour sejour)
{
return sejour.Observations;
}
private static ObservableCollection<Observation> _GetManyToOneCollection(Category category)
{
return category.Observations;
}
private static ObservableCollection<Observation> _GetManyToOneCollection(Praticien praticien)
{
return praticien.Observations;
}
#region binary observation (datas)
private static Observation _GetOneToMany(BinaryObservation binaryObservation)
{
return binaryObservation.Observation;
}
private static void _SetOneToMany(BinaryObservation binaryObservation, Observation observation)
{
binaryObservation.Observation = observation;
}
#endregion
#endregion
}
}
when I build I get no error and I can run the debugger without errors either, but when using the custom cells nothing show up, so it seems the binding isn't done the right way.
Thanks for your time
In your modified ObsView you are never actually binding the ItemsSource for TableSource - so the table source doesn't know what collection to show
In the N+1 3 Kittens tutorial this is done using:
var set = this.CreateBindingSet<FirstView, FirstViewModel>();
set.Bind(source).To(vm => vm.Kittens);
set.Apply();
See https://github.com/MvvmCross/NPlus1DaysOfMvvmCross/blob/master/N-03-KittenView_Mac/KittenView.Touch/Views/FirstView.cs#L24
Similarly, in N=6:
var set = this.CreateBindingSet<FirstView, Core.ViewModels.FirstViewModel>();
// ...
set.Bind(source).To(vm => vm.Results);
// ...
set.Apply();
See https://github.com/MvvmCross/NPlus1DaysOfMvvmCross/blob/master/N-07-BooksPlus/Books.Touch/Views/FirstView.cs#L45

asp.net mvc 3 dependency injection ninject

I want to ask something about asp.net mvc 3 dependency injection ninject.
Here is my Interface,
public interface IRegistration<T>
{
bool Registration(T Entity);
}
This is ClsMembers class.
public class ClsMembers:IRegistration<Member>
{
private SmileWorkDbEntities db;
public ClsMembers()
{
db = new SmileWorkDbEntities();
}
public bool Registration(Member member)
{
db.Members.Add(member);
if (db.SaveChanges() != 0)
{
return true;
}
else
{
return false;
}
}
public int GetMemberId(string username, string pwd)
{
var Mem = (from m in db.Members where m.Member_username == username && m.Member_password == pwd select m).FirstOrDefault();
return Mem.Member_id;
}
}
here is my controller,
public class MembersRegistrationController : Controller
{
IRegistration<Member> ireg1;
public MembersRegistrationController(IRegistration<Member> _ireg1)
{
ireg1 = _ireg1;
}
public ActionResult MemberRegistration()
{
return View();
}
[HttpPost]
public ActionResult MemberRegistration(Member m)
{
if(ireg1.Registration(m))
{
return RedirectToAction("MemberProfileRegistration", new {mId = i });
}
else
{
return View();
}
}
}
Everything is ok... but i cannot access GetMemberId() method.. pls tell me how can i access GetMemberId() from my controller...
Regard,
MinThitTun
Modify your IRegistration interface by adding int GetMemberId(string username, string pwd) method:
public interface IRegistration<T>
{
bool Registration(T Entity);
int GetMemberId(string username, string pwd);
}
After all, I thing you should read Interfaces (C# Programming Guide)
UPDATE:
public interface IMembersRepository
{
int GetMemberId(string username, string password);
// Other stuff related to members...
}
public class MembersRepository : IMembersRepository
{
private SmileWorkDbEntities db = new SmileWorkDbEntities();
public int GetMemberId(string username, string password)
{
var Mem = (from m in db.Members where m.Member_username == username && m.Member_password == pwd select m).FirstOrDefault();
return Mem.Member_id;
}
// Other stuff related to members...
}
public class MembersRegistrationController : Controller
{
IRegistration<Member> ireg1;
IMembersRepository membersRepository;
public MembersRegistrationController(IRegistration<Member> _ireg1, IMembersRepository memRepository)
{
ireg1 = _ireg1;
membersRepository = memRepository;
}
// ...
}

Web api HTTP 500 (Internal Server Error)

Hello I have an error 500 (internal server error) when I run the code below. My issue is that I have no trace at all of the error. It seems that visual studio is unable to catch it.
The following code returns a Candidate if I try to add pers to candidate the code fail and i get error 500. The thing is PersonAddressDescription implement AddressDescription is inheritance the problem ?
public class CheckController : ApiController
{
public Candidate Get()
{
PersonAddressDescription pers = new PersonAddressDescription();
Candidate candidate = new Candidate();
//IF I REMOVE THIS NO PROBLEM
candidate.address = pers;
return candidate;
}
}
AddressDescription class
/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(CompanyAddressDescription))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(PersonAddressDescription))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.17626")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.crif-online.ch/webservices/crifsoapservice/v1.00")]
public abstract partial class AddressDescription : object, System.ComponentModel.INotifyPropertyChanged {
private Location locationField;
private ContactItem[] contactItemsField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=0)]
public Location location {
get {
return this.locationField;
}
set {
this.locationField = value;
this.RaisePropertyChanged("location");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("contactItems", Order=1)]
public ContactItem[] contactItems {
get {
return this.contactItemsField;
}
set {
this.contactItemsField = value;
this.RaisePropertyChanged("contactItems");
}
}
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string propertyName) {
System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if ((propertyChanged != null)) {
propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
}
}
}
PersonAddressDescription class that implement AddressDescription
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.17626")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.crif-online.ch/webservices/crifsoapservice/v1.00")]
public partial class PersonAddressDescription : AddressDescription {
private string firstNameField;
private string lastNameField;
private string maidenNameField;
private Sex sexField;
private bool sexFieldSpecified;
private string birthDateField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=0)]
public string firstName {
get {
return this.firstNameField;
}
set {
this.firstNameField = value;
this.RaisePropertyChanged("firstName");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=1)]
public string lastName {
get {
return this.lastNameField;
}
set {
this.lastNameField = value;
this.RaisePropertyChanged("lastName");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=2)]
public string maidenName {
get {
return this.maidenNameField;
}
set {
this.maidenNameField = value;
this.RaisePropertyChanged("maidenName");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=3)]
public Sex sex {
get {
return this.sexField;
}
set {
this.sexField = value;
this.RaisePropertyChanged("sex");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool sexSpecified {
get {
return this.sexFieldSpecified;
}
set {
this.sexFieldSpecified = value;
this.RaisePropertyChanged("sexSpecified");
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute(Order=4)]
public string birthDate {
get {
return this.birthDateField;
}
set {
this.birthDateField = value;
this.RaisePropertyChanged("birthDate");
}
}
}
I suspect that the object you retrieved (addResp) contains circular references somewhere in its object graph. Circular references cannot be JSON serialized.
For example try putting the following code inside your controller to test what happens when you attempt to JSON serialize this instance:
TypeIdentifyAddressResponse addResp = ws.identifyAddress("test");
string json = JsonConvert.SerializeObject(addResp);
UPDATE:
It seems that AddressDescription is an abstract class and your actual instance is PersonAddressDescription. You need to indicate that to the serializer by using the [KnownType] attribute:
[KnownType(typeof(PersonAddressDescription))]
[KnownType(typeof(CompanyAddressDescription))]
...
public abstract partial class AddressDescription : object, System.ComponentModel.INotifyPropertyChanged {
{
...
}
As an alternative if you don't want to further pollute your (already polluted) domain models with other attributes you could also define the known type inside your WebApiConfig.cs:
config.Formatters.XmlFormatter.SetSerializer<Candidate>(
new DataContractSerializer(typeof(Candidate),
new Type[] { typeof(PersonAddressDescription) }));

Resources