I can't figure out why BeforeSaveEntity() is not being called when I save my new comments. The comments are saved to the database but the fields that I modify on the server are not being updated. Break points in the BeforeSaveEntity function are not hit. SaveChanges() is run.
//server controller
public class LeaseRepository : EFContextProvider<LeaseEntities>
{
public LeaseRepository(IPrincipal user)
{
//
}
protected override bool BeforeSaveEntity(EntityInfo entityInfo)
{
var entity = entityInfo.Entity;
if (entity is LeaseComment)
{
return BeforeSaveComment(entity as LeaseComment, entityInfo);
}
return base.BeforeSaveEntity(entityInfo);
}
private bool BeforeSaveComment(LeaseComment c, EntityInfo info)
{
// c.Comment = "server comment!";
if (info.EntityState == EntityState.Added)
{
c.UserId = AgentId;// AdName;
c.CreatedOn = DateTime.UtcNow.ToLocalTime();
}
return true;
}
private readonly EFContextProvider<LeaseEntities>
_contextProvider = new EFContextProvider<LeaseEntities>();
private LeaseEntities Context { get { return _contextProvider.Context; } }
public string Metadata
{
get { return _contextProvider.Metadata(); }
}
public SaveResult SaveChanges(JObject saveBundle)
{
return _contextProvider.SaveChanges(saveBundle);
}
}
Deleting these two functions fixed it.
public string Metadata
{
get { return _contextProvider.Metadata(); }
}
public SaveResult SaveChanges(JObject saveBundle)
{
return _contextProvider.SaveChanges(saveBundle);
}
I'm guessing the SaveChanges() was the problem.
Related
I want to filter Listview by Searchview
I use the following Adapter for the filter and it works if I haven't made any new additions to the adapter
When I add a new item to Listview, the search stops completely until I restart the program after adding, modifying or deleting it
full code
adapter class
Do you want to achieve the result like following GIF?
If you want to add the item to the listview, based on your adapter, you should item in the adapter like following code.
public class TableItemAdapter : BaseAdapter<TableItem>, IFilterable
{
public List<TableItem> _originalData;
public List<TableItem> _items;
private readonly Activity _context;
public TableItemAdapter(Activity activity, IEnumerable<TableItem> tableitems)
{
_items = tableitems.ToList();
_context = activity;
Filter = new TableItemFilter(this);
}
//Add data to the `_items`, listview will be updated, if add data in the activity,
//there are two different lists, so listview will not update.
public void AddData(TableItem tableItem)
{
_items.Add(tableItem);
NotifyDataSetChanged();
}
public override TableItem this[int position]
{
get { return _items[position]; }
}
public Filter Filter { get; private set; }
public override int Count
{
get { return _items.Count; }
}
public override long GetItemId(int position)
{
return position;
}
public override View GetView(int position, View convertView, ViewGroup parent)
{
var item = _items[position];
View view = convertView;
if (view == null) // no view to re-use, create new
view = convertView ?? _context.LayoutInflater.Inflate(Resource.Layout.TableItem, null);
//view = _context.LayoutInflater.Inflate(Resource.Layout.TableItem, null);
view.FindViewById<TextView>(Resource.Id.Text1).Text = item.Heading;
view.FindViewById<TextView>(Resource.Id.Text2).Text = item.SubHeading;
return view;
}
public override void NotifyDataSetChanged()
{
// this.NotifyDataSetChanged();
base.NotifyDataSetChanged();
}
}
public class TableItemFilter :Filter
{
private readonly TableItemAdapter _adapter;
public TableItemFilter(TableItemAdapter adapter)
{
_adapter = adapter;
}
protected override FilterResults PerformFiltering(ICharSequence constraint)
{
var returnObj = new FilterResults();
var results = new List<TableItem>();
if (_adapter._originalData == null)
_adapter._originalData = _adapter._items;
if (constraint == null) return returnObj;
if (_adapter._originalData != null && _adapter._originalData.Any())
{
results.AddRange(
_adapter._originalData.Where(
item => item.SubHeading.ToLower().Contains(constraint.ToString()) | item.Heading.ToLower().Contains(constraint.ToString())));
}
returnObj.Values = FromArray(results.Select(r => r.ToJavaObject()).ToArray());
returnObj.Count = results.Count;
constraint.Dispose();
return returnObj;
}
protected override void PublishResults(ICharSequence constraint, FilterResults results)
{
using (var values = results.Values)
_adapter._items = values.ToArray<Java.Lang.Object>().Select(r => r.ToNetObject<TableItem>()).ToList();
_adapter.NotifyDataSetChanged();
// Don't do this and see GREF counts rising
constraint.Dispose();
results.Dispose();
}
}
public class JavaHolder : Java.Lang.Object
{
public readonly object Instance;
public JavaHolder(object instance)
{
Instance = instance;
}
}
public static class ObjectExtensions
{
public static TObject ToNetObject<TObject>(this Java.Lang.Object value)
{
if (value == null)
return default(TObject);
if (!(value is JavaHolder))
throw new InvalidOperationException("Unable to convert to .NET object. Only Java.Lang.Object created with .ToJavaObject() can be converted.");
TObject returnVal;
try { returnVal = (TObject)((JavaHolder)value).Instance; }
finally { value.Dispose(); }
return returnVal;
}
public static Java.Lang.Object ToJavaObject<TObject>(this TObject value)
{
if (Equals(value, default(TObject)) && !typeof(TObject).IsValueType)
return null;
var holder = new JavaHolder(value);
return holder;
}
}
}
Then in the activity, you add the data by adapter.
private void Button1_Click(object sender, System.EventArgs e)
{
tableItemAdapter.AddData(new TableItem() { Heading = "test1222", SubHeading = "sub Test" });
}
Here is my demo, you can download it.
https://github.com/851265601/Xamarin.Android_ListviewSelect/blob/master/XAListViewSearchDemo.zip
my code:
public class StateManagementController : Controller
{
public void OwnerTest()
{
if (Session["Owner"] == null)
{
Logowanie();
}
}
public ActionResult Logowanie()
{
return RedirectToAction("Log", "Owner");
}
}
public class AnimalController : StateManagementController
{
public ActionResult MyAnimals()
{
OwnerTest();
//some code here
return View(animals.ToList());
}
}
The problem is that even if the session is null and Redirect is reached it doesn't redirect me but it still goes to ,,some code" in MyAnimals action, how can I stop it in ActionResult Logowanie? i dont want to change code in MyAnimals, I want only to use function there without checking if it returns something.
You Logowanie Action may return an ActionResult but the OwnerTest method ignores the returned result. Try this:
public class StateManagementController : Controller
{
public ActionResult OwnerTest()
{
if (Session["Owner"] == null)
{
return Logowanie();
}
else
{
return null;
}
}
public ActionResult Logowanie()
{
return RedirectToAction("Log", "Owner");
}
public class AnimalController : StateManagementController
{
public ActionResult MyAnimals()
{
var temp = OwnerTest();
if (temp != null)
{
return temp;
}
else
{
//some code here
return View(animals.ToList());
}
}
}
I've got a special problem with binding data to an itemsource of an mvxtablieviewsource.
I'm trying to generate a list of favorites, which are generated in the core by clicking on a different tablview.
Normally I get the databinding working like this: (Just basic structure)
controller:
var source = new MySource(TableView);
this.AddBindings(new Dictionary<object, string>
{
{source, "ItemsSource Favs"}
});
Source:
private List<FavModel> _favs;
public override IEnumerable ItemsSource
{
get { return _favs; }
set
{
_favs = (List<FavModel>)value;
ReloadTableData();
}
}
protected override UITableViewCell GetOrCreateCellFor(UITableView tableView, NSIndexPath indexPath, object item)
{
var cell = new AdFavCell();
cell.TextLabel.Text = ((FavModel)item).Display;
return cell;
}
Normally it works really great but no in this case where i generate the data by reacting on users touch, I've got this strange failure;
When I set a breakpoint in the setter of the ItemsSource, and wait for a while then it works correctly.
When I run without a breakpoint the tableview keeps empty.
I also figured out that if I insert a manually pause in the setter then it works too:
Setter with pause:
public override IEnumerable ItemsSource
{
get { return _mydata; }
set
{
_favs = (List<FavModel>)value;
ReloadTableData();
Task.Delay(1000).Wait();
}
}
I also tried to do a delaybinding, but it didn't work.
Have anyone an idea where the problem is?
Edit:
Here some additional Information:
How the Data is generated:
I've got a tableview with content and depending on a longclick on a cell, I create a popumenu where you can add your favorites.
Detecting the longclick:
protected override UITableViewCell GetOrCreateCellFor(UITableView tableView, NSIndexPath indexPath, object item)
{
MvxTableViewCell cell = null;
if (item is SoccerEventListModel)
{
cell = tableView.DequeueReusableCell(this.CellIdentifier) as SoccerEvent;
if (cell == null)
{
cell = new SoccerEvent((SoccerEventListModel)item);
cell.AddGestureRecognizer(new UILongPressGestureRecognizer((e) =>
{
if (e.State == UIGestureRecognizerState.Began)
{
var command = ItemLongClickCommand;
if (command != null)
command.Execute(item);
}
}));
return cell;
}
}
}
Binding the Longclick to the core:
EventListViewModel.EventFavViewCallbackEvent += EventListViewModel_EventFavViewCallbackEvent;
void EventListViewModel_EventFavViewCallbackEvent(EventModel e)
{
var StoreFav = new EventFavoritesView { ViewModel = new EventFavoritesViewModel { ID = e.ID } };
View.Add(StoreFav.View);
}
Depending on the ID of the cell, it creates the list of the favorites by sending a request to our server.
Update:
private long _id;
public long ID
{
get { return _id; }
set { _id = value; RaisePropertyChanged(() => ID); Update(); }
}
When the data is received a RaisePropertyChanged() should make the view to reload its content.
private List<FavModel> _favs;
public List<FavModel> Favs
{
get { return _favs; }
set { _favs = value; RaisePropertyChanged(() => Favs); }
}
ViewModel:
public class EventFavoritesViewModel : MvxViewModel
{
private readonly EventFavoritesService _eventFavoriteService;
private readonly UserFavoritesService _userFavoriteService;
private long _id;
public long ID
{
get { return _id; }
set { _id = value; RaisePropertyChanged(() => ID); Update(); }
}
private string _title;
public string Title
{
get { return _title; }
set { _title = value; RaisePropertyChanged(() => Title); }
}
private List<FavModel> _favs;
public List<FavModel> Favs
{
get { return _favs; }
set { _favs = value; RaisePropertyChanged(() => Favs); }
}
private MvxCommand<FavModel> _itemSelectedCommand;
public System.Windows.Input.ICommand ItemSelectedCommand
{
get
{
_itemSelectedCommand = _itemSelectedCommand ?? new MvxCommand<FavModel>(ToggleFav);
return _itemSelectedCommand;
}
}
public void Init(long eventID)
{
MvxTrace.Trace("We get the details", Logger.Errorlevel.Debug);
ID = eventID;
}
public EventFavoritesViewModel()
{
_eventFavoriteService = new EventFavoritesService(UpdateEventFav);
_userFavoriteService = new UserFavoritesService(UpdateUserFav);
}
private void UpdateUserFav(Fav[] favlist)
{
MvxMessenger.Publish(new UserFavUpdateMessage(this, favlist));
}
private void Update()
{
Favs = _eventFavoriteService.GetFavforEvent(ID).MapToFavs();
}
private void UpdateEventFav(Fav[] favlist)
{
Favs = favlist.MapToFavs();
}
private void ToggleFav(FavModel item)
{
MvxTrace.Trace("Got Item: " + item.Display);
item.NewSubscription = !item.NewSubscription;
}
private IMvxMessenger MvxMessenger
{
get
{
return Mvx.Resolve<IMvxMessenger>();
}
}
public void SaveFavs()
{
foreach (var fav in Favs)
{
if (fav.AlreadySubscribed != fav.NewSubscription)
{
if (fav.NewSubscription)
_userFavoriteService.PutToUserFavorites(fav.MapToFav());
else
_userFavoriteService.DeleteFromUserFavorites(fav.MapToFav());
}
}
}
}
I hope this is enough information, otherwise just tell me.:-)
Thanks for any help.
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()
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;
}
// ...
}