I'm very new to MVC/LINQ so bear with me. I'm wanting to check if that TransmissionStatus var is false and if so linq to db to pull the appropriate failed message.
class AuditLogManagement
{
public int ID { get; set; }
public DateTime Date { get; set; }
public string MsgType { get; set; } //possibly enum?
public AuditLogEventDetails EventDetails { get; set; }
public string MsgContents { get; set; }
public bool TransmissionStatus { get; set; }
public string FailedTransmissionMsg
{
get
{
if (!TransmissionStatus)
{
//linq to db to return failed xmission message
}
}
}
}
Related
I have this model class:
public class MembershipSerial
{
[HiddenInput(DisplayValue=false)]
public int Id { get; set; }
[HiddenInput(DisplayValue=false)]
public string Serial { get; set; }
[Required]
[Display(Name="Membership Serial")]
public string SerialConfirmed { get; set; }
}
I am using EF code-first approach, I would like to check the value of the Serial vs SerialConfirmed and find any Serial which is equal to SerialConfirmed.
I tried below but i get a null exception and don't know how to solve this?
public ActionResult Checkout(UserDetails Details)
{
if (Details.MembershipSerial.Serial.Any().ToString() == Details.MembershipSerial.SerialConfirmed)
{
return View("UserSerial");
}
return View();
}
public class UserDetails : IdentityUser
{
public virtual DeliveryDetails DeliveryDetails { get; set; }
public virtual UserOrders UserOrders { get; set; }
public virtual MembershipSerial MembershipSerial { get; set; }
}
Edit:
public class MembershipSerial
{
[HiddenInput(DisplayValue=false)]
public int Id { get; set; }
[HiddenInput(DisplayValue=false)]
public string Serial { get; set; }
[Required]
[Display(Name="Membership Serial")]
public string SerialConfirmed { get; set; }
}
public class DeliveryDetails
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Company { get; set; }
public string Address { get; set; }
public string AddressLine2 { get; set; }
public string District { get; set; }
public string Province { get; set; }
}
public class UserOrders
{
public int Id { get; set; }
public string ProductName { get; set; }
}
public class MyDbContext : IdentityDbContext<UserDetails>
{
public MyDbContext()
: base ("EFDbContext")
{
}
public System.Data.Entity.DbSet<MembershipSerial> MembershipSerial { get; set; }
public System.Data.Entity.DbSet<DeliveryDetails> DeliveryDetails { get; set; }
public System.Data.Entity.DbSet<UserOrders> UserOrders { get; set; }
}
Any help is appreciated. Thanks in advance.
Your if statement should be like this:
if (Details.MembershipSerial.Serial == Details.MembershipSerial.SerialConfirmed)
Serial and Serial Confirmed are strings so you can just compare them
If you're trying to compare any Serial in the database with the SerialConfirmed that the user is Checking Out then you need a variable to hold a new instance of your connection string: assuming that MemberShipSerial is a table in your database...
using(var db = new ConnectionString())
{
if(db.MembershipSerial.Any(x => x.Serial.ToUpper() == Details.MembershipSerial.SerialConfirmed.ToUpper())
{
/*do something*/
}
}
if you just want to compare Serial and SerialConfirmed based on what the user typed in then use
if(Details.MembershipSerial.Serial.ToUpper() == Details.MembershipSerial.SerialConfirmed.ToUpper())
if the second option returns a null exception then you have to debug on the CheckingIn Action and see if what those properties are holding the values you are expecting
I have the following code:
internal static bool SaveUOSChangeLog(List<Contracts.DataContracts.UOSChangeLog> values, string user)
{
try
{
using(var ctx = new StradaDataReviewContext2())
{
values.ForEach(u => { u.Username = user; u.Changed = DateTime.Now; });
var test = ctx.UOSChangeLog.Add(values);
ctx.SaveChanges();
return true;
}
}
The thing I want to do Is to save values to the database. However, I get a the following error message:
Here is my Contracts.DataContracts.UOSChangeLog:
public int? Id { get; set; }
public int Accident_nr { get; set; }
public int Refnr { get; set; }
public int Action { get; set; }
public string Old_data { get; set; }
public string New_data { get; set; }
public DateTime SearchedFromDate { get; set; }
public DateTime SearchedToDate { get; set; }
public DateTime Changed { get; set; }
public string Username { get; set; }
public string Comment { get; set; }
And here Is my Services.StradaDataReview2Model.UOSChangeLog that are used as a DbSet
[Table("UOSChangeLog")]
public partial class UOSChangeLog
{
[Required]
public int? Id { get; set; }
public int Accident_nr { get; set; }
[Required]
public int Refnr { get; set; }
[Required]
public int Action { get; set; }
[Required]
public string Old_data { get; set; }
[Required]
public string New_data { get; set; }
[Required]
public DateTime SearchedFromDate { get; set; }
[Required]
public DateTime SearchedToDate { get; set; }
[Required]
public DateTime Changed { get; set; }
[Required]
public string Username { get; set; }
[Required]
public string Comment { get; set; }
}
You're trying to add a list with the Add method which takes a single object, just keep it simple and use a foreach:
using(var ctx = new StradaDataReviewContext2())
{
foreach(var value in values)
{
value.Username = user;
value.Changed = DateTime.Now;
ctx.UOSChangeLog.Add(value);
}
ctx.SaveChanges();
return true;
}
Just use a simple foreach, linq is a querying language, not a modifying language.
Please use addrange method.
db.TheTable.AddRange(TheList)
db.SaveChanges();
You can use Entity Framework's .AddRange method to add a collection of objects to your Db.
MSDN
It will look like:
using(var ctx = new StradaDataReviewContext2())
{
values.ForEach(u => { u.Username = user; u.Changed = DateTime.Now; });
var test = ctx.UOSChangeLog.AddRange(values);
ctx.SaveChanges();
return true;
}
I have the following 2 models:
public class Alert
{
public int Id { get; set; }
public DateTime AlertDatetime { get; set; }
public bool Unread { get; set; }
public int? ReadByUserId { get; set; }
public DateTime? ReadDateTime { get; set; }
public DateTime ImportDateTime { get; set; }
public bool AlertHasRecords { get; set; }
//Error Reporting and Recording.
public bool Error { get; set; }
public string ErrorText { get; set; }
public virtual IEnumerable<AlertRecord> Records { get; set; }
}
public class AlertRecord
{
public int Id { get; set; }
public string HospitalNumber { get; set; }
public string ForeName { get; set; }
public string SurName { get; set; }
public DateTime DateOfBirth { get; set; }
public DateTime EventDateTime { get; set; }
public string CrisNumber { get; set; }
public DateTime CreationDateTime { get; set; }
//Link it back to the master Alert!
public int AlertId { get; set; }
public virtual Alert Alert { get; set; }
}
Once the "Alert" Object properties have values in them, I am trying to use EntityFramework to inset this object into my SQL DB like this:
class Program
{
private static Alert MainAlert = new Alert();
private static PrimaryDBContext db = new PrimaryDBContext();
static void Main(string[] args)
{
MainAlert = AlertObjectFactory.GetAlertObject();
db.Alerts.Add(MainAlert);
db.SaveChanges();
}
}
The AlertObjectFactory.cs and The Class responsible for building the list of AlertRecords are here(They are large class files)
https://gist.github.com/anonymous/67a2ae0192257ac51f39
The "Alert" Table is being populated with data, however the 4 records in the
IEnumerable Records
are not being inserted...
Is this functionality possible with EF?
Try changing your IEnumerable to something that implements ICollection such as List
See this answer for more details
I am trying to create a list of customer names that is fetched from a Json call but I get an error:
cannot implicitly convert type System.Collections.Generic.List<char>
to System.Collections.Generic.List<string>
I am using these 2 classes:
Customers:
namespace eko_app
{
static class Customers
{
public static List<CustomerResponse> GetCustomers(string customerURL)
{
List<CustomerResponse> customers = new List<CustomerResponse>();
try
{
var w = new WebClient();
var jsonData = string.Empty;
// make the select products call
jsonData = w.DownloadString(customerURL);
if (!string.IsNullOrEmpty(jsonData))
{
// deserialize the json to c# .net
var response = Newtonsoft.Json.JsonConvert.DeserializeObject<RootObject>(jsonData);
if (response != null)
{
customers = response.response;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return customers;
}
public class BusinessAssociate
{
public string business_associate_id { get; set; }
public string created_by { get; set; }
public DateTime created { get; set; }
public DateTime modified { get; set; }
public bool? deleted { get; set; }
public string business_id { get; set; }
public string identity_id { get; set; }
public string associate_type { get; set; }
public string name { get; set; }
}
public class Identity
{
public string identity_id { get; set; }
public string created_by { get; set; }
public DateTime created { get; set; }
public DateTime modified { get; set; }
public bool? deleted { get; set; }
public string name { get; set; }
public object identity_type { get; set; }
}
public class ChartOfAccount
{
public string chart_of_accounts_id { get; set; }
public DateTime created { get; set; }
public DateTime modified { get; set; }
public string created_by { get; set; }
public string deleted { get; set; }
public string account_id { get; set; }
public string account_name { get; set; }
public string business_id { get; set; }
public string account_category { get; set; }
public string accounts_groups_id { get; set; }
public string cash_equivalent { get; set; }
public string acc_category { get; set; }
public decimal? balance { get; set; }
public decimal? credit_balance { get; set; }
public decimal? debit_balance { get; set; }
public decimal? absolute_balance { get; set; }
public string balance_type { get; set; }
public decimal? raw_balance { get; set; }
public string extended_name { get; set; }
public string normal_balance_type { get; set; }
}
public class CustomerResponse
{
public BusinessAssociate BusinessAssociate { get; set; }
public Identity Identity { get; set; }
public ChartOfAccount ChartOfAccount { get; set; }
}
public class Messages
{
public string msgs { get; set; }
public string errs { get; set; }
}
public class RootObject
{
public List<CustomerResponse> response { get; set; }
public Messages messages { get; set; }
}
}
}
HomeForm:
private void GetCustomerNameList()
{
// get customers
customerURL = "https://eko-app.com/BusinessAssociate/list_associates/1/sessionId:" + sessionID + ".json";
var customers = Customers.GetCustomers(customerURL);
List<string> customerNames = new List<string>();
foreach (var c in customers)
{
customerNames = c.BusinessAssociate.name.ToList(); <--------error thrown here
}
}
The error is thrown at customerNames = c.BusinessAssociate.name.ToList(); on the HomeForm.
What am I doing wrong in creating a list of customer names?
I think you wanted to add all Customer.BusinessAssociate names to list:
foreach (var c in customers)
{
customerNames.Add(c.BusinessAssociate.name);
}
What you originally written converted each name string to char list.
You're assigning a list of chars (string) into a list of strings.
Try something like this outside of the foreach loop:
customerNames = customers.Select(x => x.BusinessAssociate.name).ToList();
This also makes the initialization of cutomerNames redundant.
Instead of foreach use:
customerNames = customers.Select(c => c.BusinessAssociate.name).ToList();
Im trying to get the last record submitted in the db using the repository pattern and MVC. I am attaching the interface and class.And the controller where you can put the code. Please let me know if you need more details. Thanks.
public interface IRequestRepository
{
tblRequest GetCaseId(int caseId);
}
public class RequestRepository: IRequestRepository
{
helpdeskEntities context = null;
public RequestRepository()
{
context = new helpdeskEntities();
}
public string GetCaseId(Ticket ticket)
{
string caseId = string.Empty;
tblRequest tr = context.tblRequests.Where(u => u.CaseID == ticket.CaseID && u.UEmailAddress == ticket.UEmailAddress).SingleOrDefault();
if (tr != null)
{
caseId = tr.CaseID;
}
return caseId;
}
}
public class Ticket
{
public int CaseID { get; set; }
public string Title { get; set; }
[Required]
public string UFirstName { get; set; }
[Required]
public string ULastName { get; set; }
//public string UDisplayName { get; set; }
[Required]
public string UDep_Location { get; set; }
[Required]
public string UEmailAddress { get; set; }
//public string UComputerName { get; set; }
//public string UIPAddress { get; set; }
[Required]
public string UPhoneNumber { get; set; }
[Required]
public string Priority { get; set; }
[Required]
public string ProbCat { get; set; }
//public string IniDateTime { get; set; }
//public string UpdateProbDetails { get; set; }
//public string UpdatedBy { get; set; }
public string InitiatedBy_tech { get; set; }
public string AssignedBy { get; set; }
public string TechAssigned { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string ProbDetails { get; set; }
}
Controller
public ActionResult CreateTicket(tblRequest td)
{
}
First, you need to upgrade your IRequestRepository and add that method:
(I am assuming you're using EntityFramework for that)
public IRequestRepository
{
Request Latest(Ticket ticket);
}
Next, you need to implement that method in your RequestRepository:
public class RequestRepository : IRequestRepository
{
/* other code here */
public Request Latest(Ticket ticket)
{
// I'm also assuming you're using an auto incremented CaseId
return this.context.tblRequests.OrderByDescending(p => p.CaseId).FirstOrDefault(p => p.UEmailAddress == ticket.UEmailAddress);
}
}
And another thing:
Your IRequestRepository.GetCaseId implementation returns a string while it should return a tblRequest (one would also expect it to return an int Id...)
Anyway, I hope this helps!