Specified cast is not valid C# Entity Framework - c#

Hi I have been getting this Specified cast is not valid in my code but when I connect to my backup database I do not get the Specified cast is not valid error. I am not sure what is going on.
Again, this code works perfectly on one database and gives me the error on the other.
My Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Linq.SqlClient;
using System.Text.RegularExpressions;
using MvcPaging;
using lookups.Models;
using lookups.Helpers;
namespace lookups.Controllers
{
public class MPController : Controller
{
// GET: /Lookups/
public LpAppsDataDataContext db = new LpAppsDataDataContext();
public const int DefaultPageSize = 30;
//get MP Data
if (countSpace == 1 && v.Count(char.IsLetter) > 3)
{
if (SqlString.CheckStringForComma(v))
{
mpq = db.mps
.Where(c => c.NAME_LAST.ToLower().Contains(SqlString.GetSplitCommaString(v.ToLower(), 0))).OrderBy(c => c.NAME_LAST).ThenBy(f => f.NAME_FIRST);
}
else
{
mpq = db.mps
.Where(c => c.NAME_LAST.ToLower().Contains(SqlString.GetSplitString(v.ToLower(), 1)) || c.NAME_LAST.Contains(SqlString.GetSplitString(v.ToLower(), 0))).OrderBy(c => c.NAME_LAST).ThenBy(f => f.NAME_FIRST);
}
}
else
{
mpq = db.mps
.Where(c => c.NAME_L
ViewBag.count = mpq.Count();
}
}
else { ViewBag.count = 0; }
#ViewBag.col = "Unclaimed Pensions";
return View(mpq.ToPagedList(currentPageIndex, DefaultPageSize));
}
}
}
My Model
[global::System.Data.Linq.Mapping.TableAttribute(Name = "dbo.mp")]
public partial class mp
{
private string _COMPANY;
private string _STATE;
private System.Nullable<System.DateTime> _DOPT;
private string _SP_STATE;
private string _PRT_NAME;
private string _NAME_LAST;
private string _NAME_FIRST;
private string _LASTADDRESS;
private System.Nullable<double> _ID;
private System.Nullable<System.DateTime> _DATE;
private string _PLAN_TYPE;
public mp()
{
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_COMPANY", DbType = "NVarChar(255)")]
public string COMPANY
{
get
{
return this._COMPANY;
}
set
{
if ((this._COMPANY != value))
{
this._COMPANY = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_STATE", DbType = "NVarChar(255)")]
public string STATE
{
get
{
return this._STATE;
}
set
{
if ((this._STATE != value))
{
this._STATE = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_DOPT", DbType = "DateTime")]
public System.Nullable<System.DateTime> DOPT
{
get
{
return this._DOPT;
}
set
{
if ((this._DOPT != value))
{
this._DOPT = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_SP_STATE", DbType = "NVarChar(255)")]
public string SP_STATE
{
get
{
return this._SP_STATE;
}
set
{
if ((this._SP_STATE != value))
{
this._SP_STATE = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_PRT_NAME", DbType = "NVarChar(255)")]
public string PRT_NAME
{
get
{
return this._PRT_NAME;
}
set
{
if ((this._PRT_NAME != value))
{
this._PRT_NAME = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_NAME_LAST", DbType = "NVarChar(255)")]
public string NAME_LAST
{
get
{
return this._NAME_LAST;
}
set
{
if ((this._NAME_LAST != value))
{
this._NAME_LAST = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_NAME_FIRST", DbType = "NVarChar(255)")]
public string NAME_FIRST
{
get
{
return this._NAME_FIRST;
}
set
{
if ((this._NAME_FIRST != value))
{
this._NAME_FIRST = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_LASTADDRESS", DbType = "NVarChar(255)")]
public string LASTADDRESS
{
get
{
return this._LASTADDRESS;
}
set
{
if ((this._LASTADDRESS != value))
{
this._LASTADDRESS = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_ID", DbType = "Float")]
public System.Nullable<double> ID
{
get
{
return this._ID;
}
set
{
if ((this._ID != value))
{
this._ID = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_DATE", DbType = "DateTime")]
public System.Nullable<System.DateTime> DATE
{
get
{
return this._DATE;
}
set
{
if ((this._DATE != value))
{
this._DATE = value;
}
}
}
[global::System.Data.Linq.Mapping.ColumnAttribute(Storage = "_PLAN_TYPE", DbType = "NVarChar(255)")]
public string PLAN_TYPE
{
get
{
return this._PLAN_TYPE;
}
set
{
if ((this._PLAN_TYPE != value))
{
this._PLAN_TYPE = value;
}
}
}
}
StackTrace
Line 257: #ViewBag.col = "Unclaimed Pensions";
Line 258:
Line 259: return View(mpq.ToPagedList(currentPageIndex, DefaultPageSize));
Line 260: }
Line 261:
Stack Trace:
[InvalidCastException: Specified cast is not valid.]
System.Data.SqlClient.SqlBuffer.get_Double() +51
System.Data.SqlClient.SqlDataReader.GetDouble(Int32 i) +62
Read_mp(ObjectMaterializer`1 ) +2057
System.Data.Linq.SqlClient.ObjectReader`2.MoveNext() +32
System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection) +392
System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection) +10
MvcPaging.PagedList`1..ctor(IQueryable`1 source, Int32 index, Int32 pageSize, Nullable`1 totalCount) +2014
MvcPaging.PagingExtensions.ToPagedList(IQueryable`1 source, Int32 pageIndex, Int32 pageSize, Nullable`1 totalCount) +134
lookups.Controllers.MPController.Mp(Nullable`1 page, String sortOrder) in

Compare the backup database with the database that doesn't work, specifically the ID column. Make sure they match both the Type (Float) and ability to be Nullable (NULL).
The exception being thrown indicates that one of the columns (that is of type "double") doesn't match the model.
The ID column on the "mp" table is the only double column in your model.

In SQL Server Developer 2019, I used the sys tables to create a SQL script to determine what SQL Server thinks are the types per columns.
select
obj.name as [Table]
, col.name as [Column]
, case
when type.[precision] > 0 and type.scale = 0 then type.name + '(' + CONVERT(nvarchar(8), type.precision) + ')'
when type.[precision] > 0 and type.scale > 0 then type.name + '(' + CONVERT(nvarchar(8), type.precision) + ',' + CONVERT(nvarchar(8), type.scale) + ')'
else type.name end as [FullType]
from
sys.objects as [obj]
inner join sys.columns as [col]
on obj.object_id = col.object_id
inner JOIN sys.types as [type]
on col.system_type_id = type.system_type_id
where
obj.type = N'U'
I could then use script in a common table expressions (CTE) or other similar structure to filter on specific columns.

Related

How to read null values out of a integer column in sql to C#?

i am trying to make a project for my school. I am trying to read a table where some null values are in an integer column. I've made it an integer but i can't get the null values into the integer.
I've already searched in stackoverflow but none of the answers i could make at my project. Can someone provide me some help, tell me where i have to put the code to make it work again. I just started as programmer.
This is my database conn string + reader:
public static List<Klant> GetAlleklanten()
{
var result = new List<Klant>();
using (var conn = new SqlConnection(ConnectionString))
{
conn.Open();
const string query = "select k.klantid, k.naam, k.adres, k.telefoonnummer, k.woonplaats, k.email, k.wachtwoord, kp.klantpasid from klant k left join klantpas kp on k.klantid = kp.klantid";
SqlCommand selectKamers = new SqlCommand(query, conn);
SqlDataReader reader = selectKamers.ExecuteReader();
while (reader.Read())
{
Klant klant = new Klant((int)reader["klantid"], (string)reader["naam"], (string)reader["adres"], (string)reader["telefoonnummer"], (string)reader["woonplaats"], (string)reader["email"], (string)reader["wachtwoord"], (int)reader["klantpasid"]);
result.Add(klant);
}
reader.Close();
}
return result;
}
klantpasid is the one that also can return a null value instead of an integer.
Here is the class where the klantpasid is in the construtor:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FontysHotel
{
public class Klant
{
// instantie variabelen
private int klantid;
private string naam;
private string adres;
private string telefoonnummer;
private string woonplaats;
private string email;
private string wachtwoord;
private int? klantpasid;
// properties
public int Klantid
{
get
{
return klantid;
}
set
{
klantid = value;
}
}
public string Naam
{
get
{
return naam;
}
set
{
naam = value;
}
}
public string Adres
{
get
{
return adres;
}
set
{
adres = value;
}
}
public string Telefoonnummer
{
get
{
return telefoonnummer;
}
set
{
telefoonnummer = value;
}
}
public string Woonplaats
{
get
{
return woonplaats;
}
set
{
woonplaats = value;
}
}
public string Email
{
get
{
return email;
}
set
{
email = value;
}
}
public string Wachtwoord
{
get
{
return wachtwoord;
}
set
{
wachtwoord = value;
}
}
public int? Klantpasid
{
get
{
return klantpasid;
}
set
{
klantpasid = value;
}
}
// Constructor
public Klant(int klantid, string naam, string adres, string telefoonnummer, string woonplaats, string email, string wachtwoord, int klantpasid)
{
Klantid = klantid;
Naam = naam;
Adres = adres;
Telefoonnummer = telefoonnummer;
Woonplaats = woonplaats;
Email = email;
Wachtwoord = wachtwoord;
Klantpasid = klantpasid;
}
}
}
Please provide me some help, tell me where i have to place the right code so i can continue my school project. The error i am getting now is ''' The specified conversion is invalid
'''
You can check klantid for DBNull.Value, and if it is, assign corresponding special int value; so instead of
(int)reader["klantid"]
put
reader.IsDBNull(reader.GetOrdinal("klantid")) ? -1 : Conver.ToInt32(reader["klantid"])
a better way is to declare private int klantid; as private int? klantid; (nullable int):
private int? klantid; // it can accept null now
public int? Klantid
{
get
{
return klantid;
}
set
{
klantid = value;
}
}
then while reading from reader we can use turnary operator:
KlantId = !reader.IsDBNull(reader.GetOrdinal("klantid"))
? Conver.ToInt32(reader["klantid"])
: null;
I know a fix for you,
You change Klantpasid from int? to int
If klantpasid is null in your database, we set the value to 0 instead of null
public int Klantpasid
{
get
{
return klantpasid;
}
set
{
if( value == null){
klantpasid = 0;
}else {
klantpasid = value;
}
}
}
You can declare your property as nullable
public int? Klantid
{
get
{
return klantid;
}
set
{
klantid = value;
}
}
Check out more on documentation.
When you read your data with a DataReader, it will return DBNull.Value. Whe you want to fill your Klant.Klantpasid value (which is of type Nullable<int>), you will have to convert the value to Nullable<int> yourself. When ADO.NET was first implemented, there were no nullable values, so they introduced DBNull instead. More modern approaches like Entity Framework use nullable types instead.
You can write a helper method to help converting your read value to a nullable type:
static T? AsNullable<T>(object value) where T : struct {
switch (value) {
case T converted:
return converted;
case DBNull:
return default(T?);
default:
throw new InvalidCastException();
}
}
So instead of...
(int)reader["klantpasid"]
...you write:
AsNullable<int>(reader["klantpasid"])
And of course you change the type of your constructor parameter from int to int?.

How can I modify a static property?

I am tring to motify a static property, I don't know where I am getting wrong. Here is the code.
public static string Id
{
get { return Id; }
set
{
if (Id.Length < Idlen)
{
var zero = new string('0', Idlen - Id.Length);
Id = zero + Id;
Id = value;
}
else
{
Id = Id.Substring(Id.Length - Idlen);
Id = value;
}
}
}
public static int Idlen { get; set; }
So here is an example of what I think you are trying to achieve. (Although ReSharper is telling me not to use these field names...)
private static string _Id;
public static string Id
{
get => _Id;
set // You want to use value here (new value), not Id (old value)
{
if (value == null)
{
// Consider what you want to do if user calls Id = null
_Id = new string('0', Idlen);
}
else if (value.Length < Idlen)
{
var zero = new string('0', Idlen - value.Length);
_Id = zero + value;
}
else
{
_Id = value.Substring(value.Length - Idlen);
}
}
}
public static int Idlen { get; set; }

Huge List<T> processing and Pdf generate

I have a pdf file as Byte[] and I'm using iTextSharp to modify the file and embed a specific details in it.
in the List I have min. 25K objects, and I need to generate 25K pdf files.
I'm using Parallel.ForEach but it takes 16.40 mins to be done in Total.
I used ToLookUp method like this:
var valuesToLookupWith = Recipients.ToLookup(item => item.ID);
List<int> Ids = Recipients.Select(item => item.ID).ToList();
Partitioner<int> partitioner = Partitioner.Create(Ids, EnumerablePartitionerOptions.NoBuffering);
Parallel.ForEach(partitioner, new ParallelOptions { MaxDegreeOfParallelism = 6 } ,(id) =>
{
var item = valuesToLookupWith[id].ToList().FirstOrDefault();
item.Attachment = AttachmentEngine.GeneratePdfFromPdfFile((fileAsByteArray,id, "www.xyz.ca"));
...
});
and I used ForEach and also it takes approx. > 25 minutes.
foreach (int id in Ids)
{
var item = valuesToLookupWith[id].ToList().FirstOrDefault();
item.Attachment = AttachmentEngine.GeneratePdfFromPdfFile(fileAsByteArray,id, "www.xyz.ca");
...
}
any suggested way to speedup the process please?
FYI I'm not writing anything on the disk, all is done in memory as Byte[] and then I'm writing the values back to the Db.
and also all the time spent - mentioned in the question is only the time spent for Parallel.ForEach / ForEach statements.
Db calls is not an issue for me at all, I'm making only two calls to the Db , one when I load list of recipients from it and another call when writing values back to the Db
public static byte[] GeneratePdfFromPdfFile(byte[] file, int id, string landingPage)
{
try
{
using (var ms = new MemoryStream())
{
//Create an iTextSharp Document which is an abstraction of a PDF but **NOT** a PDF
var doc = new iTextSharp.text.Document();
//Create a writer that's bound to our PDF abstraction and our stream
var writer = PdfWriter.GetInstance(doc, ms);
//Open the document for writing
doc.Open();
PdfContentByte cb = writer.DirectContent;
// doc.NewPage();
//var srHtml = new StringReader(source);
////parse html code to xml
//iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, srHtml);
PdfReader reader = new PdfReader(file);
for (int pageNumber = 1; pageNumber < reader.NumberOfPages + 1; pageNumber++)
{
doc.SetPageSize(reader.GetPageSizeWithRotation(1));
doc.NewPage();
//Insert to Destination on the first page
PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);
int rotation = reader.GetPageRotation(pageNumber);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageNumber).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
// Add a new page to the pdf file
doc.NewPage();
// set pdf open action to open the link embedded in the file.
string _embeddedURL = "http://" + landingPage + "/Default.aspx?code=" + GetCampaignRecipientCode(id) + "&m=" + eventCode18;
PdfAction act = new PdfAction(_embeddedURL);
writer.SetOpenAction(act);
doc.Close();
return ms.ToArray();
}
}
catch { return null; }
}
Recipient Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CampaignLauncherLibrary
{
public class CampaignRecipientLib
{
private int _id;
private int _crid;
private string _crcode;
private int _cmpId;
private string _cmpStatus;
private string _email;
private string _firstName;
private string _lastName;
private string _language;
private string _cmpDefaultlanguage;
private bool _isdoubleBarrle;
private DateTime? _scheduled;
private string _offset;
private string _emailTo;
private string _emailFrom;
private string _emailBody;
private string _emailSubject;
private byte[] _emailAttachment;
private string _emailReplyTo;
private string _attachmentName;
private bool _readytobesent;
private bool _pickupready;
private TimeSpan _Toffset;
private int? _cmprIDnextRecipient;
private string _CampaignGroupCode;
private bool _Reschedule;
private List<int> _Campaigns;
private List<int> _SentCampaigns;
private bool _restrictToWorkHours;
private TimeSpan? _whStart;
private TimeSpan? _whEnd;
private string _emailName;
public CampaignRecipientLib()
{
}
public CampaignRecipientLib(CampaignRecipientLib _recipient)
{
ID = _recipient.ID;
CampaignId = _recipient.CampaignId;
CampaignStatus = _recipient.CampaignStatus;
CMPRID = _recipient.CMPRID;
CMPRCode = Guid.NewGuid().ToString("N");
Email = _recipient.Email;
FirstName = _recipient.FirstName;
LastName = _recipient.LastName;
Language = _recipient.Language;
DefaultLanguage = _recipient.DefaultLanguage;
IsdoubleBarrle = _recipient.IsdoubleBarrle;
Scheduled = _recipient.Scheduled;
Offset = _recipient.Offset;
EmailTo = _recipient.EmailTo;
EmailFrom = _recipient.EmailFrom;
EmailBody = _recipient.EmailBody;
EmailSubject = _recipient.EmailSubject;
EmailAttachment = _recipient.EmailAttachment;
EmailReplyTo = _recipient.EmailReplyTo;
AttachmentName = _recipient.AttachmentName;
ReadyTobeSent = _recipient.ReadyTobeSent;
PickupReady = _recipient.PickupReady;
IDnextRecipient = _recipient.IDnextRecipient;
CampaignGroupCode = _recipient.CampaignGroupCode;
Reschedule = _recipient.Reschedule;
Campaigns = _recipient.Campaigns;
SentCampaigns = _recipient.SentCampaigns;
EmailName = _recipient.EmailName;
Toffset = _recipient.Toffset;
}
public void AssingRandomCampaign()
{
int result = 0;
List<int> cmp = _Campaigns;
List<int> sentcmp = _SentCampaigns;
if (cmp.Where(x => !sentcmp.Distinct().Contains(x)).ToList().Count > 0)
{
cmp = cmp.Where(x => !sentcmp.Distinct().Contains(x)).ToList();
result = cmp.Shuffle().Take(1).ToList()[0];
}
else
{
int N = 0;
if (sentcmp.Count == 2) N = 1;
else if (sentcmp.Count == 3) N = 2;
else N = sentcmp.Count % 2 == 0 ? 2 : 3;
List<int> lastN = sentcmp.Skip(Math.Max(0, sentcmp.Count) - N).ToList();
cmp = cmp.Where(predicate: x => !lastN.Contains(x)).ToList();
sentcmp = sentcmp.Where(predicate: x => cmp.Contains(x)).ToList();
List<int> grpOccurrences = sentcmp.GroupBy(i => i).OrderByDescending(item => item.Count()).SelectMany(i => i).Distinct().ToList();
result = grpOccurrences.Shuffle().PickRandom(1).ToList()[0];
}
if (result > 0)
{
_SentCampaigns.Add(result);
CampaignId = result;
}
}
public bool reAdjustScheduleDate()
{
try
{
Scheduled = Utilities.FixDate(Scheduled.Value, RestrictToWorkHours, Offset, WhStart, WhEnd);
}
catch (Exception ex)
{
return false;
}
return true;
}
public TimeSpan Toffset
{
get { return _Toffset; }
set { _Toffset = value; }
}
public string EmailName
{
get { return _emailName; }
set { _emailName = value; }
}
public int? IDnextRecipient
{
get { return _cmprIDnextRecipient; }
set { _cmprIDnextRecipient = value; }
}
public string CampaignGroupCode
{
get { return _CampaignGroupCode; }
set { _CampaignGroupCode = value; }
}
public bool RestrictToWorkHours
{
get { return _restrictToWorkHours; }
set { _restrictToWorkHours = value; }
}
public TimeSpan? WhStart
{
get { return _whStart; }
set { _whStart = value; }
}
public TimeSpan? WhEnd
{
get { return _whEnd; }
set { _whEnd = value; }
}
public bool Reschedule
{
get { return _Reschedule; }
set { _Reschedule = value; }
}
public List<int> Campaigns
{
get { return _Campaigns; }
set { _Campaigns = value; }
}
public List<int> SentCampaigns
{
get { return _SentCampaigns; }
set { _SentCampaigns = value; }
}
public int ID
{
get { return _id; }
set { _id = value; }
}
public int CMPRID
{
get { return _crid; }
set { _crid = value; }
}
public string CMPRCode
{
get { return _crcode; }
set { _crcode = value; }
}
public int CampaignId
{
get { return _cmpId; }
set { _cmpId = value; }
}
public string CampaignStatus
{
get { return _cmpStatus; }
set { _cmpStatus = value; }
}
public string Email
{
get { return _email; }
set { _email = value; }
}
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
public string Language
{
get { return _language; }
set { _language = value; }
}
public string DefaultLanguage
{
get { return _cmpDefaultlanguage; }
set { _cmpDefaultlanguage = value; }
}
public bool IsdoubleBarrle
{
get { return _isdoubleBarrle; }
set { _isdoubleBarrle = value; }
}
public DateTime? Scheduled
{
get { return _scheduled; }
set { _scheduled = value; }
}
public string EmailTo
{
get { return _emailTo; }
set { _emailTo = value; }
}
public string Offset
{
get { return _offset; }
set { _offset = value; }
}
public string EmailFrom
{
get { return _emailFrom; }
set { _emailFrom = value; }
}
public string EmailBody
{
get { return _emailBody; }
set { _emailBody = value; }
}
public string EmailSubject
{
get { return _emailSubject; }
set { _emailSubject = value; }
}
public byte[] EmailAttachment
{
get { return _emailAttachment; }
set { _emailAttachment = value; }
}
public string EmailReplyTo
{
get { return _emailReplyTo; }
set { _emailReplyTo = value; }
}
public string AttachmentName
{
get { return _attachmentName; }
set { _attachmentName = value; }
}
public bool ReadyTobeSent
{
get { return _readytobesent; }
set { _readytobesent = value; }
}
public bool PickupReady
{
get { return _pickupready; }
set { _pickupready = value; }
}
}
}

protobuf-net Specified method is not supported

I have recently decided to use protobuf-net to serialize large plain text data files my application uses to see if there is any performance gain over parsing the plain text data.
Data Class:
[ProtoContract]
public class ClimateFile : BaseModel
{
#region Properties
[ProtoMember(1)]
public double Latitude { get { return GetValue(() => Latitude); } private set { SetValue(() => Latitude, value); } }
[ProtoMember(2)]
public double Longitude { get { return GetValue(() => Longitude); } private set { SetValue(() => Longitude, value); } }
[ProtoMember(3)]
public string Notes { get { return GetValue(() => Notes); } set { SetValue(() => Notes, value); } }
[ProtoMember(4)]
public DateTime MinDate { get { return GetValue(() => MinDate); } private set { SetValue(() => MinDate, value); } }
[ProtoMember(5)]
public DateTime MaxDate { get { return GetValue(() => MaxDate); } private set { SetValue(() => MaxDate, value); } }
[ProtoMember(6)]
public List<ClimateDailyData> DailyData { get { return GetValue(() => DailyData); } private set { SetValue(() => DailyData, value); } }
#endregion
#region Method
public static ClimateFile Load(string filePath)
{
try
{
var ext = Path.GetExtension(filePath).ToUpper();
if (ext == ".P51")
return new ClimateFile(filePath);
else if (ext == ".P51X")
{
ClimateFile climateFile;
using (var file = File.OpenRead(filePath))
{
climateFile = Serializer.Deserialize<ClimateFile>(file);
}
return climateFile;
}
}
catch (Exception e)
{
throw new InvalidDataException(String.Format("The file \"{0}\" could not be opened, {1}", filePath, ExceptionUtilities.JoinExceptionMessages(e)));
}
throw new ArgumentException("filePath was not a .P51 or .P51X file.");
}
public void LoadP51File(string filePath)
{
List<string[]> lines = GetFileLines(filePath);
Latitude = double.Parse(lines[0][0]);
Longitude = double.Parse(lines[0][1]);
for (int i = 2; i < lines[0].Length; ++i)
Notes += String.Format("{0} ", lines[0][i]);
MinDate = GetDate(lines[2][0]);
MaxDate = GetDate(lines[lines.Count - 1][0]);
// Parse daily data
lines.RemoveRange(0, 2);
var dailyData = lines.Select(row => new ClimateDailyData()
{
DataDate = GetDate(row[0]),
MaxTemperature = double.Parse(row[2]),
MinTemperature = double.Parse(row[3]),
Rainfall = double.Parse(row[4]),
Evaporation = double.Parse(row[5]),
SolarRadiation = double.Parse(row[6])
}).ToList();
DailyData = dailyData;
}
public void SaveP51XFile(string filePath)
{
using (var file = File.Create(filePath))
{
Serializer.Serialize<ClimateFile>(file, this);
}
}
public List<string[]> GetFileLines(string filePath)
{
var rows = new List<string[]>();
var cells = new List<string>();
var cell = new StringBuilder();
using (var fs = new BufferedStream(File.OpenRead(filePath)))
{
int buffer;
while ((buffer = fs.ReadByte()) != -1)
{
char nextChar = (char)buffer;
if (nextChar >= '!') // If the character is a non-whitespace printable character
{
cell.Append(nextChar);
continue;
}
if (nextChar == ' ' || nextChar == '\t')
{
if (cell.Length > 0)
{
cells.Add(cell.ToString());
cell.Clear();
}
continue;
}
if (nextChar == '\r' || nextChar == '\n')
{
if (cell.Length > 0)
{
cells.Add(cell.ToString());
cell.Clear();
}
if (cells.Count > 0)
{
rows.Add(cells.ToArray());
cells.Clear();
}
continue;
}
throw new InvalidDataException("The climate file contains unknown characters.");
}
if (cell.Length > 0)
cells.Add(cell.ToString());
if (cells.Count > 0)
rows.Add(cells.ToArray());
}
return rows;
}
public DateTime GetDate(string date)
{
return DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);
}
public override void Dispose()
{
if (Disposed)
return;
if (DailyData != null)
foreach (ClimateDailyData dailyData in DailyData)
dailyData.Dispose();
base.Dispose();
}
#endregion
#region Initialization
public ClimateFile()
{
}
public ClimateFile(string filePath)
{
LoadP51File(filePath);
}
#endregion
}
Collection Data Class:
[ProtoContract]
public class ClimateDailyData : BaseModel
{
[ProtoMember(1)]
public DateTime DataDate { get { return GetValue(() => DataDate); } set { SetValue(() => DataDate, value); } }
[ProtoMember(2)]
public int JulianDay { get { return DataDate.DayOfYear; } }
[ProtoMember(3)]
public double MaxTemperature { get { return GetValue(() => MaxTemperature); } set { SetValue(() => MaxTemperature, value); } }
[ProtoMember(4)]
public double MinTemperature { get { return GetValue(() => MinTemperature); } set { SetValue(() => MinTemperature, value); } }
[ProtoMember(5)]
public double Rainfall { get { return GetValue(() => Rainfall); } set { SetValue(() => Rainfall, value); } }
[ProtoMember(6)]
public double Evaporation { get { return GetValue(() => Evaporation); } set { SetValue(() => Evaporation, value); } }
[ProtoMember(7)]
public double SolarRadiation { get { return GetValue(() => SolarRadiation); } set { SetValue(() => SolarRadiation, value); } }
}
Serialization Command:
public ICommand ImportP51
{
get
{
return new RelayCommand(delegate
{
OpenFileDialog openDialogue = new OpenFileDialog()
{
AddExtension = true,
CheckPathExists = true,
CheckFileExists = true,
DefaultExt = ".p51",
Filter = "Climate Files|*.p51",
InitialDirectory = DataPath,
Multiselect = false,
Title = "Select a File to Open"
};
if ((bool)openDialogue.ShowDialog())
{
string filePath = String.Empty;
try
{
filePath = openDialogue.FileName;
var climate = new Climate();
climate.FilePath = filePath;
var savePath = String.Format("{0}\\{1}.p51x", ClimateDataPath, Path.GetFileNameWithoutExtension(filePath));
climate.FileData.SaveP51XFile(savePath);
}
catch (Exception e)
{
MessageBox.Show(String.Format("The file \"{0}\" could not be opened, {1}", filePath, ExceptionUtilities.JoinExceptionMessages(e)), "Invalid File");
}
}
});
}
}
When executing ImportP51, I get the exception "Specified method is not supported", I am using protobuf-net V2 r594 which was released on the 12/10/2012 and am thinking of trying to use one of the previous versions if I cannot get it to work with this version. Can someone please tell me what I am doing wrong?
I've tried to reconstruct a working version of the code (since I don't have your BaseModel) which I've done by using automatically implemented properties and adding an initializer for the list (DailyData), and explicitly referencing r594 from google-code. The only error I get is:
Cannot apply changes to property ClimateDailyData.JulianDay
which makes sense, because it can't rightly deserialize data into a read-only property, so I removed the serialization marker from that one:
// [ProtoMember(2)] removed - serialized implicitly via DataData
public int JulianDay { get { return DataDate.DayOfYear; } }
After that it worked fine. Since I don't have your command framework, I have:
static class Program
{
static void Main()
{
var climateFile = new ClimateFile();
climateFile.InitSomeDataForSerialization();
climateFile.SaveP51XFile("foo.P51X");
var clone = ClimateFile.Load("foo.P51X");
}
}
where InitSomeDataForSerialization just sets some of the values (since they have private setters, I can't do that in Main):
public void InitSomeDataForSerialization()
{
Longitude = 10; Latitude = 4; Notes = "Test";
DailyData.Add(
new ClimateDailyData { DataDate = DateTime.Today, MinTemperature = 12, MaxTemperature = 35}
);
}
And... it works.
On a hunch, I checked what happens if you reference "CoreOnly" instead of "Full", but that then refuses to compile because Serializer.Serialize<T> and Serializer.Deserialize<T> don't exist.
I'm happy to help, but as far as I can tell, nothing is wrong.
Things I would suggest next:
show the full stack-trace of what happens in this exception, including any inner-exceptions (see the fix below)
please check exactly which file you referenced in the 594 zip (look at "What Files Do I Need.txt", but I'd guess the correct one for you is "Full/net30/..."; the nuget package configures the most appropriate files automatically)
please show a fully reproducible example, i.e. where I can press F5 and see the exact exception (I had to change the code in the example for it to compile, which means I am no longer testing the same thing)
Fix for correct exception wrapping:
catch (Exception e)
{
throw new InvalidDataException(String.Format("The file \"{0}\" could not be opened", filePath), e);
}

Error message Error 5 Ambiguity

here i am getting this error message:
Error 5 Ambiguity between
'OPTFDashboard.Common.Modules.CNAAll.ViewModels.CNAAllViewModel.Shift'
and
'OPTFDashboard.Common.Modules.CNAAll.ViewModels.CNAAllViewModel.Shift' C:\OPTFDashboard\Common\Modules\CNAAll\ViewModels\CNAAllViewModel.cs 34 117 Common
I am trying to bind the selected nurses shift (day,eve, all) to refresh the data displayed per this choice.
using System;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Windows.Data;
using OPTFDashboard.Common.Modules.CNABathing.DataAccess;
using OPTFDashboard.Common.Ribbon;
using OPTFDashboard.Common.Utility;
using OPTFDashboard.DataModel;
using OPTFDashboard.ViewModel;
using OPTFDashboard.Common.Modules.CNAAll.DataAccess;
namespace OPTFDashboard.Common.Modules.CNAAll.ViewModels
{
[Export]
class CNAAllViewModel : TabViewModel, ISelectedContentTab
{
private readonly String[] _shift = new String[] { "ALL", "DAY", "EVE", "NIGHT" };
public CNAAllViewModel()
: base()
{
DisplayName = "All CNA";
StartDate = DateTime.Now.AddMonths(-3);
EndDate = DateTime.Now.AddDays(19);
GroupDataCollection = new ObservableCollection<GroupData>()
{
RibbonControlHelper.CreateFacilitySelection()
, new GroupData("Criterria"
, RibbonControlHelper.CreateDateSelection(StartDate,EndDate,(s, e) => { StartDate = s; EndDate = e; RefreshData(); })
, RibbonControlHelper.CreateUnitSelection(UnitChanged)
, RibbonControlHelper.CreateComboBox("Shift", "Shift", "Select Shift to show.", _shift, (type) => { Shift = type; })
)
};
}
private string Shift;
private DateTime startDate;
public DateTime StartDate
{
get { return startDate; }
set { startDate = value; }
}
private DateTime endDate;
public DateTime EndDate
{
get { return endDate; }
set { endDate = value; }
}
public ObservableCollection<GroupData> GroupDataCollection { get; private set; }
private String UnitCode { get; set; }
private void UnitChanged(Unit unit)
{
UnitCode = unit == null ? "" : unit.Description;
RefreshData();
}
protected override void RefreshData()
{
if (FacilitiesAreChanging) { return; }
Loading = true;
// this is the details section.
// Load CNABathing
CNAAllRepository.DetailedCNABathing(FacilitySelectionService.SelectedFacilities, StartDate, EndDate, UnitCode,
(cnabathingdetails) =>
{
var data = new ListCollectionView(cnabathingdetails);
data.GroupDescriptions.Add(new PropertyGroupDescription("FACILITY_KEY"));
data.GroupDescriptions.Add(new PropertyGroupDescription("UNIT"));
DataCNABathing = data;
});
CNAAllRepository.DetailedCNABowel(FacilitySelectionService.SelectedFacilities, startDate, endDate, UnitCode,
(cna) =>
{
var data = new ListCollectionView(cna);
data.GroupDescriptions.Add(new PropertyGroupDescription("FACILITY_KEY"));
data.GroupDescriptions.Add(new PropertyGroupDescription("UNIT"));
DataCNABowel = data;
});
CNAAllRepository.DetailedCNAIntakeVSOutput(FacilitySelectionService.SelectedFacilities, StartDate, EndDate, UnitCode,
(CNAIntakeVSOutputDetails) =>
{
var data = new ListCollectionView(CNAIntakeVSOutputDetails);
data.GroupDescriptions.Add(new PropertyGroupDescription("FACILITY_KEY"));
data.GroupDescriptions.Add(new PropertyGroupDescription("UNIT"));
DataCNAIntakeVSOutput = data;
});
CNAAllRepository.DetailedCNAPoorEating((FacilitySelectionService.SelectedFacilities), startDate, endDate, UnitCode, "0",
(cnaPoorEatingDetail) =>
{
var data = new ListCollectionView(cnaPoorEatingDetail);
data.GroupDescriptions.Add(new PropertyGroupDescription("UNIT"));
DataCNAPoorEating = data;
});
Loading = false;
}
private ListCollectionView _DataCNABathing;
public ListCollectionView DataCNABathing
{
get { return _DataCNABathing; }
set { this.SetReferenceProperty("DataCNABathing", ref _DataCNABathing, value); }
}
private ListCollectionView _DataCNABowel;
public ListCollectionView DataCNABowel
{
get { return _DataCNABowel; }
set { this.SetReferenceProperty("DataCNABowel", ref _DataCNABowel, value); }
}
private ListCollectionView _DataCNAIntakeVSOutput;
public ListCollectionView DataCNAIntakeVSOutput
{
get { return _DataCNAIntakeVSOutput; }
set { this.SetReferenceProperty("DataCNAIntakeVSOutput", ref _DataCNAIntakeVSOutput, value); }
}
private ListCollectionView _DataCNAPoorEating;
public ListCollectionView DataCNAPoorEating
{
get { return _DataCNAPoorEating; }
set { this.SetReferenceProperty("DataCNAPoorEating", ref _DataCNAPoorEating, value); }
}
// here we will put the shift pulldown :
private String _Type;
private String Shift
{
get { return _Type; }
set { if (this.SetReferenceProperty("Shift", ref _Type, value)) { RefreshData(); } }
}
}
}
You have a private property called Shift, and a private field called Shift. Remove one of them.
private string Shift;
...
private String Shift
{
get { return _Type; }
set { if (this.SetReferenceProperty("Shift", ref _Type, value)) { RefreshData(); } }
}

Categories