What am i doing wrong? Entries are not getting logged into database - asp.net-mvc-3

Here is Index:
It goes through folder and should add entries to database. But when i run it no entries are getting added. Is something wrong with this code?
(Basically code goes through couple folders gets image file and songs under the folder and add to database, but it is not working.)
public ActionResult Index()
{
DemoDb db = new DemoDb();
var movies = new List<SongModel>();
MovieModel movie = new MovieModel();
SongModel song = new SongModel();
//Function to get all the folders present in that particular location,Use
var folders = Directory.GetDirectories(Server.MapPath("~/Content/themes/base/songs"));
foreach (var folder in folders)
{
movie.MovieName = new DirectoryInfo(folder).Name;
string[] files = Directory.GetFiles(folder);
string img = string.Empty;
var list = new List<string>();
foreach (var file in files)
{
if (Path.GetExtension(file) == ".jpg" ||
Path.GetExtension(file) == ".png")
{
movie.Image = Path.Combine(Server.MapPath("~/Content/themes/base/songs"), file);
}
else
{
song.MovieId = movie.MovieId;
song.Song = Path.Combine(Server.MapPath("~/Content/themes/base/songs"), file);
}
}
db.movies.Add(movie);
db.songs.Add(song);
db.SaveChanges();
}
return View();
}
Here are classes and database design too:
public class MovieModel
{
[Key]
public int MovieId { get; set; }
public string MovieName { get; set; }
public int SongId { get; set; }
public string Image { get; set; }
}
public class SongModel
{
[Key]
public int SongId { get; set; }
public int MovieId { get; set; }
public string Song { get; set; }
}

You are creating only one movie and song above.
For every folder you overwrite the values in a movie object but never add a new object to your context, you only try to re-add your existing movie.
Also I wouldn't do this on an index HttpGet method. By the http spec a repeated GET call shouldn't change the system state each time (hence it should be idempotent)

Related

SQLite.NET Extensions Many To Many, no join table records created

I am new to using SQLite.NET and the Extensions.
To my best ability I have followed the guides I've found but no records are being created in the many to many join tables and I've no idea why.
I have a solution NuGet dependency on the SQLiteNetExtensions project.
I have the following tables:
[Table("Contact")]
public class Contact
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(50)]
public string FirstName { get; set; }
[MaxLength(50)]
public string Surname { get; set; }
[ManyToMany(typeof(Participant))]
public List<Journey> Journeys { get; set; }
}
[Table("Journey")]
public class Journey
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[ManyToMany(typeof(Participant))]
public List<Contact> Contacts { get; set; }
[ManyToMany(typeof(Waypoint))]
public List<Location> Locations { get; set; }
}
[Table("Location")]
public class Location
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(50)]
public string Name { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
[ManyToMany(typeof(Waypoint))]
public List<Journey> Journeys{ get; set; }
}
public class Participant
{
[ForeignKey(typeof(Contact))]
public int ContactId { get; set; }
[ForeignKey(typeof(Journey))]
public int JourneyId { get; set; }
}
public class Waypoint
{
[ForeignKey(typeof(Location))]
public int LocationId { get; set; }
[ForeignKey(typeof(Journey))]
public int JourneyId { get; set; }
}
When I build the database I use the following test code:
string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "xandroid.db3");
var db = new SQLiteConnection(platform, dbPath);
db.DropTable<Location>();
db.DropTable<Waypoint>();
db.DropTable<Contact>();
db.DropTable<Participant>();
db.DropTable<Journey>();
db.CreateTable<Location>();
db.CreateTable<Waypoint>();
db.CreateTable<Contact>();
db.CreateTable<Participant>();
db.CreateTable<Journey>();
Location home = new Location { Name = "Home", Latitude=22.22, Longitude=22.22 };
Location perth = new Location { Name = "Perth", Latitude = 4444.4444, Longitude = 4444.4444 };
db.InsertAll(new List<Location> { home, perth });
Contact beans = new Contact { FirstName = "Beans", Surname = "Connor" };
Contact winston = new Contact { FirstName = "Winston", Surname = "Connor" };
db.InsertAll(new List<Contact> { beans, winston });
Journey travelToPerth = new Journey { Locations = new List<Location> { perth }, Contacts = new List<Contact> { beans, winston }};
Journey returnHome = new Journey { Locations = new List<Location> { home }, Contacts = new List<Contact> { beans, winston}};
db.InsertAll(new List<Journey> { travelToPerth, returnHome } );
When I access the data I use the following code:
var waypoints = db.Table<Waypoint>();
Console.Out.WriteLine(waypoints.Count() + " recorded waypoints");
var participants = db.Table<Participant>();
Console.Out.WriteLine(participants.Count() + " recorded participants");
var journeys = db.Table<Journey>();
Console.Out.WriteLine(journeys.Count() + " recorded journeys");
The output of which is:
0 recorded waypoints
0 recorded participants
2 recorded journeys
You are inserting the objects using plain sqlite.net methods, that know nothing about your relationships. To save and load relationships you have to use SQLite-Net Extension methods. Most sqlite-net methods also have a WithChildren alternative to save relationships:
import SQLiteNetExtensions.Extensions;
db.InsertAllWithChildren(new List<Journey> { travelToPerth, returnHome } );
Will insert both elements and insert the required records to Participant and Waypoint tables to save the relationships.
Note: This still requires Location and Contact elements to be already inserted in database. To insert objects recursively, take a look at the Cascade operations section of the SQLite-Net Extensions documentation.

Retrieving information from derived child object collections using LINQ

I have been trying to get a list of all Workflows that have Offices contained in a certain List by Office Id. I can easily get all of the Workflows that have SingleWorkflowSteps because they have only one Office, but have been unable to understand how I would successfully get those contained in a MultiWorkflowStep. All workflow steps have either a SingleWorkflowStep or a MultiWorkflowStep that contains two or more SingleWorkflowSteps. At the time I designed this, it seemed like a logical way to do this but atlas my LINQ-fu is not as good as I thought it was. Can someone please point me in the right directions. Code listed below:
var OfficesToFind = new List<int> (new int[] { 1,3,5,7,9,10,11,12} );
public class Workflow
{
public Workflow()
{
WorkflowSteps = new List<WorkflowStepBase>();
}
public int Id { get; set; }
public virtual ICollection<WorkflowStepBase> WorkflowSteps { get; set; }
}
public abstract class WorkflowStepBase
{
public int Id { get; set; }
public int StatusId { get; set; }
public virtual Workflow Workflow { get; set; }
public virtual Status Status { get; set; }
}
public class MultiWorkflowStep : WorkflowStepBase
{
public MultiWorkflowStep()
{
ChildSteps = new List<SingleWorkflowStep>();
}
public virtual ICollection<SingleWorkflowStep> ChildSteps { get; set; }
}
public class SingleWorkflowStep : WorkflowStepBase
{
public int? ParentStepId { get; set; }
public int OfficeId { get; set; }
public virtual MultiWorkflowStep ParentStep { get; set; }
public virtual Office Office { get; set; }
}
public class Office
{
public int Id { get; set; }
public string Name { get; set; }
}
public class WorkflowService : IWorkflowService<Workflow>
{
private readonly IRepository<Workflow> _workflowService;
private readonly IRepository<SingleWorkflowStep> _singleStepService;
private readonly IRepository<MultiWorkflowStep> _multiStepService;
public WorkflowService(IUnitOfWork uow)
{
_workflowService = uow.GetRepository<Workflow>();
_singleStepService = uow.GetRepository<SingleWorkflowStep>();
_multiStepSercice = uow.GetRepository<MultiWorkflowStep>();
}
// ~ ------- Other CRUD methods here -------- ~
public IEnumerable<Workflow> GetWorkflowFilter(List<int> statuses, List<int> offices...)
{
var query = _workflowService.GetIQueryable(); // returns an IQueryable of dbset
if(statuses.Any())
{
query = query.Where(q => statuses.Contains(q.StatusId));
}
if(offices.Any())
{
// Get all active single steps and the ones that contain the offices
singleSteps = _singleStepService
.Where(s => s.StatusId == (int)Enumerations.StepStatus.ACTIVE)
.Where(s => offices.Contains(s.OfficeId));
// Get all of the parent Workflows for the singleSteps
var workflows = singleSteps.Select(w => w.Workflow);
// Update the query with the limited scope
query = query.Where(q => q.Workflow.Contains(q));
}
return query.ToList();
}
}
OK, after a good night sleep, being all bright-eyed and bushy-tailed, I figured out my own problem. First the updated code was all wrong. Because each derived WorkflowStep has access to the Workflow and each MultiWorkflowStep contains a list of SingleWorkflowSteps - when I get the list of all SingleWorkflowSteps (which would include all from MultiWorkflowStep(s)), I simply needed to get a list of all of the parent Workflows of the SingleWorkflowSteps. Next I updated my query to limit the Workflows that were contained in the new Workflow list and here is the correct code for the GetWorkflowFilter method:
...
if(offices.Any())
{
// Get all active single steps and the ones that contain the offices
singleSteps = _singleStepService.Where(s => s.StatusId == (int)Enumerations.StepStatus.ACTIVE).Where(s => offices.Contains(s.OfficeId));
// Get all of the parent Workflows for the singleSteps
var workflows = singleSteps.Select(w => w.Workflow);
// Update the query with the limited scope
query = query.Where(q => q.Workflow.Contains(q));
}
return query.ToList();
}

Get value from IsolatedStorageSetting in windows phone7

Can anyone help me to solve this problem?
I am using visual studio2010 and its windows phone 7 application
I have created addpet.xaml and mypet.xaml.
Created IsolatedStorageSetting object in mypet.cs file
{
public static IsolatedStorageSettings settings=IsolatedStorageSettings.ApplicationSettings;
}
I have 5 textboxes and I am storing its value in list item.That list stores in IsolatedStorageSetting object.
{
SaveMypet savepet = new SaveMypet();
savepet.Name = txt_name.ToString();
savepet.Birthday = txt_birthday.ToString();
savepet.FavFood = txt_favouritefood.ToString();
savepet.DocNo = txt_doctorsno.ToString();
savepet.VacDate = txt_vacdate.ToString();
savepet.FavToy = txt_favouritetoy.ToString();
// savepet.Image1 = image1.Source;
listMyPet.Add(savepet);
settings.Add("iso_listMyPet", listMyPet);
}
Now I want to access this object in addpet.cs and cast it to list and then want to assign to listbox.
Like this, I have did but does not work
Created list object in addpet.cs
{
static List<pg_addPet> list_listMyPet = null;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
list_listMyPet = (List<pg_addPet>)pg_addPet.settings["iso_mypet_list"];
listbox_mypet.ItemsSource = list_listMyPet;
}
And my SaveMypet class is
public class SaveMypet
{
public string Name { get; set; }
public string Birthday { get; set; }
public string FavFood { get; set; }
public string DocNo { get; set; }
public string VacDate { get; set; }
public string FavToy { get; set; }
// public ImageSource Image1 { get; set; }
}
You've declared the settings property as static. Therefore, you need to use the class name to access it:
list_listMyPet = (List<pg_addPet>)pg_mypet.settings["iso_mypet_list"];
Try the following:
if(!pg_mypet.settings.TryGetValue("iso_mypet_list", out list_listMyPet))
{
list_listMyPet = new List<pg_addPet>();
}
This will try to retrieve the value and if if fails it will create an empty list instead.

Binding ListBox with a model in MVC3

My model is
public class SiteConfig
{
public SiteConfig()
{
}
public int IdSiteConfig { get; set; }
public string Name { get; set; }
public byte[] SiteLogo { get; set; }
public string Brands { get; set; }
public string LinkColour { get; set; }
public IEnumerable<SiteBrand> SiteBrands { get; set; }
}
and
public class SiteBrand
{
public int Id { get; set; }
public int SiteId { get; set; }
public int BrandId { get; set; }
public Brand Brand { get; set; }
public SiteConfig SiteConfig { get; set; }
}
public class Brand
{
public int BrandId { get; set; }
public string Name { get; set; }
public IEnumerable<SiteBrand> SiteBrands { get; set; }
}
I am following Data Base first approach. Each SiteConfig record can contain one or more Brand. So Brand is saving to another table called SiteBrand.
SiteBrand contains the forign key reference to both SiteConfig(on IdSiteConfig) and Brand(BrandId).
When I am creating a SiteConfig I want to display all the available Brand as list box where user can select one or many record(may not select any brand).
But when I bind my view with the model how can I bind my list box to the list of brands and when view is posted how can I get the selected brands.
And I have to save the SiteConfig object to database with the selected Items. And this is my DB diagram.
This is my DAL which saves to db.
public SiteConfig Add(SiteConfig item)
{
var siteConfig = new Entities.SiteConfig
{
Name = item.Name,
LinkColour = item.LinkColour,
SiteBrands = (from config in item.SiteBrands
select new SiteBrand {BrandId = config.BrandId, SiteId = config.SiteId}).
ToList()
};
_dbContext.SiteConfigs.Add(siteConfig);
_dbContext.SaveChanges();
return item;
}
Can somebody advide how to bind the list box and get the selected items.
Thanks.
Add a new Property to your SiteConfig ViewModel of type string array. We will use this to get the Selected item from the Listbox when user posts this form.
public class SiteConfig
{
//Other properties here
public string[] SelectedBrands { get; set; } // new proeprty
public IEnumerable<SiteBrand> SiteBrands { get; set; }
}
In your GET action method, Get a list of SiteBrands and assign to the SiteBrands property of the SiteConfig ViewModel object
public ActionResult CreateSiteConfig()
{
var vm = new SiteConfig();
vm.SiteBrands = GetSiteBrands();
return View(vm);
}
For demo purposes, I just hard coded the method. When you implement this, you may get the Data From your Data Access layer.
public IList<SiteBrand> GetSiteBrands()
{
List<SiteBrand> brands = new List<SiteBrand>();
brands.Add(new SiteBrand { Brand = new Brand { BrandId = 3, Name = "Nike" } });
brands.Add(new SiteBrand { Brand = new Brand { BrandId = 4, Name = "Reebok" } });
brands.Add(new SiteBrand { Brand = new Brand { BrandId = 5, Name = "Addidas" } });
brands.Add(new SiteBrand { Brand = new Brand { BrandId = 6, Name = "LG" } });
return brands;
}
Now in your View, which is strongly typed to SiteConfig ViewModel,
#model SiteConfig
<h2>Create Site Config</h2>
#using (Html.BeginForm())
{
#Html.ListBoxFor(s => s.SelectedBrands,
new SelectList(Model.SiteBrands, "Brand.BrandId", "Brand.Name"))
<input type="submit" value="Create" />
}
Now when user posts this form, you will get the Selected Items value in the SelectedBrands property of the ViewModel
[HttpPost]
public ActionResult CreateSiteConfig(SiteConfig model)
{
if (ModelState.IsValid)
{
string[] items = model.SelectedBrands;
//check items now
//do your further things and follow PRG pattern as needed
}
model.SiteBrands = GetBrands();
return View(model);
}
You can have a "ViewModel" that has both the site and brand model in it. Then you can bind your view to that model. This would allow you to bind any part of the view to any part of any of the underlying models.
public class siteViewModel{
public SiteConfig x;
public Brand b; //Fill this with all the available brands
}
Of course you can include any other information your view might need (reduces the need of ViewBag as well).

Windows Phone 7 isolated storage serialization errors with List of objects

I have been trying to serialize a list of objects from a class and keep getting an error stating there is an error in the XML file at point (25, 6)(these numbers change depending on what I am trying to serialize).
Here's an example of how I am trying to serialize the data:
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using((IsolatedStorageFileStream fs = isf.CreateFile("data.dat"))
{
XmlSerializer ser = new XmlSerializer(User.Data.GetType());
ser.Serialize(fs, User.Data);
}
}
And here's how I am deserializing the data:
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isf.FileExists("Data.dat"))
{
using (IsolatedStorageFileStream fs = isf.OpenFile("Data.dat", System.IO.FileMode.Open))
{
XmlSerializer ser = new XmlSerializer(User.Data.GetType());
object obj = ser.Deserialize(fs);
if (null != obj && obj is Data)
User.Data= obj as Data;
}
}
}
I don't see any initial problems with this portion of the code, but it crashes on every list of objects I pass it.
Here's a sample of the class I'm using:
public class Data
{
public static int counter;
public Data() { this.index = counter++; }
public DateTime availablefrom { get; set; }
public DateTime availableuntil { get; set; }
public string course { get; set; }
public DateTime? datetaken { get; set; }
public double duration { get; set; }
public string instructions { get; set; }
public string instructorname { get; set; }
public double scorepointscorrect { get; set; }
public double scorepointspossible { get; set; }
public string testname { get; set; }
public int index { get; private set; }
}
When I give the serializer just simple classes it works, so I know the serializer itself is working, but when I create a list of objects from my Data class or other classes, it crashes. Anyone have any suggestions?
Since "index" is a public property of data, the deserializer is trying to set the value of it. This fails because set for "index" is private. Try setting "index" to internal instead of public and it should deserialize correctly.
Try passing in the list type instead of the type that s in the list. For example:
XmlSerializer serializer = new XmlSerializer(typeof(List<Incident>));
instead of
XmlSerializer serializer = new XmlSerializer(typeof(Incident));
Here is how I save and load lists of objects to and from Isolated Storage:
private static IsolatedStorageFile _isoStore;
public static IsolatedStorageFile IsoStore
{
get { return _isoStore ?? (_isoStore = IsolatedStorageFile.GetUserStoreForApplication()); }
}
public static void SaveList<T>(string folderName, string dataName, ObservableCollection<T> dataList) where T : class
{
if (!IsoStore.DirectoryExists(folderName))
{
IsoStore.CreateDirectory(folderName);
}
string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileStreamName, FileMode.Create, IsoStore))
{
DataContractSerializer dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
dcs.WriteObject(stream, dataList);
}
}
public static ObservableCollection<T> LoadList<T>(string folderName, string dataName) where T : class
{
ObservableCollection<T> retval = new ObservableCollection<T>();
string fileStreamName = string.Format("{0}\\{1}.dat", folderName, dataName);
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileStreamName, FileMode.OpenOrCreate, IsoStore))
{
if (stream.Length > 0)
{
DataContractSerializer dcs = new DataContractSerializer(typeof(ObservableCollection<T>));
retval = dcs.ReadObject(stream) as ObservableCollection<T>;
}
}
return retval;
}

Resources