Creating list of objects with LINQ - c#

I'm trying to change a Dataset into a List of objects. For some reason, I have this error " Error CS7036: There is no argument given that corresponds to the required formal parameter" but I really don't know why...
What am I missing?
Thx in advance
automate.cs
public class Automate
{
private string SrtAutomate { get; set; }
public string AutomateId { get; set; }
public string MachineName { get; set; }
public DateTime LastUpdate { get; set; }
public DateTime LastTreatment { get; set; }
public bool AskStop { get; set; }
public bool AskPause { get; set; }
public string ListeningConfiguration { get; set; }
public string Informations { get; set; }
public Automate(string srtAutomate, string automateId, string machineName,
DateTime lastUpdate, DateTime lastTreatment, bool askStop, bool askPause, string informations, string listeningConfiguration)
{
SrtAutomate = srtAutomate;
AutomateId = automateId;
MachineName = machineName;
LastUpdate = lastUpdate;
LastTreatment = lastTreatment;
AskStop = askStop;
AskPause = askPause;
ListeningConfiguration = listeningConfiguration;
Informations = informations;
}
}
checkTable.cs
public static class CheckTable
{
public static List<Automate> GetAutomaton()
{
DataSet dsAutomate;
List<Automate> lstAutomate = new List<Automate>();
using (var databaseConnexion = new DatabaseConnexion(Parameters.DbSrtServer, Parameters.DbSrtName, Parameters.DbSrtUser, Parameters.DbSrtPassword))
{
string request = "SELECT * FROM SrtAutomateStatus";
//CONNEXION A BDD
try { databaseConnexion.Open(); }
catch (Exception ex) { throw new Exception($"Impossible détablir une connexion à la base : {Parameters.DbSrtName}"); }
DatabaseParamQuery paramQuery = new DatabaseParamQuery(request);
//RECUPERATION DES AUTOMATES
try { dsAutomate = databaseConnexion.GetQueryResults(paramQuery); }
catch (Exception ex) { throw new Exception($"Impossible de récuperer la liste des automates : {ex.Message}"); }
}
lstAutomate = dsAutomate.Tables[0].AsEnumerable().Select(dataRow => new Automate
{
SrtAutomate = dataRow.Field<string>("srtAutomate"),
AutomateId = dataRow.Field<string>("automateId"),
MachineName = dataRow.Field<string>("machineName"),
LastUpdate = dataRow.Field<DateTime>("lastUpdate"),
LastTreatment = dataRow.Field<DateTime>("lastTreatment"),
AskStop = dataRow.Field<bool>("askStop"),
AskPause = dataRow.Field<bool>("askPause"),
Informations = dataRow.Field<string>("informations"),
ListeningConfiguration = dataRow.Field<string>("isteningConfiguration")
}).toList();
return lstAutomate;
}
}

Related

Best way to write application data to a file in WPF

I am using the Caliburn.Micro MVVM pattern.
I am writing an application that has 2 DataGrids, one holds a BindableCollection of RepairOrder, the other a BindableCollection WriteOff.
BindableCollection_WriteOff is property of BindableCollection_RepairOrder. (See the below code).
I need to find a way to write all the RepairOrder including the WriteOff associated with each RO. Besides RepairOrder class holding the WriteOff class, the WriteOff class does not have a way to tie the WriteOff to a RepairOrder.
Repair Order Class:
public class RepairOrder
{
public string Schedule { get; set; }
public string ControlNumber { get; set; }
public int Age { get; set; }
public double Value { get; set; }
public string Note { get; set; }
public double OrgValue { get; set; }
private List<WriteOff> _myWriteOffs;
public List<WriteOff> GetMyWriteOffs()
{
return _myWriteOffs;
}
public void AddMyWriteOff(WriteOff value)
{ _myWriteOffs.Add(value); }
public void DeleteMyWriteOff(WriteOff value)
{ _myWriteOffs.Remove(value); }
public RepairOrder(string CN, string SC, double VL)
{
ControlNumber = CN;
Schedule = SC;
Value = Math.Round(VL, 2);
Note = null;
_myWriteOffs = new List<WriteOff>();
}
public RepairOrder()
{
_myWriteOffs = new List<WriteOff>();
}
public static RepairOrder FromCSV(string CSVLine, string Sched)
{
string[] values = CSVLine.Split(',');
RepairOrder rep = new RepairOrder();
rep.ControlNumber = values[2];
rep.Value = Math.Round(double.Parse(values[5]),2);
rep.Age = int.Parse(values[4]);
rep.Schedule = Sched;
return rep;
}
}
Write Off Class:
public class WriteOff
{
private string _store;
public string Account { get; set; }
public string Description { get; set; }
public double WriteOffAmount { get; set; }
public string Schedule { get; set; }
public string Store
{
get {
if (String.IsNullOrEmpty(_store)) return "";
string temp = _store.Substring(0, 3);
return temp;
}
set { _store = value; }
}
public string Note { get; set; }
public WriteOff(string Acct, string Desc, double Amount, string _store)
{
Account = Acct;
Description = Desc;
WriteOffAmount = Amount;
Store = _store;
}
public string GetWOAccount() {
string SchedAccountNumber = "";
//{ "Navistar", "Cummins", "Misc", "Kenworth", "Mack/Volvo" }
switch (Account)
{
case "Navistar":
SchedAccountNumber = "222000";
break;
case "Cummins":
SchedAccountNumber = "223000";
break;
case "Misc":
SchedAccountNumber = "224500";
break;
default:
SchedAccountNumber = "";
break;
}
return SchedAccountNumber;
}
}

Azure Mobile Service for Windows Phone 8.1 - Insert to existing DB

I am writing an app that has an Azure database. I've never did nything connected with Azure, so I am new to all the stuff. I've found on the internet and at microsoft documentation some tutorials, but I must have got sth wrong, cause it doesn't work. So I have a table at my database called Week, I've created a model in my code:
[DataContract]
public class Week
{
//[JsonProperty(PropertyName = "Id")]
//[DataMember]
public int Id { get; set; }
[JsonProperty(PropertyName = "Book")]
[DataMember]
public Book CurrentBook { get; set; }
[JsonProperty(PropertyName = "Is_Read")]
[DataMember]
public Boolean IsRead { get; set; }
[JsonProperty(PropertyName = "Pages_Read")]
[DataMember]
public int PagesRead { get; set; }
[JsonProperty(PropertyName = "Start_Date")]
[DataMember]
public DateTime StartDate { get; set; }
[JsonProperty(PropertyName = "User")]
[DataMember]
public User Reader { get; set; }
[JsonProperty(PropertyName = "Week_Number")]
[DataMember]
public int WeekNumber { get; set; }
public Week(Book currentBook, Boolean isRead, int pagesRead, DateTime startDate, User reader, int weekNumber)
{
CurrentBook = currentBook;
IsRead = isRead;
PagesRead = pagesRead;
StartDate = startDate;
Reader = reader;
WeekNumber = weekNumber;
}
public Week()
{
}
public int GetMonth()
{
//TODO: Implement the method.
return 0;
}
}
Then I created the WeekRepository for CRUD operations:
public class WeekRepository : BaseRepository<Week>
{
private IMobileServiceTable<Week> weekTable;
public string errorMesage = string.Empty;
public WeekRepository()
{
weekTable = MobileService.GetTable<Week>();
}
public async override Task<int> Save(Week entity)
{
try
{
await weekTable.InsertAsync(entity);
// .ContinueWith(t =>
//{
// if (t.IsFaulted)
// {
// errorMesage = "Insert failed";
// }
// else
// {
// errorMesage = "Inserted a new item with id " + entity.Id;
// }
//});
}
catch (WebException ex)
{
errorMesage = ex.Message;
}
return entity.Id;
}
public override void Update(Week entity)
{
return;
}
public override Week Load(int bookId)
{
var week = weekTable.Where(w => w.IsRead == false).ToListAsync();
return week.Result.Single();
}
public override List<Week> LoadByUserId(int userId)
{
return new List<Week>();
}
public Week LoadCurrentWeek(int userId)
{
return new Week();
}
}
To test if it works, I wrote a simple test:
[TestMethod]
public void ShouldSaveWeekToTheDB()
{
//ARANGE
Week weekTestEntity = new Week(null, false, 10, new DateTime(), null, 1);
//ACT
int id = weekRepository.Save(weekTestEntity).Result;
//ASSERT
var savedItem = weekRepository.Load(1);
Assert.AreEqual(false, savedItem.IsRead);
}
However, InsertAsync() throws an exception - Not Found. I've no idea what I am doing wrong, cause it seems a simple thing as far as I can see from the material on the Internet.
If You could help me, I would be really grateful!
Thank You in advance!
Best Regards,
Roman.

items not adding to a dictionary

i want to add items in a sql database to a dictionary but the values enter as null in the object reference heres the code im using atm
public static Dictionary<string, prizedbinfo> dbprizes = new Dictionary<string, prizedbinfo>();
private void LoadData(string dataloc)
{
if (!File.Exists(dataloc))
{
MessageBox.Show(dataloc + " not found.");
return;
}
var connection = new SQLiteConnection("Data Source=" + dataloc);
connection.Open();
var datacommand = new SQLiteCommand("SELECT prizeID, createdOn, expiresOn, modifiedOn, status, redeemedOn, giftedOn, claimedOn FROM mySnackData", connection);
List<string[]> datas = ExecuteStringCommand(datacommand, 9);
foreach (string[] row in datas)
{
if (!Program.dbprizes.ContainsKey(row[0]))
{
Program.dbprizes.Add(row[0], new prizedbinfo(row));
}
}
connection.Close();
}
and the prizedbinfo object is
class prizedbinfo
{
public prizedbinfo(string[] dbdata)
{
string prizeID = dbdata[0];
string createdOn = dbdata[1];
string expiresOn = dbdata[2];
string modifiedOn = dbdata[3];
string status = dbdata[4];
string redeemedOn = dbdata[5];
string giftedOn = dbdata[6];
string claimedOn = dbdata[7];
string name = dbdata[8];
}
public string prizeID { get; set; }
public string createdOn { get; set; }
public string expiresOn { get; set; }
public string modifiedOn { get; set; }
public string status { get; set; }
public string redeemedOn { get; set; }
public string giftedOn { get; set; }
public string claimedOn { get; set; }
public string name { get; set; }
}
i have tested it with breakpoints and all the data is correctly added to datas and row but not to the prizedbinfo object for some reason
Remove the string keyword from all your variables in the prizedbinfo constructor. You're creating local variables that immediately go out of scope, so you're losing your values.
public prizedbinfo(string[] dbdata)
{
prizeID = dbdata[0];
createdOn = dbdata[1];
expiresOn = dbdata[2];
modifiedOn = dbdata[3];
status = dbdata[4];
redeemedOn = dbdata[5];
giftedOn = dbdata[6];
claimedOn = dbdata[7];
name = dbdata[8];
}

Serialization woes

I have an issue with serialization. I understand that methods can not be serialized for good reason, so I created a factory class to convert my existing class into a more manageable class.
This is the original class:
using Assets.Components;
using Assets.Data;
using IO.Components;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace Assets
{
[Serializable]
public class Asset
{
#region Fields
Metadata _metadata;
string _fileName;
string _companyId;
#endregion
#region Properties
[Required]
public string DisplayName { get; set; }
public string Description { get; set; }
public string Tags { get; set; }
public int Id { get; set; }
public int CategoryId { get; set; }
public AssetType Type { get; set; }
public int LanguageId { get; set; }
public int StatusId { get; set; }
public DateTime DateCreated { get; set; }
public long DateCreatedMilliseconds { get { return DateCreated.ToJavaScriptMilliseconds(); } }
public int Views { get; set; }
public int Downloads { get; set; }
public string ThumbNail { get; set; }
public string Filename
{
set { _fileName = value; }
}
[Required]
public string CompanyId
{
set { _companyId = value; }
}
public string GetBaseDirectory
{
get { return "/Public/Uploads/" + this._companyId + "/0"; }
}
public double Rating
{
get
{
List<int> Score = new List<int>();
foreach (IRating oRating in this.Ratings())
{
Score.Add(oRating.Score);
}
return (Score.Count > 0) ? Score.Average() : 0;
}
}
public Metadata Metadata
{
get
{
if (_metadata == null)
{
_metadata = new Metadata(this.Id);
if (_metadata.AssetId == 0)
{
try
{
if (GetFilename() != null)
{
string path = System.IO.Path.Combine(HttpContext.Current.Server.MapPath(this.GetBaseDirectory), GetFilename());
if (!System.IO.File.Exists(path))
_metadata = new Metadata();
else
{
_metadata = MetadataExtractor.Create(path, this.Id);
_metadata.save();
}
}
else
{
_metadata = new Metadata();
}
}
catch
{
_metadata = new Metadata();
}
}
}
return _metadata;
}
}
public bool IsConverted { get; set; }
public string UserId { get; set; }
public DateTime DateModified { get; set; }
public long DateModifiedMilliseconds { get { return DateCreated.ToJavaScriptMilliseconds(); } }
public string Culture { get; set; }
public string Language { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public int CategoryCount { get; set; }
public int AssetCount { get; set; }
public bool IgnoreRights { get; set; }
#endregion
#region Contructors
/// <summary>
/// Default constructor
/// </summary>
public Asset()
{
}
/// <summary>
/// Get's the asset from the database, but set's the status to the profiles Requires Approval state.
/// </summary>
/// <param name="Id">Asset Id</param>
/// <param name="IsViewing">Boolean to update the reports table</param>
/// <param name="IsDownloading">Boolean to update the reports table</param>
public Asset(int Id, string UserId, string CompanyId, bool IsViewing, bool IsDownloading)
{
try
{
Asset oAsset = AssetData.GetAsset(Id, IsViewing, IsDownloading, UserId, CompanyId);
// Assign the values to this class
this.Id = oAsset.Id;
this.DisplayName = oAsset.DisplayName;
this.IsConverted = oAsset.IsConverted;
this.StatusId = oAsset.StatusId;
this.Type = oAsset.Type;
this.UserId = oAsset.UserId;
this.UserName = oAsset.UserName;
this.CompanyId = oAsset.GetCompanyId();
this.Description = oAsset.Description;
this.Tags = oAsset.Tags;
this.LanguageId = oAsset.LanguageId;
this.Culture = oAsset.Culture;
this.Language = oAsset.Language;
if (oAsset.ThumbNail != null) this.ThumbNail = oAsset.ThumbNail;
this.Filename = oAsset.GetFilename();
if (oAsset.Views != 0) this.Views = oAsset.Views;
if (oAsset.Downloads != 0) this.Downloads = oAsset.Downloads;
}
catch (Exception ex)
{
Stars.BLL.Error.Handling.LogError("Skipstone", "Asset", "Asset", ex.Message, ex.ToString()); // Record our error
}
}
/// <summary>
/// Used for executing some of the public methods
/// </summary>
/// <param name="Id">Id of the asset to retrieve</param>
/// <param name="CompanyId">The CompanyId of the company for the User</param>
public Asset(int Id, string CompanyId)
{
this.Id = Id;
this.CompanyId = CompanyId;
}
#endregion
#region Public methods
public string GetCompanyId()
{
return _companyId;
}
public string GetFilename()
{
return _fileName;
}
public string GetThumbnail()
{
return this.GetBaseDirectory + "/" + this.ThumbNail;
}
public string GetSmallThumbnail()
{
return this.GetBaseDirectory + "/sml_" + this.ThumbNail;
}
public Collection<IRating> Ratings()
{
Collection<IRating> oRatings = new Collection<IRating>();
try
{
oRatings = RatingData.get(this.Id);
}
catch
{
// record our error
}
return oRatings;
}
public Collection<IComment> Comments()
{
Collection<IComment> oComments = new Collection<IComment>();
try
{
oComments = CommentData.getAssetComments(this.Id);
}
catch (Exception ex)
{
// record our error
}
return oComments;
}
public void SaveMetadata()
{
}
public Collection<GenericType> Categories()
{
return MiscellaneousManager.AssetCategories(this.Id, GetCompanyId());
}
public void Save()
{
if (this.Id > 0)
{
AssetData.update(this);
}
else
{
Asset oAsset = AssetData.create(this);
this.Id = oAsset.Id;
this.DisplayName = oAsset.DisplayName;
this.Type = oAsset.Type;
this.UserId = oAsset.UserId;
this.CompanyId = oAsset.GetCompanyId();
this.Description = oAsset.Description;
this.Tags = oAsset.Tags;
this.LanguageId = oAsset.LanguageId;
this.Culture = oAsset.Culture;
this.Language = oAsset.Language;
if (oAsset.ThumbNail != null) this.ThumbNail = oAsset.ThumbNail;
this.Filename = oAsset.GetFilename();
if (oAsset.Views != 0) this.Views = oAsset.Views;
if (oAsset.Downloads != 0) this.Downloads = oAsset.Downloads;
}
}
public void delete()
{
AssetData.delete(this.Id);
AssetManager.RemoveFromCache(this);
}
#endregion
}
}
and this is my factory method:
private static SerialisedAsset AssetFactory(Assets.Asset Object)
{
SerialisedAsset FactoryObject = new SerialisedAsset()
{
Id = Object.Id,
Name = Object.DisplayName,
UserId = Object.UserId,
UserName = Object.UserName,
CompanyId = Object.GetCompanyId(),
Description = Object.Description,
Tags = Object.Tags,
DateCreated = Object.DateCreated,
Path = Object.GetBaseDirectory,
FileName = Object.GetFilename(),
ThumbnailName = Object.ThumbNail
};
return FactoryObject;
}
which is part of my audittrailmanager class:
using Assets;
using Core;
using Reports.Objects;
using System;
using System.IO;
using System.Xml.Serialization;
namespace Reports.Components
{
public static class AuditTrailManager
{
#region Public methods
public static Audit AuditTrailFactory(Profile Profile, Object Object, Event Event)
{
Audit Audit = new Audit(SerializeObject(Object))
{
UserId = Profile.UserId,
UserName = Profile.UserName,
CompanyId = Profile.CompanyId,
ObjectName = GetObjectNameFromType(Object.GetType().ToString()),
Event = Event
};
return Audit;
}
#endregion
#region Private methods
private static string GetObjectNameFromType(string Type)
{
switch (Type)
{
case "Assets.Asset": return "Asset";
case "Core.SiteSetting": return "CompanySettings";
}
return "";
}
private static string SerializeObject(Object Object)
{
string ObjectType = Object.GetType().ToString();
switch (ObjectType)
{
case "Assets.Asset": return Serialize(AssetFactory((Asset)Object));
}
return ""; // If we fail
}
private static string Serialize(Object Object)
{
XmlSerializer ser = new XmlSerializer(Object.GetType());
using (StringWriter Xml = new StringWriter())
{
ser.Serialize(Xml, Object);
return (Xml.ToString());
}
}
private static SerialisedAsset AssetFactory(Assets.Asset Object)
{
SerialisedAsset FactoryObject = new SerialisedAsset()
{
Id = Object.Id,
Name = Object.DisplayName,
UserId = Object.UserId,
UserName = Object.UserName,
CompanyId = Object.GetCompanyId(),
Description = Object.Description,
Tags = Object.Tags,
DateCreated = Object.DateCreated,
Path = Object.GetBaseDirectory,
FileName = Object.GetFilename(),
ThumbnailName = Object.ThumbNail
};
return FactoryObject;
}
#endregion
}
}
What I am trying to do is create an audit trail which records the object I am working on (in this case an asset) and I am serializing the class and inserting it into the database for use in reporting, etc.
My question is; is this the way to do it. Is there a better way?

entity framework saves first item in the loop but none other

In my controller I'm looping through items and saving them to my db. The problem is that it saves the first item, but none of the others. I put a breakpoint on the "SaveItem()" line in the loop and it hits it every time, but what seems odd to me is that it only goes through to the method for the 1st item.
What am I doing wrong?
public void SubmitItem(Cart cart, ShippingDetails shippingDetails, ProcessedItems processedItem, string orderID)
{
var cartItems = cart.Lines;
//CartIndexViewModel cartIndex = new CartIndexViewModel();
//var customID = cartIndex.OrderID;
foreach(var item in cartItems)
{
processedItem.OrderID = orderID;
processedItem.ProductID = item.Product.ProductID;
processedItem.Name = item.Product.Name;
processedItem.Description = item.Product.Description;
processedItem.Price = item.Product.Price;
processedItem.Category = item.Product.Category;
processedItem.ImageName = item.Product.ImageName;
processedItem.Image2Name = item.Product.Image2Name;
processedItem.Image3Name = item.Product.Image3Name;
processedItem.BuyerName = shippingDetails.Name;
processedItem.Line1 = shippingDetails.Line1;
processedItem.Line2 = shippingDetails.Line2;
processedItem.Line3 = shippingDetails.Line3;
processedItem.City = shippingDetails.City;
processedItem.State = shippingDetails.State;
processedItem.Zip = shippingDetails.Zip;
processedItem.Country = shippingDetails.Country;
processedItem.Status = "Submitted";
processedItems.SaveItem(processedItem);
}
}
public class EFProcessedItemsRepository : IProcessedItems
{
private EFDbContext context = new EFDbContext();
public IQueryable<ProcessedItems> ProcessedItem
{
get { return context.ProcessedItems; }
}
public void SaveItem(ProcessedItems processedItem)
{
if(processedItem.ProcessedID == 0)
{
try
{
context.ProcessedItems.Add(processedItem);
context.SaveChanges();
}
catch (Exception)
{
throw;
}
}
else
{
context.Entry(processedItem).State = EntityState.Modified;
}
}
public void DeleteItem(ProcessedItems processedItem)
{
context.ProcessedItems.Remove(processedItem);
context.SaveChanges();
}
}
here is the class for the processedItem:
public class ProcessedItems
{
[Key]
public int ProcessedID { get; set; }
public string OrderID { get; set; }
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
public string ImageName { get; set; }
public string Image2Name { get; set; }
public string Image3Name { get; set; }
public string Status { get; set; }
//shipping
public string BuyerName { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
}
Interface:
public interface IProcessedItems
{
IQueryable<ProcessedItems> ProcessedItem { get; }
void SaveItem(ProcessedItems processedItem);
void DeleteItem(ProcessedItems processedItem);
}
try calling context.SaveChanges() after adding all of the items, I think it should persist them all in one go.
Another thing to try:
Refactor your code so that SaveItem accepts only one item to save, Add it and call SaveChanges()
Loop through the cart items outside the method and call the method with one item to save at a time.
// set orderID, shippingDetails above
foreach(var item in cartItems)
{
ProcessedItems processedItem = new ProcessedItems();
processedItem.OrderID = orderID;
processedItem.ProductID = item.Product.ProductID;
processedItem.Name = item.Product.Name;
processedItem.Description = item.Product.Description;
processedItem.Price = item.Product.Price;
processedItem.Category = item.Product.Category;
processedItem.ImageName = item.Product.ImageName;
processedItem.Image2Name = item.Product.Image2Name;
processedItem.Image3Name = item.Product.Image3Name;
processedItem.BuyerName = shippingDetails.Name;
processedItem.Line1 = shippingDetails.Line1;
processedItem.Line2 = shippingDetails.Line2;
processedItem.Line3 = shippingDetails.Line3;
processedItem.City = shippingDetails.City;
processedItem.State = shippingDetails.State;
processedItem.Zip = shippingDetails.Zip;
processedItem.Country = shippingDetails.Country;
SubmitItem(processedItem);
}
public void SubmitItem(ProcessedItems processedItem)
{
processedItem.Status = "Submitted";
processedItems.SaveItem(processedItem);
}
I think it is because processedItem is the same instance for each loop iteration. So after it has been through SaveItem once, it has its ProcessedID set and therefore won't get processed again.
My first guess is that you always store one entity, which is stored in processedItem, which is a input parameter. Try to create new Entity on each loop and then save it. In other words, you assign values to input parameter
processedItem.OrderID = orderID;
and then store same entity each time, but with changed fields
processedItems.SaveItem(processedItem);

Categories

Resources