Using switch to select enum value - c#

I am new to programming so i don't know what i am doing.
I am pulling enum value from different class and set them as getter and setter.
namespace DataLayer.Entities
{
public enum CourseModeOfDelivery
{
Online, ClassRoom, ELearning,
}
public class Course
{
public int ID { get; set; }
public String CourseName { get; set; }
public String Description { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public CourseModeOfDelivery CourseMode { get; set; }
}
reading this value in courseRepository
public static Course GetCourse(int id)
{
Course a = new Course();
String GetCommand = "Select CourseName, Description, StartDate, EndDate, CourseMode from Course" + "Where ID = #CourseID";
SqlConnection connection = DBManager.GetSqlConnection();
SqlCommand command = new SqlCommand(GetCommand, connection);
command.Parameters.AddWithValue("#StudentID", id);
try
{
var reader = command.ExecuteReader();
//Read the Command Object and then return details
if (reader.HasRows)
{
while (reader.Read())
{
a.ID = Convert.ToInt32(reader["ID"]);
a.CourseName = reader["CourseName"].ToString();
a.Description = reader["Description"].ToString();
a.StartDate = DateTime.Parse(reader["StartDate"].ToString());
a.EndDate = DateTime.Parse(reader["EndDate"].ToString());
var selection = CourseModeOfDelivery.ClassRoom;
switch (selection)
{
case CourseModeOfDelivery.ClassRoom:
a.CourseMode = CourseModeOfDelivery.ClassRoom;
return a.CourseMode;
case CourseModeOfDelivery.ELearning:
a.CourseMode = CourseModeOfDelivery.ELearning;
return a.CourseMode;
case CourseModeOfDelivery.Online:
a.CourseMode = CourseModeOfDelivery.Online;
return a.CourseMode;
}
a.CourseMode =
}
}
else
{
reader.Close();
}
}
The requirement is to use switch but don't know how to pull data in there.

It depends on the type of database field you use.
If it is int then:
a.CourseMode = (CourseModeOfDelivery) reader["CourseMode"];
If it is String then:
a.CourseMode = (CourseModeOfDelivery) Enum.Parse(typeof(CourseModeOfDelivery), reader["CourseMode"].toString());
The following might also help you:
https://msdn.microsoft.com/en-us/library/essfb559(v=vs.110).aspx
Cast int to enum in C#

Related

MySQL query data retrieve giving everything null despite data in database

so like my question said, I doing a mySQL query but the query is giving me some headache as I am trying to retrieve the data from my database as a object so I can reiterate in my javascript code however the data I retrieve out from the database is all null and 0 despite my database it self do not have value with null or 0. I have set my database value that it cannot be null.
So, this is the value in my database:
This is the data that I retrieved till.
{"Musicid":0,"Audioid":null,"Description":null,"MusicTitle":null,"AudioPath":null,"ImagePath":null,"PriceType":null,"UploadDate":"\/Date(-62135596800000)\/","Views":0,"Likes":0,"NoOfReports":0,"Type":null}
This is my C# class
public class music{
public int Musicid { get; set; }
public String Audioid { get; set; }
public String Description { get; set; }
public String MusicTitle { get; set; }
public String AudioPath { get; set; }
public String ImagePath { get; set; }
public String PriceType { get; set; }
public DateTime UploadDate { get; set; }
public int Views { get; set; }
public int Likes { get; set; }
public int NoOfReports { get; set; }
public String Type { get; set; }
public music(int musicid, String audioid, String description, String MusicTitle, String audioPath, String imagePath, String priceType, DateTime uploadDate, int views, int likes, int noOfreports, String Type)
{
musicid = this.Musicid;
audioid = this.Audioid;
description = this.Description;
MusicTitle = this.MusicTitle;
audioPath = this.AudioPath;
imagePath = this.ImagePath;
priceType = this.PriceType;
uploadDate = this.UploadDate;
views = this.Views;
likes = this.Likes;
noOfreports = this.NoOfReports;
Type = this.Type;
}
}
This is my c# code
public List<music> Searchdatabase(String searchvalue)
{
List<music> al = new List<music>();
ArrayList array = new ArrayList();
//sql connection, query values to database error need help
string cs = ConfigurationManager.ConnectionStrings["test"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(cs))
{
con.Open();
String query = "SELECT music.* FROM music WHERE MusicTitle LIKE #search";
MySqlCommand command = new MySqlCommand(query, con);
command.Parameters.AddWithValue("#search", "%" + searchvalue + "%");
using (MySqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
if (searchvalue == null || searchvalue == "")
{
break;
}
else
{
al.Add(new music(reader.GetInt32(0), reader.GetString(1), reader.GetString(2), reader.GetString(3), reader.GetString(4), reader.GetString(5), reader.GetString(6), reader.GetDateTime(7), reader.GetInt32(8), reader.GetInt32(9) , reader.GetInt32(10), reader.GetString(11)));
}
}
if (reader != null)
reader.Close();
}
}
return al;
}
The command seems to be working just like whatever I key to the searchbox value which is for searchvalue like anything that not related to the musicTitle in the database will provided me with nothing which is correct. But anything that have relation to the musicTitle it return me the object array just that the value retrieved is null and 0 despite having data in database.
I know this may be lengthy, hopefully someone can help me. Thanks
Your constructor code is wrong. You're assigning values to constructor parameters rather than the other way around.
public music(int musicid, String audioid, String description, String MusicTitle, String audioPath, String imagePath, String priceType, DateTime uploadDate, int views, int likes, int noOfreports, String Type)
{
this.Musicid = musicid;
....
this.NoOfReports = noOfreports;
this.Type = Type;
}
Also, look into object initializers instead, so you don't write these ridiculous constructors.
new music { Musicid = musicid, Type, NoOfReports = noOfreports .... };
In this case you don't even need a constructor. As you can see, if the variable name is the same as the property name, you don't have to write this as X = Y, but just X. So it's like a constructor, but you don't have to write the actual constructor.
Your constructor has everything in reverse order. You are setting the arguments instead of the properties. Change it to this and try again.
public music(int musicid, String audioid, String description, String MusicTitle, String audioPath, String imagePath, String priceType, DateTime uploadDate, int views, int likes, int noOfreports, String Type)
{
this.Musicid =musicid;
this.Audioid = audioid;
this.Description = description;
this.MusicTitle = MusicTitle;
this.AudioPath = audioPath;
this.ImagePath = imagePath;
this.PriceType = priceType;
this.UploadDate = uploadDate;
this.Views = views;
this.Likes = likes;
this.NoOfReports = noOfreports;
this.Type = Type;
}

How do I extend a model class to another model?

I am trying to extend a class to another class that will collect them as a list.
model:
public class Brand
{
public int BrandId { get; set; }
public string Name { get; set; }
public string Guid { get; set; }
public float Rating { get; set; }
public string Industry { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Postal { get; set; }
public string CountryCode { get; set; }
public virtual Snapshot Snapshot { get; set; }
}
public class Snapshot
{
public int ID { get; set; }
public string Guid { get; set; }
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public string Email { get; set; }
public DateTime DateTimeSent { get; set; }
public string Subject { get; set; }
public string Html { get; set; }
public string Image { get; set; }
public string Unsubscribe { get; set; }
}
public class BrandSnaphotViewModel
{
public Brand Brand { get; set; }
public List<Snapshot> SnapshotItems { get; set; }
}
controller:
public ActionResult Index(string brandGuid)
{
BrandSnaphotViewModel viewModel = new BrandSnaphotViewModel();
Brand brand = GetBrand(brandGuid);
viewModel.Brand = brand;
List<Snapshot> snapshot = GetBrandSnapshots(brand.BrandId);
viewModel.SnapshotItems = snapshot;
List<BrandSnaphotViewModel> viewModelList = new List<BrandSnaphotViewModel>();
viewModelList.Add(viewModel);
return View(viewModelList.AsEnumerable());
}
private Brand GetBrand(string brandGuid)
{
Brand brand = new Brand();
string dbConnString = WebConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
MySqlConnection dbConn = new MySqlConnection(dbConnString);
dbConn.Open();
MySqlCommand dbCmd = new MySqlCommand();
dbCmd.CommandText = "SELECT *, industries.name AS industry_name FROM brands LEFT JOIN industries ON brands.industry_id = industries.industry_id WHERE brand_guid = '" + brandGuid.ToString() + "' AND private = 0 LIMIT 1";
dbCmd.Connection = dbConn;
MySqlDataReader dbResult = dbCmd.ExecuteReader();
if (dbResult.Read())
{
brand.Guid = dbResult["brand_guid"].ToString();
brand.BrandId = Convert.ToInt32(dbResult["brand_id"]);
brand.Industry = dbResult["industry_name"].ToString();
}
dbResult.Close();
dbConn.Close();
return brand;
}
private List<Snapshot> GetBrandSnapshots(int brandId)
{
string dbConnString = WebConfigurationManager.ConnectionStrings["dbConn"].ConnectionString;
MySqlConnection dbConn = new MySqlConnection(dbConnString);
dbConn.Open();
MySqlCommand dbCmd = new MySqlCommand();
dbCmd.CommandText = "SELECT * FROM snapshots WHERE brand_id = " + brandId + " AND archive = 0 ORDER BY date_sent DESC";
dbCmd.Connection = dbConn;
MySqlDataReader dbResult = dbCmd.ExecuteReader();
List<Snapshot> snapshots = new List<Snapshot>();
while (dbResult.Read())
{
snapshots.Add(new Snapshot
{
SnapshotId = Convert.ToInt32(dbResult["snapshot_id"]),
Subject = dbResult["subject"].ToString(),
DateTimeSent = Convert.ToDateTime(dbResult["date_sent"]),
Image = dbResult["image"].ToString(),
Email = dbResult["email"].ToString(),
ContentType = dbResult["content_type"].ToString(),
Type = dbResult["type"].ToString()
});
}
dbResult.Close();
dbConn.Close();
return snapshots;
}
edit
FIXED
The issue was the VIEW was not referencing the ViewModel as an IENumerable<>. FACEPALM.
#model IEnumerable<projectvia.ViewModels.BrandSnaphotViewModel>
#{
ViewBag.Title = "Index";
}
#foreach(var item in Model)
{
#item.Brand.Guid;
for(int i = 0; i< #item.SnapshotItems.Count; i++)
{
#item.SnapshotItems[i].Subject<br/>
}
}
That resolved the issue.
Thank you both experts for the insights... i took both advice and came to this solution.
you are doing wrong, it is a list.
you cannot add element this way. Create object and add that object in list by calling Add()
do like this to add items in it:
List<BrandEmailList> brandSnapshotsList = new List<BrandEmailList>();
while (dbResult.Read())
{
BrandEmailList brandSnapshots = new BrandEmailList (); // create an object
brandSnapshots.ID = Convert.ToInt32(dbResult["snapshot_id"]);
brandSnapshots.Guid = dbResult["snapshot_guid"].ToString();
brandSnapshots.DateTimeSent = dbResult["date_sent"];
brandSnapshots.Subject = dbResult["subject"].ToString();
brandSnapshots.Image = dbResult["image"];
brandSnapshotsList.Add(brandSnapshots); // add it in list
}
EDIT:
List is a generic thing, you don't need to create a class for it. you can just instantiate a list and add items in it.
why are you doing like that you can do it this way simply:
List<Snapshot> brandSnapshotsList = new List<Snapshot>();
while (dbResult.Read())
{
Snapshot brandSnapshots = new Snapshot(); // create an object
brandSnapshots.ID = Convert.ToInt32(dbResult["snapshot_id"]);
brandSnapshots.Guid = dbResult["snapshot_guid"].ToString();
brandSnapshots.DateTimeSent = dbResult["date_sent"];
brandSnapshots.Subject = dbResult["subject"].ToString();
brandSnapshots.Image = dbResult["image"];
brandSnapshotsList.Add(brandSnapshots); // add it in list
}
Building on what Ehsan Sajjad did, looking at public IEnumerator<Snapshot> BrandEmails, i believe what you look for looks more like this:
public class Snapshot
{
public int ID { get; set; }
public string Guid { get; set; }
// ...
}
public class BrandEmailList : List<Snapshot>
{
}
You need not even create a new type for your brand email list, you can use List<Snapshot> directly.
public ViewResult Whatever() {
var brand = GetBrand(brandName);
var brandSnapshots = GetBrandSnapshots();
return View(brand, brandSnapshots);
}
private Brand GetBrand(string brandName)
{
try
{
var brand = new Brand();
brand.Name = brandName;
// database stuffs ...
return brand;
}
catch (Exception ex)
{
throw ex;
}
}
private List<Snapshot> GetBrandSnapshots()
{
// ...
// DB stuffs -- that *really* should not be in the controller anyways.
// ...
var snapshots = new List<BrandEmailList>();
while (dbResult.Read())
{
// object initializer syntax
snapshots.Add(new Snapshot {
ID = Convert.ToInt32(dbResult["snapshot_id"]),
Guid = dbResult["snapshot_guid"].ToString(),
DateTimeSent = dbResult["date_sent"],
Subject = dbResult["subject"].ToString(),
Image = dbResult["image"],
});
}
return snapshots
}
As a side note, mixing database access into controller methods can be a bad idea. It does not have to be, but it can be. Generally, fetching data from the database happens at a different "level" than serving a MVC result. MVC controller don't have the "purpose" to talk to a database, that work can/should be delegated to a dedicated type. Compare the single responsibility principle part of the SOLID principles.

How to correct DoNotExposeGenericLists error C#

I have the following method in DAL which accepts the model OrderList and returns a List<OrderList>
public List<OrderList> GetOrderList(OrderList orderList)
{
...
return new List<OrderList>();
}
When I analyze using FXCop, it's saying DoNotExposeGenericLists Error
FXCop is saying this as resolution
"Change 'List<OrderList>' in 'OrderRelatedDataAccess.GetOrderList(OrderList)' to use
Collection<T>, ReadOnlyCollection<T> or KeyedCollection<K,V>"
How can I correct this?
My OrderList model is shown below
public int serialNumber { get; set; }
public int orderID { get; set; }
public int orderListID { get; set; }
public int productID { get; set; }
public int quantity { get; set; }
public long price { get; set; }
public string productName { get; set; }
Thanks.
Edit:
Code inside the method
List<OrderList> listOfOrderList = new List<OrderList>();
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand("sGetOrderListByOrderID", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#orderID", orderList.orderID);
connection.Open();
reader = command.ExecuteReader();
int sno = 0;
while (reader.Read())
{
long price = long.Parse(reader[4].ToString());
listOfOrderList.Add(new OrderList()
{
serialNumber = ++sno,
orderID = (int)reader[0],
productID = (int)reader[2],
quantity = (int)reader[3],
price = price,
productName = reader[5].ToString(),
});
}
connection.Close();
}
return listOfOrderList;
In your case its best to change the method signature to use an IList instead of List
public IList<OrderList> GetOrderList(OrderList orderList)
{
//get your data and build your list here
return new List<OrderList>();
}
See the differences between ICollection and IList in this answer
The answer is right there in the FxCop message. Just change the return type to be ICollection<OrderList>, like so:
public ICollection<OrderList> GetOrderList(OrderList orderList)
{
...
return new List<OrderList>();
}

How to Deserialize datareader or data table to c# class

i have populated data reader from db table and i have class like
public class CandidateApplication
{
public string EmailID { get; set; }
public string Name { get; set; }
public string PhoneNo { get; set; }
public string CurrentLocation { get; set; }
public string PreferredWorkLocation { get; set; }
public int RoleApplingFor { get; set; }
public string CurrentJobTitle { get; set; }
public int EducationLevel { get; set; }
public decimal SalaryExpected { get; set; }
public string AvailableTime { get; set; }
public int AdvertID { get; set; }
public bool SignForAlert { get; set; }
public string CVInText { get; set; }
public string CVFileName { get; set; }
public bool IsDownloaded { get; set; }
public string specialization { get; set; }
public bool isallocated { get; set; }
public int id { get; set; }
public string AdvertAdditionalInfo { get; set; }
}
i can populate the above class in loop. we can iterate in data reader and populate class but i want to know is there any short cut way to populate class from data reader.
if data deserialization is possible from data reader to class then also tell me if few fields are there in class which are not there in data reader then how to handle the situation.
You don't need to use a Data Reader, You could just Populate the Data into a DataTable, and use the below method to create a List of your CandidateApplication Class.
The Call :-
List<CandidateApplication> CandidateList = GetCandidateInformation();
The Method that generates the list :-
public List<CandidateApplication> GetCandidateInformation()
{
DataTable dt = new DataTable();
using (OleDbConnection con = new OleDbConnection(ConfigurationManager.AppSettings["con"]))
{
using (OleDbCommand cmd = new OleDbCommand("SELECT * FROM [TableName]", con))
{
var adapter = new OleDbDataAdapter();
adapter.SelectCommand = cmd;
con.Open();
adapter.Fill(dt);
var CandApp = (from row in dt.AsEnumerable()
select new CandidateApplication
{
EmailID = row.Field<string>("EmailID"),
Name = row.Field<string>("Name"),
PhoneNo = row.Field<string>("PhoneNo"),
CurrentLocation = row.Field<string>("CurrentLocation"),
PreferredWorkLocation = row.Field<string>("PreferredWorkLocation"),
RoleApplingFor = row.Field<int>("RoleApplingFor"),
CurrentJobTitle = row.Field<string>("CurrentJobTitle"),
EducationLevel = row.Field<int>("EducationLevel "),
SalaryExpected = row.Field<decimal>("SalaryExpected"),
AvailableTime = row.Field<string>("AvailableTime"),
AdvertID = row.Field<int>("AdvertID"),
SignForAlert = row.Field<bool>("SignForAlert"),
CVInText = row.Field<string>("CVInText"),
CVFileName = row.Field<string>("CVFileName"),
IsDownloaded = row.Field<bool>("IsDownloaded"),
Specialization = row.Field<string>("Specialization"),
Isallocated = row.Field<bool>("Isallocated"),
Id = row.Field<int>("Id"),
AdvertAdditionalInfo = row.Field<string>("AdvertAdditionalInfo")
}).ToList();
return CandApp;
}
}
}
Although not an answer to your question, I would suggest you to consider the following workaround, which uses a SqlDataAdapter instead of a data reader:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Xml.Serialization;
class Program
{
static void Main(string[] args)
{
var cs = "YourConnectionString";
var xml = "";
using (var con = new SqlConnection(cs))
using (var c = new SqlCommand("SELECT * FROM CandidateApplication", con))
{
con.Open();
using (var adapter = new SqlDataAdapter(c))
{
var ds = new DataSet("CandidateApplications");
ds.Tables.Add("CandidateApplication");
adapter.Fill(ds, ds.Tables[0].TableName);
xml = ds.GetXml();
}
}
// We need to specify the root element
var rootAttribute = new XmlRootAttribute();
// The class to use as the XML root element (should match the name of
// the DataTable in the DataSet above)
rootAttribute.ElementName = "CandidateApplications";
// Initializes a new instance of the XmlSerializer class that can
// serialize objects of the specified type into XML documents, and
// deserialize an XML document into object of the specified type.
// It also specifies the class to use as the XML root element.
// I chose List<CandidateApplication> as the type because I find it
// easier to work with (but CandidateApplication[] will also work)
var xs = new XmlSerializer(typeof(List<CandidateApplication>), rootAttribute);
// Deserialize the XML document contained by the specified TextReader,
// in our case, a StringReader instance constructed with xml as a parameter.
List<CandidateApplication> results = xs.Deserialize(new StringReader(xml));
}
}
For those properties that are missing in the retrieved data, you could declare a private field with a default value:
string _advertAdditionalInfo = "default";
public string AdvertAdditionalInfo
{
get
{
return _advertAdditionalInfo;
}
set
{
_advertAdditionalInfo = value;
}
}
If you would like to enforce that the retrieved data will not fill in a specific property, use:
[XmlIgnoreAttribute]
public string AdvertAdditionalInfo { get; set; }
I made a generic function for converting the SELECT result from an OleDbCommand to a list of classes.
Let's say that I have a class that looks like this, which maps to the columns in the database:
internal class EconEstate
{
[Column(Name = "basemasterdata_id")]
public Guid BaseMasterDataId { get; set; }
[Column(Name = "basemasterdata_realestate")]
public Guid? BaseMasterDataRealEstate { get; set; }
[Column(Name = "business_area")]
public string BusinessArea { get; set; }
[Column(Name = "profit_centre")]
public int ProfitCentre { get; set; }
[Column(Name = "rentable_area")]
public decimal RentableArea { get; set; }
}
Then I can get a list of those EconEstate objects using this code:
public void Main()
{
var connectionString = "my connection string";
var objects = ReadObjects<EconEstate>(connectionString, "EMBLA.EconEstates").ToList();
}
private static IEnumerable<T> ReadObjects<T>(string connectionString, string tableName) where T : new()
{
using (var connection = new OleDbConnection(connectionString))
{
connection.Open();
using (var command = new OleDbCommand($"SELECT * FROM {tableName};", connection))
{
var adapter = new OleDbDataAdapter
{
SelectCommand = command
};
var dataTable = new DataTable();
adapter.Fill(dataTable);
foreach (DataRow row in dataTable.Rows)
{
var obj = new T();
foreach (var propertyInfo in typeof(T).GetProperties())
{
var columnAttribute = propertyInfo.GetCustomAttributes().OfType<ColumnAttribute>().First();
var value = row[columnAttribute.Name];
var convertedValue = ConvertValue(value, propertyInfo.PropertyType);
propertyInfo.SetValue(obj, convertedValue);
}
yield return obj;
}
}
}
}
private static object ConvertValue(object value, Type targetType)
{
if (value == null || value.GetType() == typeof(DBNull))
{
return null;
}
if (value.GetType() == targetType)
{
return value;
}
var underlyingTargetType = Nullable.GetUnderlyingType(targetType) ?? targetType;
if (value is string stringValue)
{
if (underlyingTargetType == typeof(int))
{
return int.Parse(stringValue);
}
else if (underlyingTargetType == typeof(decimal))
{
return decimal.Parse(stringValue);
}
}
var valueType = value.GetType();
var constructor = underlyingTargetType.GetConstructor(new[] { valueType });
var instance = constructor.Invoke(new object[] { value });
return instance;
}
As you can see, the code is generic, making it easy to handle different tables and classes.

Incorrect JSON Date

I am having trouble with the representation of a date in JSON. I am using Service Stack as a web service to get the data from. My code on the server side is as follows:
public object Execute(GetNoPatientList request)
{
NoPatientList _noPatientList = new NoPatientList();
List<string> _noMatchPatientList = new List<string>();
List<NoPatientList> _newList = new List<NoPatientList>();
try
{
using (SqlConnection cn = new SqlConnection(Database.WaldenWebConnection))
{
cn.Open();
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandText = "select [DateTimeStamp] as DateCreated,[ID],[PatientMRN],[FirstName],[MiddleName]"
+ " ,[LastName],convert(varchar,[DOB],101) as DOB,[Sex],[Note],[Source] as Interface"
+ " from PatientNoMatch"
+ " where FoundMatch = 'F'"
+ " and Show = 'T'"
+ " order by DateTimeStamp desc";
SqlDataReader dr = cm.ExecuteReader();
while (dr.Read())
{
NoPatientList _noPatientList1 = new NoPatientList();
_noPatientList1.PatientMRN = dr["PatientMRN"].ToString();
_noPatientList1.FirstName = dr["FirstName"].ToString();
_noPatientList1.MiddleName = dr["MiddleName"].ToString();
_noPatientList1.LastName = dr["LastName"].ToString();
_noPatientList1.DOB = dr["DOB"].ToString();
_noPatientList1.Sex = dr["Sex"].ToString();
_noPatientList1.Note = dr["Note"].ToString();
_noPatientList1.DateCreated = dr.GetDateTime(0);
_noPatientList1.Interface = dr["Interface"].ToString();
_newList.Add(_noPatientList1);
}
return _newList;
}
}
}
catch
{
return _newList;
}
}
The type is represented as follows:
[DataContract]
public class NoPatientList
{
[DataMember]
public string ID { get; set; }
[DataMember]
public string PatientMRN { get; set; }
[DataMember]
public string FirstName { get; set; }
[DataMember]
public string MiddleName { get; set; }
[DataMember]
public string LastName { get; set; }
[DataMember]
public string Sex { get; set; }
[DataMember]
public string DOB { get; set; }
[DataMember]
public string Note { get; set; }
[DataMember]
public DateTime DateCreated { get; set; }
[DataMember]
public string Interface { get; set; }
}
The web service is being consumed by a Silverlight application from the following call:
/InterfaceUtility/servicestack/json/syncreply/
The Silverlight application is processing the code into a grid using the following code
private void GetNoPatientMatchData()
{
try
{
gridViewNoMatch.ItemsSource = null;
}
catch { }
_client = new WebClient();
_client.OpenReadCompleted += (a, f) =>
{
if (!f.Cancelled && f.Error == null)
{
_listOfNoPatientsMatches = new List<NoPatientList>();
MemoryStream _memoryStream = new MemoryStream();
f.Result.CopyTo(_memoryStream);
_memoryStream.Position = 0;
StreamReader _streamReader = new StreamReader(_memoryStream);
string _memoryStreamToText = _streamReader.ReadToEnd();
List<NoPatientList> _deserializedNoPatientList = (List<NoPatientList>)Newtonsoft.Json.JsonConvert.DeserializeObject(_memoryStreamToText, typeof(List<NoPatientList>));
gridViewNoMatch.ItemsSource = _deserializedNoPatientList;
}
else
{
MessageBox.Show(f.Error.Message,
"Error", MessageBoxButton.OK);
}
};
_client.OpenReadAsync(new Uri(_serviceUri + "getnopatientlist"));
The issue is that the times on DateTime field appear to always 6 hours off.
Any ideas as to what is going on?
This is probably a time zone issue. Check that:
Your webservice is returning you dates/times in UTC format.
Your code is parsing these dates/times as UTC dates and times.

Categories