Facebook Ad Leads retrieval asp.net - asp.net-mvc

Is there a way I can read Ad leads data from Lead_ID in asp.net? I see there are examples of PHP but there is no SDK for C#.Unforunately I have to use Asp.net and cannot use any other technologies
Any suggestions are highly appreciated

You can use facebook sdk c# and
var fb = new FacebookClient
{
AccessToken ="token"
};
var json = fb.Get("page_id or ad_id/leadgen_forms");
var forms = JsonConvert.DeserializeObject<FormsLeads>(json.ToString());
foreach (var form in forms.data)
{
var jsonre = fb.Get(form.id + "/leads");
var leads = JsonConvert.DeserializeObject<Leads>(jsonre.ToString());
while (leads.paging != null)
{
foreach (var lead in leads.data)
{
var leadnovo = new Models.Lead();
leadnovo.CamposExtras.Add(new CampoExtra { Nome = "idfacebook", Valor = lead.id });
leadnovo.DataCadastro = lead.created_time;
foreach (var t in lead.field_data)
{
if (t.name == "full_name")
{
leadnovo.Nome = t.values.FirstOrDefault();
}
else
if (t.name == "email")
{
leadnovo.Email = t.values.FirstOrDefault();
}
else
if (t.name == "phone_number")
{
leadnovo.Celular = t.values.FirstOrDefault();
}
else
{
leadnovo.CamposExtras.Add(new CampoExtra()
{
Nome = t.name,
Valor = t.values.FirstOrDefault()
});
}
}
if (db.Leads.FirstOrDefault(c => c.Email == leadnovo.Email) == null)
{
db.Leads.Add(leadnovo);
db.SaveChanges();
}
}
if (leads.paging != null)
{
jsonre = fb.Get(form.id + "/leads?after=" + leads.paging.cursors.after);
leads = JsonConvert.DeserializeObject<Leads>(jsonre.ToString());
}
}
}
}
Class for deserialize
public class Cursors
{
public string before { get; set; }
public string after { get; set; }
}
public class Field_Data
{
public string name { get; set; }
public string[] values { get; set; }
}
public class FormsLeads
{
public Formulario[] data { get; set; }
public Paging paging { get; set; }
}
public class Formulario
{
public string id { get; set; }
public string leadgen_export_csv_url { get; set; }
public string locale { get; set; }
public string name { get; set; }
public string status { get; set; }
}
public class Lead
{
public DateTime created_time { get; set; }
public string id { get; set; }
public Field_Data[] field_data { get; set; }
}
public class Leads
{
public Lead[] data { get; set; }
public Paging paging { get; set; }
}
public class Paging
{
public Cursors cursors { get; set; }
}

Related

how to return json data from mvc controller and view

I am new to mvc so here is my problem I have created a jquery-datatble with a action link named "detalles". When a user clicks on it I what to be able to see the details of the item selected in the jquery-datatble. Once the user has clicked on it. It opens a new tab that has a form with fields and also an other jquery-datatble. Basicly my idea would be to only have one return in the controler that return the view and th json.
Here is my Action result for i "detalles"
public ActionResult Detalles(int? id)
{
proveedorContext proveedorContext = new proveedorContext();
if (id == null)
{
}
proveedorModel proveedor = proveedorContext.GetAllProveedor().Find(obj => obj.proveedor_id == id);
//When i am here my model is not empty
loadProveedorContactoTable(proveedor);
if (proveedor == null)
{
}
return View(proveedor);
}
But unfortunately after words my program calls "loadProveedorContactoTable" again and then my model is completely null
public ActionResult loadProveedorContactoTable(proveedorModel model)
{
try
{
var proveedorsContactoData = model.contactos.OrderBy(a => a.nombre_contacto).ToList();
return Json(new { data = proveedorsContactoData }, JsonRequestBehavior.AllowGet);
}
catch
{
return View();
}
}
Here is my proveedorModel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace erp_colombia.Models
{
public class proveedorModel
{
public int proveedor_id { get; set; }
public string nombre { get; set; }
public string direccion { get; set; }
public string codigo_postal { get; set; }
public string cuidad { get; set; }
public string pais { get; set; }
public string pagina_internet { get; set; }
public int compras_cantidad { get; set; }
public int componente_cantidad { get; set; }
public int eliminado { get; set; }
public List<ContactoModel> contactos { get; set; }
}
}
And here is how I read the data for contactos and proveedor()
public List<proveedorModel> GetAllProveedor()
{
List<proveedorModel> list = new List<proveedorModel>();
using (MySqlConnection conn = GetConnection())
{
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM erp_proveedores",conn);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
list.Add(new proveedorModel()
{
proveedor_id = int.Parse(reader.GetString(reader.GetOrdinal("proveedor_id"))),
nombre = reader.GetString(reader.GetOrdinal("nombre")),
direccion = reader.GetString(reader.GetOrdinal("direccion")),
codigo_postal = reader.GetString(reader.GetOrdinal("codigo_postal")),
cuidad = reader.GetString(reader.GetOrdinal("cuidad")),
pais = reader.GetString(reader.GetOrdinal("pais")),
pagina_internet = reader.GetString(reader.GetOrdinal("pagina_internet")),
eliminado = int.Parse(reader.GetString(reader.GetOrdinal("eliminado"))),
contactos = new proveedorContactoContext().GetAllProveedorContactos(int.Parse(reader.GetString(reader.GetOrdinal("proveedor_id"))))
});
}
}
return list;
}
}
What can I do to fix this problem thank you for your help. I am thinking about making one return that would return the json and the view how could I so thar

Cannot Add Previously Inserted Object to Another Object (Entity Framework)

I have the EF classes OAFile and Email. I am loading the emails from the server and storing in the repository. The user can then list the e-mails and "associate" them with the selected file.
The email object is previously inserted into the repository, and I want to get the count of the emails of the file.
file.Emails.Add(email)
adds the email to the file object, but it is not being saved.
file.Emails.Count
returns always 0.
The email.FileID field is saved correctly.
What am I missing? How can get the number of email by calling file.Emails.Count?
[HttpPost]
[ValidateInput(false)]
public ActionResult AssignEmail(int emailId, int assignedTo)
{
if (emailId > 0 && assignedTo > 0)
{
Email email = repository.Emails.FirstOrDefault(x => x.EmailID == emailId);
OAFile file = repository.OAFiles.FirstOrDefault(x => x.FileID == assignedTo);
if (email != null && file != null)
{
email.FileID = assignedTo;
email.AssignedByID = HttpContext.User.Identity.GetUserId();
file.Emails.Add(email);
repository.Save();
return Json(new { success = true }, JsonRequestBehavior.DenyGet);
}
else
{
return Json(new { success = false }, JsonRequestBehavior.DenyGet);
}
}
else
{
return Json(new { success = false }, JsonRequestBehavior.DenyGet);
}
}
The Email class:
public class Email
{
public Email()
{
Attachments = new HashSet<EmailAttachment>();
}
[Key]
public int EmailID { get; set; }
public string EmailIdentifier { get; set; }
public int MessageNumber { get; set; }
public string From { get; set; }
public string Subject { get; set; }
public DateTime DateSent { get; set; }
public string Body { get; set; }
public int? FileID { get; set; }
public string AssignedByID { get; set; }
public string AssignedToID { get; set; }
public string EmailType { get; set; }
public ICollection<EmailAttachment> Attachments { get; set; }
[ForeignKey("FileID")]
public virtual OAFile OAFile { get; set; }
[ForeignKey("AssignedByID")]
public virtual AppUser AssignedBy { get; set; }
[ForeignKey("AssignedToID")]
public virtual AppUser AssignedTo { get; set; }
}
and the OAFile class:
public class OAFile
{
public OAFile()
{
Services = new HashSet<Service>();
Documents = new HashSet<Document>();
Notes = new HashSet<Note>();
Forms = new HashSet<Form>();
Emails = new HashSet<Email>();
}
[Key]
public int FileID { get; set; }
[Required]
public int CompanyID { get; set; }
[Required]
[StringLength(14)]
public string OurFileName { get; set; }
[Required]
[StringLength(100)]
public string CompanyFileName { get; set; }
[Required]
public string AppUserId_Creator { get; set; }
[DisplayFormat(DataFormatString = "{0:dd.MM.yyyy}")]
public DateTime CreatedOn { get; set; }
public int ClientID { get; set; }
[ForeignKey("ClientID")]
public virtual Client Client { get; set; }
public virtual ICollection<Service> Services { get; set; }
public ICollection<Document> Documents { get; set; }
public ICollection<Note> Notes { get; set; }
public ICollection<Form> Forms { get; set; }
public ICollection<Email> Emails { get; set; }
public virtual Company Companies { get; set; }
[ForeignKey("AppUserId_Creator")]
public virtual AppUser AppUsers_Creator { get; set; }
}
EDIT: I am calling the file.Emails.Count statement below to check whether the file has any emails associated with it.
public bool IsFileEmpty(int fileId)
{
bool isFileEmpty = true;
OAFile file = repository.FindOAFile(fileId);
if (file.Services.Count > 0 || file.Documents.Count > 0
|| file.Forms.Count > 0 || file.Notes.Count > 0 || file.CCTable != null || file.AccountingTable != null
|| file.Emails.Count > 0
)
{
isFileEmpty = false;
}
return isFileEmpty;
}
EDIT 2: I am calling the IsFileEmpty() method in another controller (HomeController.cs) while populating view model for search results. The results rows display the Delete link if the file is empty.
public ActionResult FilesSearch(FileSearchViewModel viewModel)
{
var files = !string.IsNullOrWhiteSpace(viewModel.Keyword) ? repository.FindOAFiles(viewModel.Keyword) : repository.OAFiles;
var sortedFile = files.Where(x => x.IsFileOpen).OrderByDescending(x => x.CreatedOn).ToList();
sortedFile.AddRange(files.Where(x => !x.IsFileOpen).OrderByDescending(x => x.CreatedOn));
var resultsList = new List<FileSearchResultsViewModel>();
foreach (OAFile file in sortedFile)
{
var resultsViewModel = new FileSearchResultsViewModel();
resultsViewModel.oAFile = file;
resultsViewModel.isFileEmpty = IsFileEmpty(file.FileID);
resultsList.Add(resultsViewModel);
}
return PartialView("_FilesSearch", resultsList);
}

Database-First & Error: Unable to determine a valid ordering for dependent operations

I have a problem with the project I am working on. On POST:Edit, it saves my changes. On POST:Create, I receive this error: "Unable to determine a valid ordering for dependent operations. Dependencies may exist due to foreign key constraints, model requirements, or store-generated values."
So I did what my teachers taught us in College: I just Googled it. The answers however were suggesting to change the ModelBuilder-fluent API. I do not think this would be inappropriate since I use Database-First approach (It says it is only for Code-First) AND my Save is functional in Edit. Since I wanted to work with ViewModels, I followed this tutorial. I even found and posted a solution for the tutorial about the Create method to help me with my problem. Please help me. I am about to throw my computer out of the window. Which is kind of complicated because they are made of tempered glass.
So here's the metadata for my model (with minimal data annotation for readability sake:
public partial class Employe
{
sealed class Metadata
{
[Key]
public int IdEmploye { get; set; }
public string NomEmploye { get; set; }
public string PrenomEmploye { get; set; }
[ForeignKey("TitreEmploye_IdTitre")]
public int IdTitre { get; set; }
[ForeignKey("Departement_IdDepartement")]
public int IdDepartement { get; set; }
[ForeignKey("Employe_IdSuperviseur")]
public int IdSuperviseur { get; set; }
public System.DateTime DateEmbauche { get; set; }
public Nullable<System.DateTime> DateDepart { get; set; }
public string StatutEmploye { get; set; }
[ForeignKey("Employeur_IdEmployeur")]
public int IdEmployeur { get; set; }
[ForeignKey("Localisation_IdLocalisation")]
public int IdLocalisation { get; set; }
public string Langue { get; set; }
public Nullable<bool> CarteAcces { get; set; }
[ForeignKey("TelephoneBureau_IdTelephoneBureau")]
public Nullable<int> IdTelephoneBureau { get; set; }
public Nullable<bool> CarteAffaire { get; set; }
public string AdresseCourriel { get; set; }
public bool CodeAlarme { get; set; }
public System.DateTime DateNaissance { get; set; }
public Nullable<bool> IsSuperviseur { get; set; }
public Nullable<bool> IsActif { get; set; }
}
}
}
Here's my problematic(?) model:
public partial class Employe
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Employe()
{
this.AccesApplicatif1 = new HashSet<AccesApplicatif>();
this.TelephoneCellulaire1 = new HashSet<TelephoneCellulaire>();
this.CleBatiment1 = new HashSet<CleBatiment>();
this.EquipementInfo = new HashSet<EquipementInfo>();
this.GroupeSecurite1 = new HashSet<GroupeSecurite>();
this.VehiculeCompagnie1 = new HashSet<VehiculeCompagnie>();
this.Employe1 = new HashSet<Employe>();
}
public int IdEmploye { get; set; }
public string NomEmploye { get; set; }
public string PrenomEmploye { get; set; }
public int IdTitre { get; set; }
public int IdDepartement { get; set; }
public int IdSuperviseur { get; set; }
public System.DateTime DateEmbauche { get; set; }
public Nullable<System.DateTime> DateDepart { get; set; }
public string StatutEmploye { get; set; }
public int IdEmployeur { get; set; }
public int IdLocalisation { get; set; }
public string Langue { get; set; }
public Nullable<bool> CarteAcces { get; set; }
public Nullable<int> IdTelephoneBureau { get; set; }
public Nullable<bool> CarteAffaire { get; set; }
public string AdresseCourriel { get; set; }
public bool CodeAlarme { get; set; }
public System.DateTime DateNaissance { get; set; }
public Nullable<bool> IsSuperviseur { get; set; }
public Nullable<bool> IsActif { get; set; }
public virtual Departement Departement { get; set; }
public virtual Employeur Employeur { get; set; }
public virtual Localisation Localisation { get; set; }
public virtual TelephoneBureau TelephoneBureau { get; set; }
public virtual TitreEmploye TitreEmploye { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<AccesApplicatif> AccesApplicatif1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<TelephoneCellulaire> TelephoneCellulaire1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<CleBatiment> CleBatiment1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<EquipementInfo> EquipementInfo { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<GroupeSecurite> GroupeSecurite1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<VehiculeCompagnie> VehiculeCompagnie1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Employe> Employe1 { get; set; }
public virtual Employe Employe2 { get; set; }
public string NomSuperviseur
{
get
{
return string.Format("{0} {1}", PrenomEmploye, NomEmploye);
}
}
}
As I said, since I wanted to work with ViewModels, here's the culprit:
public partial class EmployeVM
{
public Employe Employe { get; set; } //Employe
public string NomEmploye { get; set; } //Employe
public string PrenomEmploye { get; set; } //Employe
public DateTime DateNaissance { get; set; } //Employe
public string Langue { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<Titre> Titres { get; set; } //TitreEmploye
public class Titre
{
public string description { get; set; } //TitreEmploye
}
//////////////////////////////////////////////////////////////
public IEnumerable<Departement> Departements { get; set; } //Departement
public class Departement
{
public string description { get; set; } //Departement
}
//////////////////////////////////////////////////////////////
public IEnumerable<Superviseur> Superviseurs { get; set; } //Employe
public class Superviseur
{
public string nomSuperviseur { get; set; } //Employe
}
public string StatutEmploye { get; set; } //Employe
public DateTime DateEmbauche { get; set; } //Employe
public Nullable<System.DateTime> DateDepart { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<Employeur> Employeurs { get; set; } //Employeur
public class Employeur
{
public string nomEmployeur { get; set; } //Employeur
}
//////////////////////////////////////////////////////////////
public IEnumerable<Localisation> Localisations { get; set; } //Localisation
public class Localisation
{
public string description { get; set; } //Localisation
}
public bool CarteAcces { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<TelephoneBureau> TelephoneBureaux { get; set; } //TelephoneBureau
public class TelephoneBureau
{
public string extension { get; set; } //TelephoneBureau
}
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllTelephoneCellulaires { get; set; } //TelephoneCellulaire
private List<int> _selectedTelephoneCellulaires;
public List<int> SelectedTelephoneCellulaires
{
get
{
if (_selectedTelephoneCellulaires == null)
{
_selectedTelephoneCellulaires = Employe.TelephoneCellulaire1.Select(m => m.IdTelephoneCellulaire).ToList();
}
return _selectedTelephoneCellulaires;
}
set { _selectedTelephoneCellulaires = value; }
}
public bool CarteAffaire { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllEquipementInformatiques { get; set; } //EquipementInfo
private List<int> _selectedEquipementInformatiques;
public List<int> SelectedEquipementInformatiques
{
get
{
if (_selectedEquipementInformatiques == null)
{
_selectedEquipementInformatiques = Employe.EquipementInfo.Select(m => m.IdEquipementInfo).ToList();
}
return _selectedEquipementInformatiques;
}
set { _selectedEquipementInformatiques = value; }
}
public string AdresseCourriel { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllGroupeSecurites { get; set; } //GroupeSecurite
private List<int> _selectedGroupeSecurites;
public List<int> SelectedGroupeSecurites
{
get
{
if (_selectedGroupeSecurites == null)
{
_selectedGroupeSecurites = Employe.GroupeSecurite1.Select(m => m.IdGroupeSecurite).ToList();
}
return _selectedGroupeSecurites;
}
set { _selectedGroupeSecurites = value; }
}
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllAccesApplicatifs { get; set; } //AccesApplicatif
private List<int> _selectedAccesApplicatifs;
public List<int> SelectedAccesApplicatifs
{
get
{
if (_selectedAccesApplicatifs == null)
{
_selectedAccesApplicatifs = Employe.AccesApplicatif1.Select(m => m.IdAccesApplicatif).ToList();
}
return _selectedAccesApplicatifs;
}
set { _selectedAccesApplicatifs = value; }
}
public bool CodeAlarme { get; set; } //Employe
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllCleBatiments { get; set; } //CleBatiment
private List<int> _selectedCleBatiments;
public List<int> SelectedCleBatiments
{
get
{
if (_selectedCleBatiments == null)
{
_selectedCleBatiments = Employe.CleBatiment1.Select(m => m.IdCleBatiment).ToList();
}
return _selectedCleBatiments;
}
set { _selectedCleBatiments = value; }
}
//////////////////////////////////////////////////////////////
public IEnumerable<SelectListItem> AllVehiculeCompagnies { get; set; } //VehiculeCompagnie
private List<int> _selectedVehiculeCompagnies;
public List<int> SelectedVehiculeCompagnies
{
get
{
if (_selectedVehiculeCompagnies == null)
{
_selectedVehiculeCompagnies = Employe.VehiculeCompagnie1.Select(m => m.IdVehiculeCompagnie).ToList();
}
return _selectedVehiculeCompagnies;
}
set { _selectedVehiculeCompagnies = value; }
}
public bool IsSuperviseur { get; set; } //Employe
public bool IsActif { get; set; } //Employe
public EmployeVM()
{
AllTelephoneCellulaires = new List<SelectListItem>();
AllEquipementInformatiques = new List<SelectListItem>();
AllGroupeSecurites = new List<SelectListItem>();
AllAccesApplicatifs = new List<SelectListItem>();
AllCleBatiments = new List<SelectListItem>();
AllVehiculeCompagnies = new List<SelectListItem>();
}
}
And here's the Create part of my Controller (I KNOW I will have to add some methods to comply to DRY, but for now, that's what it is:
// GET: Employes/Create
//[AcceptVerbs(HttpVerbs.Get), ImportModelStateFromTempData]
public ActionResult Create()
{
var employeView = new EmployeVM();
//Population pour les ListBoxFor
var allTelephoneCellulaireActifList = db.TelephoneCellulaireActif.ToList();
ViewBag.AllTelephoneCellulaires = allTelephoneCellulaireActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdTelephoneCellulaire.ToString()
});
var allEquipementInfoActifList = db.EquipementInfoActif.ToList();
ViewBag.AllEquipementInformatiques = allEquipementInfoActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdEquipementInfo.ToString()
});
var allGroupeSecuriteList = db.GroupeSecurite.ToList();
ViewBag.AllGroupeSecurites = allGroupeSecuriteList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdGroupeSecurite.ToString()
});
var allAccesApplicatifActifList = db.AccesApplicatifActif.ToList();
ViewBag.AllAccesApplicatifs = allAccesApplicatifActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdAccesApplicatif.ToString()
});
var allCleBatimentList = db.CleBatiment.ToList();
ViewBag.AllCleBatiments = allCleBatimentList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdCleBatiment.ToString()
});
var allVehiculeCompagnieActifList = db.VehiculeCompagnieActif.ToList();
ViewBag.AllVehiculeCompagnies = allVehiculeCompagnieActifList.Select(o => new SelectListItem
{
Text = o.DescriptionVehicule,
Value = o.IdVehiculeCompagnie.ToString()
});
//Zero-or-One-to-Many relationships
List<TitreEmployeActif> ListeTitreEmployeActif = db.TitreEmployeActif.OrderBy(titre => titre.Description).ToList();
ViewBag.IdTitre = new SelectList(ListeTitreEmployeActif, "IdTitre", "Description");
List<Departement> ListeDepartement = db.Departement.OrderBy(departement => departement.Description).ToList();
ViewBag.IdDepartement = new SelectList(ListeDepartement, "IdDepartement", "Description");
List<EmployeSuperviseurActif> ListeEmployeSuperviseurActif = db.EmployeSuperviseurActif.OrderBy(sup => sup.PrenomNom).ToList();
ViewBag.IdSuperviseur = new SelectList(ListeEmployeSuperviseurActif, "IdEmploye", "PrenomNom");
List<Employeur> ListeEmployeur = db.Employeur.OrderBy(employeur => employeur.NomEmployeur).ToList();
ViewBag.IdEmployeur = new SelectList(ListeEmployeur, "IdEmployeur", "NomEmployeur");
List<Localisation> ListeLocalisation = db.Localisation.OrderBy(localisation => localisation.Description).ToList();
ViewBag.IdLocalisation = new SelectList(ListeLocalisation, "IdLocalisation", "Description");
List<TelephoneBureauActif> ListeTelephoneBureauActif = db.TelephoneBureauActif.OrderBy(phone => phone.Extension).ToList();
ViewBag.IdTelephoneBureau = new SelectList(ListeTelephoneBureauActif, "IdTelephoneBureau", "Extension");
return View();
}
// POST: Employes/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to,
// for more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(EmployeVM employeView)
{
if (!ModelState.IsValid)
{
foreach (var obj in ModelState.Values)
{
foreach (var error in obj.Errors)
{
if (!string.IsNullOrEmpty(error.ErrorMessage))
System.Diagnostics.Debug.WriteLine("ERROR WHY = " + error.ErrorMessage);
}
}
}
if (ModelState.IsValid)
{
var employeToAdd = db.Employe
.Include(e => e.TelephoneCellulaire1)
.Include(e => e.EquipementInfo)
.Include(e => e.GroupeSecurite1)
.Include(e => e.AccesApplicatif1)
.Include(e => e.CleBatiment1)
.Include(e => e.VehiculeCompagnie1)
.First();
if (TryUpdateModel(employeToAdd, "Employe", new string[] { "IdEmploye", "NomEmploye", "PrenomEmploye", "IdTitre", "IdDepartement", "IdSuperviseur", "DateEmbauche", "DateDepart", "StatutEmploye", "IdEmployeur", "IdLocalisation", "Langue", "CarteAcces", "TelephoneCellulaire", "IdTelephoneBureau", "CarteAffaire", "EquipementInformatique", "AdresseCourriel", "GroupeSecurite", "AccesApplicatif", "CodeAlarme", "CleBatiment", "VehiculeCompagnie", "DateNaissance", "IsSuperviseur", "IsActif" }))
{
var updatedTelephoneCellulaires = new HashSet<int>(employeView.SelectedTelephoneCellulaires);
var updatedEquipementInformatiques = new HashSet<int>(employeView.SelectedEquipementInformatiques);
var updatedGroupeSecurites = new HashSet<int>(employeView.SelectedGroupeSecurites);
var updatedAccesApplicatifs = new HashSet<int>(employeView.SelectedAccesApplicatifs);
var updatedCleBatiments = new HashSet<int>(employeView.SelectedCleBatiments);
var updatedVehiculeCompagnies = new HashSet<int>(employeView.SelectedVehiculeCompagnies);
//Prochaine ligne db.TelephoneCellulaire1 !!! ou db.TelephoneCellulaireActif ??? Check readonly
foreach (TelephoneCellulaire telephone in db.TelephoneCellulaire)
{
if (!updatedTelephoneCellulaires.Contains(telephone.IdTelephoneCellulaire))
{
employeToAdd.TelephoneCellulaire1.Remove(telephone);
}
else
{
employeToAdd.TelephoneCellulaire1.Add(telephone);
}
}
foreach (EquipementInfo equipement in db.EquipementInfo)
{
if (!updatedEquipementInformatiques.Contains(equipement.IdEquipementInfo))
{
employeToAdd.EquipementInfo.Remove(equipement);
}
else
{
employeToAdd.EquipementInfo.Add(equipement);
}
}
foreach (GroupeSecurite groupe in db.GroupeSecurite)
{
if (!updatedGroupeSecurites.Contains(groupe.IdGroupeSecurite))
{
employeToAdd.GroupeSecurite1.Remove(groupe);
}
else
{
employeToAdd.GroupeSecurite1.Add(groupe);
}
}
foreach (AccesApplicatif acces in db.AccesApplicatif)
{
if (!updatedAccesApplicatifs.Contains(acces.IdAccesApplicatif))
{
employeToAdd.AccesApplicatif1.Remove(acces);
}
else
{
employeToAdd.AccesApplicatif1.Add(acces);
}
}
foreach (CleBatiment cle in db.CleBatiment)
{
if (!updatedCleBatiments.Contains(cle.IdCleBatiment))
{
employeToAdd.CleBatiment1.Remove(cle);
}
else
{
employeToAdd.CleBatiment1.Add(cle);
}
}
foreach (VehiculeCompagnie vehicule in db.VehiculeCompagnie)
{
if (!updatedVehiculeCompagnies.Contains(vehicule.IdVehiculeCompagnie))
{
employeToAdd.VehiculeCompagnie1.Remove(vehicule);
}
else
{
employeToAdd.VehiculeCompagnie1.Add(vehicule);
}
}
}
db.Employe.Add(employeToAdd);
db.SaveChanges();
return RedirectToAction("Index");
}
var allTelephoneCellulaireActifList = db.TelephoneCellulaireActif.ToList();
ViewBag.AllTelephoneCellulaires = allTelephoneCellulaireActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdTelephoneCellulaire.ToString()
});
var allEquipementInfoActifList = db.EquipementInfoActif.ToList();
ViewBag.AllEquipementInformatiques = allEquipementInfoActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdEquipementInfo.ToString()
});
var allGroupeSecuriteList = db.GroupeSecurite.ToList();
ViewBag.AllGroupeSecurites = allGroupeSecuriteList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdGroupeSecurite.ToString()
});
var allAccesApplicatifActifList = db.AccesApplicatifActif.ToList();
ViewBag.AllAccesApplicatifs = allAccesApplicatifActifList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdAccesApplicatif.ToString()
});
var allCleBatimentList = db.CleBatiment.ToList();
ViewBag.AllCleBatiments = allCleBatimentList.Select(o => new SelectListItem
{
Text = o.Description,
Value = o.IdCleBatiment.ToString()
});
var allVehiculeCompagnieActifList = db.VehiculeCompagnieActif.ToList();
ViewBag.AllVehiculeCompagnies = allVehiculeCompagnieActifList.Select(o => new SelectListItem
{
Text = o.DescriptionVehicule,
Value = o.IdVehiculeCompagnie.ToString()
});
//Zero-or-One-to-Many relationships
List<TitreEmployeActif> ListeTitreEmployeActif = db.TitreEmployeActif.OrderBy(titre => titre.Description).ToList();
ViewBag.IdTitre = new SelectList(ListeTitreEmployeActif, "IdTitre", "Description");
List<Departement> ListeDepartement = db.Departement.OrderBy(departement => departement.Description).ToList();
ViewBag.IdDepartement = new SelectList(ListeDepartement, "IdDepartement", "Description");
List<EmployeSuperviseurActif> ListeEmployeSuperviseurActif = db.EmployeSuperviseurActif.OrderBy(sup => sup.PrenomNom).ToList();
ViewBag.IdSuperviseur = new SelectList(ListeEmployeSuperviseurActif, "IdEmploye", "PrenomNom");
List<Employeur> ListeEmployeur = db.Employeur.OrderBy(employeur => employeur.NomEmployeur).ToList();
ViewBag.IdEmployeur = new SelectList(ListeEmployeur, "IdEmployeur", "NomEmployeur");
List<Localisation> ListeLocalisation = db.Localisation.OrderBy(localisation => localisation.Description).ToList();
ViewBag.IdLocalisation = new SelectList(ListeLocalisation, "IdLocalisation", "Description");
List<TelephoneBureauActif> ListeTelephoneBureauActif = db.TelephoneBureauActif.OrderBy(phone => phone.Extension).ToList();
ViewBag.IdTelephoneBureau = new SelectList(ListeTelephoneBureauActif, "IdTelephoneBureau", "Extension");
return View(employeView);
}
And just to complete the picture, an extract from Create.cshtml:
<div class="form-group">
#Html.LabelFor(model => model.AllEquipementInformatiques, "Équipements informatiques", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.ListBoxFor(model => model.SelectedEquipementInformatiques, (IEnumerable<SelectListItem>)ViewBag.AllEquipementInformatiques, new { #class = "form-control" })
</div>
</div>
Speaking about a picture, here's a little capture of one of my Many-to-Many table, with data entered with Edit:
Employe_VehiculeCompagnie
The thing to know (and I think it might be part of the problem) is: all of the 6 Many-To-Many relationships are optional. But even when I try to create a new Employe with at least one item in each of the 6 Many-to-Many field, it throws that error. And it still works in Edit. Questions: why this error is thrown and how can I make my app works? Any help would be greatly appreciated.
Edit:
Should I add this? One of my join table:
CREATE TABLE [dbo].[Employe_GroupeSecurite] (
[IdEmploye] INT NOT NULL,
[IdGroupeSecurite] INT NOT NULL,
PRIMARY KEY CLUSTERED ([IdEmploye] ASC, [IdGroupeSecurite] ASC),
CONSTRAINT [FK_Employe_GroupeSecurite_Employe] FOREIGN KEY ([IdEmploye]) REFERENCES [dbo].[Employe] ([IdEmploye]),
CONSTRAINT [FK_Employe_GroupeSecurite_GroupeSecurite] FOREIGN KEY ([IdGroupeSecurite]) REFERENCES [dbo].[GroupeSecurite] ([IdGroupeSecurite])
Now what?
I found it! Here's my solution, in case someone else tumbles with the same problem.
For some strange reason, Visual Studio added a '1' at the end of some of my Many-to-Many tables name. Entity Framework did not like it (neither did I), so I renamed them in my model:
Example:
public Employe()
{
this.AccesApplicatif1 = new HashSet<AccesApplicatif>();
this.TelephoneCellulaire1 = new HashSet<TelephoneCellulaire>();
this.CleBatiment1 = new HashSet<CleBatiment>();
this.EquipementInfo = new HashSet<EquipementInfo>();
this.GroupeSecurite1 = new HashSet<GroupeSecurite>();
this.VehiculeCompagnie1 = new HashSet<VehiculeCompagnie>();
this.Employe1 = new HashSet<Employe>();
}
Became:
this.AccesApplicatif = new HashSet<AccesApplicatif>();
this.TelephoneCellulaire = new HashSet<TelephoneCellulaire>();
this.CleBatiment = new HashSet<CleBatiment>();
this.EquipementInfo = new HashSet<EquipementInfo>();
this.GroupeSecurite = new HashSet<GroupeSecurite>();
this.VehiculeCompagnie = new HashSet<VehiculeCompagnie>();
this.Employe1 = new HashSet<Employe>();
Visual Studio was intelligent enough to rename them in pretty much everything, except in my Entities.edmx, Views and my Metadata. I took great care of it and now, verything work like a charm. I still don't understand why I was able to Edit my employes though...

Httpget Method using asp.net mvc in controller

Fetch data from database some error occur here (AdminPurpose con = i.a ) Message show Cannot implicitly converted type.Please see below for my code snippets:
public JsonResult GetInfor()
{
List<AdminPurpose> all = new List<AdminPurpose>();;
using (db_Hajj_UmrahEntities dc= new db_Hajj_UmrahEntities()) {
var datas = (from a in dc.Duas join b in dc.Purposes on a.PurposeId equals b.Id
select new {
a,
b.PurPose1
});
if(datas != null) {
foreach (var i in datas)
{
AdminPurpose con = i.a ;
con.PurPose1 = i.PurPose1;
all.Add(con);
}
}
}
return new JsonResult { Data = all, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
Model class one to many relation here it's using
[MetadataType(typeof(DuaMetaData))]
public partial class AdminPurpose
{
public string PurPose1 { get; set; }
}
public class DuaMetaData
{
public string Dua_Name { get; set; }
public string Arabic_Word { get; set; }
public string Translation_English { get; set; }
public string Source { get; set; }
[Display(Name = "Purpose")]
public int PurposeId { get; set; }
}

How create view for show cookie's info in asp.net mvc using razor?

I'm developing an online store using asp.net mvc 5 and I used cookie for add goods to cart . I want to have a page to show selected items (in cookie) and I don't know how do it, I just wrote an action result for it named Basket . I should use #model List<BasketVM> in my view but when don't know how ?!
could anyone help me please ?
Thanks
GoodController
[HttpGet]
public ActionResult Basket()
{
GoodDetailsRepositories blGoodDetails = new GoodDetailsRepositories();
List<BasketVM> listBasket = new List<BasketVM>();
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = Request.Cookies.Count - 1; i >= 0; i--)
{
if (lst.Where(p => p.Name == Request.Cookies[i].Name).Any() == false)
lst.Add(Request.Cookies[i]);
}
foreach (var item in lst.Where(p => p.Name.StartsWith("NishtmanCart_")))
{
listBasket.Add(new BasketVM {
GoodDetails = blGoodDetails.Find(Convert.ToInt32(item.Name.Substring(13))), Count =Convert.ToInt32(item.Value) });
}
return View(listBasket);
}
BasketVM.cs
public class BasketVM
{
public NP1.Models.GoodDetail GoodDetails { get; set; }
public int Count { get; set; }
}
GoodDetails.cs
public partial class GoodDetail
{
public GoodDetail()
{
this.FactorItems = new HashSet<FactorItem>();
}
public int DetailsGoodID { get; set; }
public int FKSubGoods { get; set; }
public string NishtmanCode { get; set; }
public string DetailsColor { get; set; }
public string DetailsExist { get; set; }
public long DetailsNowPrice { get; set; }
public Nullable<long> DetailsPrePrice { get; set; }
public string DetailsName { get; set; }
public string DetailsLeatherType { get; set; }
public string DetailsWeight { get; set; }
public string DetailsSize { get; set; }
public string DetailsProducer { get; set; }
public string DetailsExtraInfo { get; set; }
public string DetailsURL { get; set; }
public string DetailsKeyWords { get; set; }
public string DetailsTags { get; set; }
public int DetailsLike { get; set; }
public int DetailsDisLike { get; set; }
public string DetailsImage1 { get; set; }
public string DetailsSmallImage1 { get; set; }
public string DetailsImage2 { get; set; }
public string DetailsSmallImage2 { get; set; }
public string DetailsImage3 { get; set; }
public string DetailsSmallImage3 { get; set; }
public string DetailsImage4 { get; set; }
public string DetailsSmallImage4 { get; set; }
public virtual SubGood SubGood { get; set; }
public virtual ICollection<FactorItem> FactorItems { get; set; }
}
Add to cart code
public ActionResult AddToCart (int Id , int Count)
{
try
{
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
//Edit cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Set(cookie);
}
else
{
//Add new cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
List<HttpCookie> lst = new List<HttpCookie>();
for (int i = 0; i < Request.Cookies.Count; i++ )
{
lst.Add(Request.Cookies[i]);
}
bool isGet = Request.HttpMethod == "GET";
int CartCount = lst.Where(p => p.Name.StartsWith("NishtmanCart_") && p.HttpOnly != isGet).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("Good added successfully", MessageType.Success).Script,
Html = "cart items (" + CartCount.ToString() + ")"
}
);
}
catch(Exception)
{
return Json(new MyJsonData()
{
Success = false,
Script = "alert('Good didn't add');",
Html = ""
}
);
}
}
with what name you are saving the cookies you can retrieve like this let say userid u want to get rest what you have wriiten will work:
if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Userid"))
{
HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Userid"];
// retrieve cookie data here
}
how to call in view :
Viewbag.userid = #Request.Cookies["Userid"].value
In order to read a cookie client-side it needs to be created with the HttpOnly flag set to false.
Please go thorugh the below already asked question.
MVC Access stored cookie

Resources