I have a C# class that takes job printers and some of its properties including TimeSubmitted, that is stored as DateTime with this format: 20130608204517.699000-300
I defined an object with this properties:
public class PrinterJob
{
public String Document { get; set; }
public string JobName { get; set; }
public UInt32 JobId { get; set; }
public string JobStatus { get; set; }
//===========================================================================
// This property doesn't cast adecuate
//===========================================================================
public Datetime TimeSubmitted { get; set; }
}
When I'll try to cast the DateTime (at Run Time):
foreach (ManagementObject prntJob in prntJobCollection)
{
System.String jobName = prntJob.Properties["Name"].Value.ToString();
//Job name would be of the format [Printer name], [Job ID]
char[] splitArr = new char[1];
splitArr[0] = Convert.ToChar(",");
string prnterName = jobName.Split(splitArr)[0];
if (String.Compare(prnterName, printerName, true) == 0)
{
PrinterJob prtobj = new PrinterJob();
prtobj.Document = prntJob.Properties["Document"].Value.ToString();
prtobj.JobName = prntJob.Properties["Name"].Value.ToString();
var id = prntJob.Properties["JobId"].Value;
prtobj.JobId = (UInt32)prntJob.Properties["JobId"].Value;
prtobj.JobStatus = prntJob.Properties["JobStatus"].Value.ToString();
//============================================================================
// Here The cast doesn't work. It comes as: 20130608204517.699000-300
// It throws an InvalidCastException
//============================================================================
prtobj.TimeSubmitted = (DateTime)prntJob.Properties["TimeSubmitted"].Value;
jobList.Add(prtobj);
}
}
What is the right way to cast this value to convert it to DateTime?
add reference to System.Management
var datetime = ManagementDateTimeConverter.ToDateTime("20130608204517.699000-300");
ManagementDateTimeConverter.ToDateTime
Isnt that a simple datetime? (ie. yyyyMMddHHmmss)
I wouldnt know what the part after the dot means though.
Related
So I have generated a SQLite database in Xamarin Forms. Each item has a Name and Date. I'm trying to extract the date and set it to a variable so that when each item is loaded, it will convert its date integer to DateTime and compare it to DateTime.Now.
I'm not sure how to do this, and I might be missing something very elementary- I'm a complete beginner.
public LivePage()
{
InitializeComponent();
LiveService.AddLive("2022年3月19日(土): ILLUSION FORCE presents「ILLUSION FORCE×GAUNTLET LONGSTAGE 'GACHINKO'2MAN GIG」", 20220319);
LiveService.AddLive("2022年3月20日(日)Phantom Excaliver presents 聖剣フェス」", 202203020);
LiveService.AddLive("2022年4月2日(土)Bad Company vol.17」", 20220402);
LiveService.AddLive("2022年4月10日(日)VELL'z FIRE presents", 20220410);
LiveService.AddLive("2022年4月10日(日)ILLUSION FORCE presents「ILLUSION FORCE×Amiliyah LONG STAGE 2MAN GIG」", 20220410);
LiveService.AddLive("2022年4月29日(金・祝)渋谷メタル会 presents 渋谷メタル会フェス 2022」", 20220429);
var Lists = LiveService.db.Table<Live>().ToList();
MainListView.ItemsSource = Lists;
int dateInt = Lists[2];
DateTime dater = Convert.ToDateTime(dateInt);
int result = DateTime.Compare(dater, DateTime.Now);
if (result < 0)
{
Label.TextDecorations = TextDecorations.Strikethrough;
}
How I created the Table
namespace IF2.Models
{
public class Live
{
public string Name { get; set; }
public string Date { get; set; }
public string Place { get; set; }
public string Time { get; set; }
}
}
Service File
public static SQLiteConnection db;
static void Init()
{
if (db != null)
return;
// Get an absolute path to the database file
var databasePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Lives.db3");
db = new SQLiteConnection(databasePath);
db.DropTable<Live>();
db.CreateTable<Live>();
}
public static void AddLive(string name, string date)
{
Init();
var live = new Live
{
Name = name,
Date = date,
};
var id = db.Insert(live);
}
public static void GetProperties()
{
Init();
var Lists = db.Table<Live>().ToList();
}
}
}
In your code public static void AddLive(string name, string date), you set the type of the date as string.
At first, try to get the data list, because there isn't only one line data in the table.
var stringlist = new List<string>()
// var intlist = new List<int>()
foreach(item in Lists)
{
var live = item as Live()
list.Add(live.Date)
//intlist.Add(int.Parse(live.Date))
}
Get the date time now:
string nowTime = DateTime.Now.ToString("yyyyMMdd", DateTimeFormatInfo.InvariantInfo);
// and the value of the string will be like "20220322"
And then you can compare them with the "==" such as:
var value = (nowTime == stringlist[i])
You can also compare them in the foreach(item in Lists) and needn't to get the list of the date.
Create a model class as a table. You need to give it a primary key and the attribute named table.
[Table("Live")]
public class Live
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
public string Date { get; set; }
public string Place { get; set; }
public string Time { get; set; }
}
Sorry I had to delete my previous comments. I was mistaken about SQLite being able to cast the date data as a DateTime object. Therefore, I can throw out a simple parser that will convert the string value of the date data.
If the data is bad then today’s date is returned, however you could return any date. You could use it like…
DateTime dater = GetDTFromString(dateInt.ToString());
The parser...
private DateTime GetDTFromString(string dateString) {
if (dateString.Length >= 8) {
string year = dateString.Substring(0, 4);
string month = dateString.Substring(4, 2);
string day = dateString.Substring(6, 2);
if (DateTime.TryParse(year + "," + month + "," + day, out DateTime targetDate)) {
return targetDate;
}
}
return DateTime.Now;
}
I am using lambda expression to access values with data type, but the problem I have data type for Time as Time(7) on my local database and using Entity Framework. On my model this data type is define as DateTime.
How do I now access this data type to be time?
This is my code:
public List GetIncident_Details()
{
Entities incident = new Entities();
List result = new List();
var c_incident = incident.Incident_Template.Select(c => c).ToList();
if (c_incident != null && c_incident.Count() > 0)
{
foreach (var cData in c_incident)
{
Incident_DropDown model = new Incident_DropDown();
model.Title = cData.Title;
model.Description = cData.Description;
model.Date_Occurred = cData.Date_Occurred;
// How do I change this to have access?
// It's complaining about the data type object being set to a string?
model.Time = cData.Time;
model.Assignment_Group = cData.Assignment_Group;
model.Reported_CI = cData.Reported_CI;
result.Add(model);
}
}
return result;
}
public class Incident_DropDown
{
public string Title { get; set; }
public string Description { get; set; }
public string Date_Occurred { get; set; }
public DateTime Time { get; set; } // Time
public string Assignment_Group { get; set; }
public string Reported_CI { get; set; }
}
Took some advice from #alexey-rumyantsev, then had to test my code by interrogating model data type for Time it was Date Time, then change to Timespan. While testing this data type compare to my local database record and it was passing correct vales when debugging.
// Model name
public class Incident_DropDown
{
public string Title { get; set; }
public string Description { get; set; }
public string Date_Occured { get; set; }
public TimeSpan Time { get; set; } // had to change to work
public string Assignment_Group { get; set; }
public string Reported_CI { get; set; }
}
// Controller
public List<Incident_DropDown> GetIncident_Details()
{
Entities incident = new Entities();
List<Incident_DropDown> result = new List<Incident_DropDown>();
var c_incident = incident.Incident_Template.Select(c => c).ToList();
if (c_incident != null && c_incident.Count() > 0)
{
foreach (var cData in c_incident)
{
Incident_DropDown model = new Incident_DropDown();
model.Title = cData.Title;
model.Description = cData.Description;
model.Date_Occured = cData.Date_Occured;
model.Time = cData.Time; // This here enable to pass correct time as per database record
model.Assignment_Group = cData.Assignment_Group;
model.Reported_CI = cData.Reported_CI;
result.Add(model);
}
}
return result;
}
I have a class I want to populate from a Linq query, but I am using a sub select statement to slightly alter the properties of the list. I have a class it should fit into but it refuses to go in. I am wondering if there is a way I can get these results to fit into the list as I defined it rather than a generic anonymous type.
public class SCADA_DATA_Truncated
{
public string acode { get; set; }
public string LOCCODE { get; set; }
public Nullable<System.DateTime> COLDATE { get; set; }
public string RESULT { get; set; }
public string analyte { get; set; }
}
And here is where I am attempting to populate the data:
List<SCADA_DATA_Truncated> dataResults = (SCADA_DATA_Truncated)(from b in a2Entity.SCADA_DATA
where DbFunctions.TruncateTime(b.COLDATE) >= dateCheck1 && DbFunctions.TruncateTime(b.COLDATE) <= dateCheck2
&& whereInAcode.Contains(b.acode) && whereInLoc.Contains(b.LOCCODE)
select new
{
COLDATE = DbFunctions.TruncateTime(b.COLDATE),
acode = b.acode,
LOCCODE = b.LOCCODE,
RESULT = b.RESULT,
analyte = b.analyte
}
).ToList();
This is an anonymous type:
select new
{
COLDATE = DbFunctions.TruncateTime(b.COLDATE),
acode = b.acode,
LOCCODE = b.LOCCODE,
RESULT = b.RESULT,
analyte = b.analyte
}
The runtime has no idea how to convert it to your class
Why not changing it to
select new SCADA_DATA_Truncated
{
COLDATE = DbFunctions.TruncateTime(b.COLDATE),
acode = b.acode,
LOCCODE = b.LOCCODE,
RESULT = b.RESULT,
analyte = b.analyte
}
You can then remove the explicit cast altogether
i have a list that I am trying to sort by datetime and return it. but I get a error.How do I fix this?
Cannot implicitly convert type
System.Linq.IOrderedEnumerable<ConsoleApplication2.DTNBars> to
System.Collections.Generic.List<ConsoleApplication2.DTNBars>. An
explicit conversion exists (are you missing a cast?)
public static List<DTNBars> getDTNBars(string symbol, DateTime dt)
{
TextReader tr = new StreamReader(File.Open(#"C:\historicaldata\" + symbol + ".txt", FileMode.Open));
List<DTNBars> dtnbars = new List<DTNBars>();
CsvReader csvr = new CsvReader(tr);
while (csvr.Read())
{
DTNBars b = new DTNBars();
b.Date_Time = csvr.GetField<DateTime>(0);
b.Open = csvr.GetField<double>(1);
b.High = csvr.GetField<double>(2);
b.Close = csvr.GetField<double>(4);
b.Ticker = symbol;
dtnbars.Add(b);
}
return dtnbars.OrderBy(x => x.Date_Time);
}
public class DTNBars
{
public DateTime Date_Time { get; set; }
public double Open { get; set; }
public double High { get; set; }
public double Low { get; set; }
public double Close { get; set; }
public string Ticker { get; set; }
}
Use ToList()
return dtnbars.OrderBy(x => x.Date_Time).ToList();
Your method states a return type of List<DTNBars> but you are returning IOrderedEnumerable<DTNBars> - which is the result of the OrderBy. Add ToList():
return dtnbars.OrderBy(x => x.Date_Time).ToList();
Or better just change return type to an IEnumerable<DTNBars>
Also you can refactor your initializing of the new DTNBars and use the object initializer:
dtnbars.Add( new DTNBars {
Date_Time = csvr.GetField<DateTime>(0),
Open = csvr.GetField<double>(1),
High = csvr.GetField<double>(2),
Close = csvr.GetField<double>(4),
Ticker = symbol });
I created a simple RESTful application in WCF(c#). When I'm populating using (GET) I've received this error
"Object reference not set to an instance of an object".
I received the error in the part of target.DocumentLines[0].itemCode = "";.
Here's my code:
public PRRequestData[] getAllPR()
{
List<PRRequestData> list = new List<PRRequestData>();
try
{
string sqlSelect = "SELECT DocEntry, Comments, ReqDate FROM OPRQ";
APP.strCommand = sqlSelect;
DataTable dt = new DataTable();
dt = APP.Ds.Tables[0];
foreach (DataRow row in dt.Rows)
{
// Person target = Activator.CreateInstance();
PRRequestData target = new PRRequestData();
target.requiredDate = row["ReqDate"].ToString();
target.remarks = row["Comments"].ToString();
target.docEntry = row["DocEntry"].ToString();
// DataColumnAttribute.Bind(row,target);
sqlSelect = "SELECT ItemCode, Quantity, Price, VendorNum, TaxCode FROM PRQ1 WHERE DocEntry = '" + row["DocEntry"].ToString() + "' ";
APP.strCommand = sqlSelect;
for (var i = 0; i < APP.Ds.Tables[0].Rows.Count; i++)
{
target.DocumentLines[0].itemCode = "";
}
list.Add(target);
}
return list.ToArray();
}
catch (Exception e)
{
e.ToString();
}
return list.ToArray();
Here's my DataContract source code also:
[DataContract(Namespace = "")]
public class PRRequestData
{
[DataMember]
public string docEntry { get; set; }
[DataMember]
public string remarks { get; set; }
[DataMember]
public string requiredDate { get; set; }
//[DataMember]
//public int rowcount { get; set; }
[DataMember]
public RequestDataDetails[] DocumentLines;
}
[DataContract]
public class RequestDataDetails
{
[DataMember]
public string itemCode { get; set; }
[DataMember]
public decimal quantity { get; set; }
[DataMember]
public decimal price { get; set; }
[DataMember]
public string supplier { get; set; }
[DataMember]
public string taxcode { get; set; }
}
Looks like you're not initialising this property
[DataMember]
public RequestDataDetails[] DocumentLines;
I recommend you to use List instead of RequestDataDetails[], as anyway you'll have to use an internal list.
Initialise the List of RequestDataDetails to fill it from the query, before the for loop.
List<RequestDataDetails> requestDetails = new List<RequestDataDetails>
Then change the for loop to add to that list instead of setting an array, im using the assignment you were doing, not sure if it'll do what you expect, just tell me if it suits your needs.
requestDetails.add(new RequestDataDetails { itemCode = "" });
instead of
target.DocumentLines[0].itemCode = "";
Then after the for loop convert the list to an array and assign it to target
target.DocumentLines = requestDetails.ToArray();
Hope it works!