Changing an image in a listview - xamarin.android

I'm using the tutorial code at http://redth.info/2010/10/12/monodroid-custom-listadapter-for-your-listview and after modifying the code so that it builds under monodroid 4.2.3, I've extended it so that the list class looks like this
public class Animal
{
public string Name
{
get;
set;
}
public string Description
{
get;
set;
}
public int Image
{
get;
set;
}
public int ImageCheck
{ get; set; }
public bool Checked
{ get; set; }
}
With the ItemClick event code looking like this
// ViewGroup parent = listView;
void listView_ItemClick(object sender, Android.Widget.AdapterView.ItemClickEventArgs e, ViewGroup parent)
{
var item = this.listAdapter.GetItemAtPosition(e.Position);
var view = (e.View ?? this.LayoutInflater.Inflate(Resource.Layout.customlistitem, parent, false)) as LinearLayout;
ImageView iv = FindViewById<ImageView>(Resource.Id.imageChecked);
if (item.Checked == false)
{
item.Checked = true;
item.ImageCheck = Resource.Drawable.#checked;
}
else
{
item.Checked = false;
item.ImageCheck = Resource.Drawable.checkbox;
}
iv.SetImageResource(item.ImageCheck);
}
While this works in so far as if I add in
Console.WriteLine("Animal clicked = {0}", item.Name);
the emulator output will show the name of the animal clicked, the ImageView is always at the top of the list.
Is there a way to have the tick in the correct place (so for example, if I click on the 5th item. the 5th ImageView shows a tick or just a box)?
Thanks

Simplest way
ImageView iv = e.View.FindViewById<ImageView>(Resource.Id.imageChecked);
Job done!

Related

How make default value in ASP.NET MVC

I want to create a default color when I add a new event.
Now the color is set to NULL.
[HttpPost]
public JsonResult SaveEvent(Event e)
{
var status = false;
if (e.EventID > 0)
{
//Update the event
var v = db.Events.Where(a => a.EventID == e.EventID).FirstOrDefault();
if (v != null)
{
v.EventTitle = e.EventTitle;
v.EventDescription = e.EventDescription;
v.ThemeColor = e.ThemeColor;
}
}
else
{
db.Events.Add(e);
}
db.SaveChanges();
status = true;
return new JsonResult { Data = new { status = status } };
}
How make ThemeColor red when I add the event ?
public partial class Event
{
public int EventID { get; set; }
public string EventTitle { get; set; }
public string EventDescription { get; set; }
public Nullable<System.DateTime> StartDate { get; set; }
public Nullable<System.DateTime> EndDate { get; set; }
public string ThemeColor { get; set; }
}
If you use c# 6 or higher, you can use this syntax to set the default value to a property
public string ThemeColor { get; set; } = "Red";
Otherwise you can initialize via constructor.
But if you are explicitly sending the ThemeColor as null in the payload, when invoking the method then you'll need to manually check if ThemeColor is null and set it in the controller
For example:
v.ThemeColor = e.ThemeColor ?? "Red";
EDIT:
You can add the null check on top of the method and with that you'll cover both cases
if(e.ThemeColor == null)
{
e.ThemeColor = "Red";
}

Unable to Auto mapping in sitecore MVC(Razoe VIew) help of glass mapper

Am using controller rendering, I created one model called Footer.cs and it has below properties.
[SitecoreType(TemplateId = "{1044CFB5-2B85-4A8D-9DCC-34764D2AF5B3}", AutoMap = true)]
public class Footer
{
public virtual Item Item { get; set; }
[SitecoreField(FieldName ="Copyright Text First",FieldType = SitecoreFieldType.SingleLineText)]
public virtual string CopyrightTextFirst { get; set; }
[SitecoreField(FieldName ="Copyright Text Last",FieldType = SitecoreFieldType.SingleLineText)]
public virtual string CopyrightTextLast { get; set; }
}
In My Controller:
public ActionResult FooterTemplate()
{
ISitecoreContext ctx = new SitecoreContext();
var model = ctx.GetCurrentItem<Footer>();
return View(model);
}
But, always getting null result, please help me any one.
You can use:
public ActionResult FooterTemplate()
{
ISitecoreContext ctx = new SitecoreContext();
var model = ctx.GetCurrentItem<Footer>(RenderingContext.Current.Rendering.DataSource);
return View(model);
}

Inserting to tables except where records already exist

I'm looking to add records to my database but not sure of the best approach.
Here are my models:
public class fList
{
public int fListID { get; set; }
public string Title { get; set; }
public int UserID { get; set; }
public ICollection<Item> Items { get; set; }
}
public class Item
{
public int ItemID { get; set; }
public string Name { get; set; }
public ICollection<fList> fLists { get; set; }
}
public class User
{
public int UserID { get; set; }
public string UserName { get; set; }
public ICollection<fList> fLists { get; set; }
}
Here is the database before performing the operation:
Here is how the database should look after performing the operation:
What I want to do is add a new fList and new User. I also want to add new Items but only where they don't already exist. And I want to join Items to the fList accordingly.
I'm hoping to achieve the above as efficiently as possible with minimal db calls.
Here's the controller so far:
var flist = new fList
{
Title = "Colors",
UserName = "Chris"
Items = new List<Item>()
};
flist.Items.Add(new Item { Name = "White" });
flist.Items.Add(new Item { Name = "Orange" });
flist.Items.Add(new Item { Name = "Purple" });
flist.Items.Add(new Item { Name = "Blue" });
flist.Items.Add(new Item { Name = "Green" });
foreach (var item in flist.Items)
{
// Check item exists in database
var existingitem = db.Items.SingleOrDefault(n => n.Name == item.Name);
// If item doesn't exist, add it to database
if (existingitem == null) {
db.Items.Add(item);
}
// ...What next?
}
db.fLists.Add(flist);
db.SaveChanges();
If you have time, you can download the Prodinner sample from Microsoft, it is a perfect solution include OOP, DI, IOC,etc. It also show you the generic functions for saving data.
If you need control the state during save records, you need implement state control your own. Create Interface, Enum and Implement class as show below.
public interface IDataObjectWithState
{
State State { get; set; }
}
public enum State
{
Added,
Unchanged,
Modified,
Deleted
}
public abstract class DataObjectWithState : IDataObjectWithState
{
[NotMapped]
public State State { get; set; }
}
After that any model class you want control the state you need inherit this Class, so your models have extra UnMap State columns.
In your DB Context file, make a contractor as sample below.
public Db()
: base("name=TP_HOST")
{
try
{
((IObjectContextAdapter)this).ObjectContext
.ObjectMaterialized += (sender, args) =>
{
var entity = args.Entity as IDataObjectWithState;
if (entity != null)
{
entity.State = YourEnumNamespace.State.Unchanged;
}
};
}
catch (Exception ex)
{
}
finally { }
}
// this class need include using System.Data.Entity.Infrastructure;
public static EntityState ConvertState(YourEnumNamespace.State state)
{
switch (state)
{
case YourEnumNamespace.State.Added:
return EntityState.Added;
case YourEnumNamespace.State.Deleted:
return EntityState.Deleted;
case YourEnumNamespace.State.Modified:
return EntityState.Modified;
default:
return EntityState.Unchanged;
}
}
Then before you make the call of db.SaveChanges(), you have to set the state like sample below
foreach (var entry in dbContext.ChangeTracker
.Entries<IDataObjectWithState>())
{
IDataObjectWithState stateInfo = entry.Entity;
entry.State =Functions.ConvertState(stateInfo.State);
}
I know difficult to understand mine code, what I want to mention is we define our own enum state, we tell the models what we want (Add, Unchanged, Update, Delete), using for loop change the state become knowing by System.Data.Entity.Infrastructure.

Widget in orchard won't save into database

I've a problem with orchard.
I've created a widget that is a video player, it's a simple widget with the class ContentPartRecord:
public class VideoPlayerPartRecord : ContentPartRecord
{
public virtual string MediaFile { get; set; }
public virtual int Width { get; set; }
public virtual int Height { get; set; }
public virtual bool AutoStart { get; set; }
public virtual bool Repeat { get; set; }
}
and the class ContentPart:
public class VideoPlayerPart : ContentPart<VideoPlayerPartRecord>
{
[Required(ErrorMessage = "Media File required")]
[Display(Name = "Media File: ")]
public string MediaFile
{
get { return Record.MediaFile; }
set { Record.MediaFile = value; }
}
[Required(ErrorMessage = "Width required")]
[Display(Name = "Width: ")]
public int Width
{
get { return Record.Width; }
set { Record.Width = value; }
}
[Required(ErrorMessage = "Height required")]
[Display(Name = "Height: ")]
public int Height
{
get { return Record.Height; }
set { Record.Height = value; }
}
[Display(Name = "Auto Start: ")]
public bool AutoStart
{
get { return Record.AutoStart; }
set { Record.AutoStart = value; }
}
[Display(Name = "Repeat: ")]
public bool Repeat
{
get { return Record.Repeat; }
set { Record.Repeat = value; }
}
}
this is the file migration:
public class Migrations : DataMigrationImpl {
public int Create() {
// Creating table default_Raise_VideoPlayer_VideoPlayePartRecord
SchemaBuilder.CreateTable("default_Raise_VideoPlayer_VideoPlayePartRecord", table => table
.ContentPartRecord()
.Column("MediaFile", DbType.String)
.Column("Width", DbType.Int32)
.Column("Height", DbType.Int32)
.Column("AutoStart", DbType.Boolean)
.Column("Repeat", DbType.Boolean)
);
ContentDefinitionManager.AlterPartDefinition(typeof(VideoPlayerPart).Name, cfg => cfg
.Attachable());
return 1;
}
public int UpdateFrom1() {
ContentDefinitionManager.AlterTypeDefinition("VideoPlayerWidget", cfg => cfg
.WithPart("VideoPlayerPart")
.WithPart("WidgetPart")
.WithPart("CommonPart")
.WithSetting("Stereotype", "Widget"));
return 2;
}
}
the problem is that when I insert the widget it is added but I can't see it. Why??
You need to add a Handler for your widget to persist the item, and a placement.info entry to present it.
http://docs.orchardproject.net/Documentation/Writing-a-content-part
(code taken from article)
using Maps.Models;
using Orchard.ContentManagement.Handlers;
using Orchard.Data;
namespace Maps.Handlers {
public class MapHandler : ContentHandler {
public MapHandler(IRepository<MapRecord> repository) {
Filters.Add(StorageFilter.For(repository));
}
}
}
and Placement.info
<Placement>
<Place Parts_Map="Content:10"/>
<Place Parts_Map_Edit="Content:7.5"/>
</Placement>
If it doesn't save into a database - its probably the handler. If it doesn't display on screen, it's probably placement.info
Also you didn't mention having a driver or a view, but I'd guess it is the Handler or the placement info you are missing. Also, check spelling and convention very carefully when relating the driver, migration and placement info, as there are several places you can use the wrong text string if you create your parts manually.

ViewModel Inheritance for different actions with Twitter Bootstrap MVC 4

I'm trying to create a ViewModel in MVC that allows me to switch between the display format and the edit format.
I can get the Controller to select the correct version of the ViewModel and all the properties for the inherited class and base class show in the debugger.
When the ViewModel is passed to the view, only the properties from the inherited class show up.
Can this approach work or should I create two seperate ViewModels?
ViewModel:
public partial class HouseholdViewModel
{
public int Id { get; set; }
public int familyID { get; set; }
public string entityName { get; set; }
public System.DateTime attachmentDate { get; set; }
}
public partial class DisplayHouseholdViewModel : HouseholdViewModel
{
public string phone { get; set; }
}
public partial class CreateHouseholdViewModel : HouseholdViewModel
{
public string familyPhoneCode { get; set; }
public string familyPhone { get; set; }
}
Controller (snippet):
public class HouseholdController : Controller
{
private WhatWorksEntities db = new WhatWorksEntities();
//return viewmodel object
private string displayView = "displayView";
private string createView = "createView";
public IEnumerable<object> GetModel(string view)
{
if (view == displayView)
{
var householdView = (from h in db.tHouseholds
select new DisplayHouseholdViewModel
{
Id = h.householdID,
familyID = h.familyID,
entityName = h.tEntity.entityName,
attachmentDate = h.attachmentDate,
phone = h.familyPhoneCode + " " + h.familyPhone
}).AsEnumerable();
return (householdView);
}
else
{
var householdView = (from h in db.tHouseholds
select new CreateHouseholdViewModel
{
Id = h.householdID,
familyID = h.familyID,
entityName = h.tEntity.entityName,
attachmentDate = h.attachmentDate,
familyPhoneCode = h.familyPhoneCode,
familyPhone = h.familyPhone
}).AsEnumerable();
return (householdView);
}
}
//
// GET: /Household/
public ActionResult Index()
{
var householdView = GetModel(displayView).Cast<DisplayHouseholdViewModel>();
return View(householdView);
}
The view that is returned doesn't display the phone property:
---EDIT to show debugger with phone data---
Debug view:
In your view you need some logic to display the field -
#Html.LabelFor(l => l.Phone, "Phone")
#Html.DisplayFor(p => p.Phone)
And at the top you need to make sure you are displaying the proper view model
#model YourNamespace.ViewModels.DisplayViewModel
If you are trying to change on the same view between two ViewModels you will need to create two separate partial views and toggle their display settings

Resources