Values from textbox is not being passed to SQL using MVC - c#

Form code:
public partial class Customer_Information : Form
{
private Controller controller;
Customer_Information info;
public Customer_Information()
{
InitializeComponent();
controller = new Controller();
}
private void Customer_Information_Load(object sender, EventArgs e)
{
// btnnext.Enabled = false;
info = new Customer_Information();
}
private void btnsave_Click(object sender, EventArgs e)
{
View view = controller.CreateProduct(info);
controller.InsertProduct(view);
}
View.cs:
class View
{
public string BILL_TO { get; set; }
public string SHIP_TO { get; set; }
public string VENDOR { get; set; }
public string BUYER { get; set; }
public string TERMS { get; set; }
public string CONTACTS { get; set; }
public string CURRENCY { get; set; }
public string PONUM { get; set; }
public string ENTRYDATE { get; set; }
public string SHIPDATE { get; set; }
public string CANCELDATE { get; set; }
public string ORDERTYPE { get; set; }
public View(string billto, string shipto, string vendor, string buyer, string terms, string contacts, string currency, string ponum, string entryd, string shipd, string canceld, string ordert)
{
BILL_TO = billto;
SHIP_TO = shipto;
VENDOR = vendor;
BUYER = buyer;
TERMS = terms;
CONTACTS = contacts;
CURRENCY = currency;
PONUM = ponum;
ENTRYDATE = entryd;
SHIPDATE = shipd;
CANCELDATE = canceld;
ORDERTYPE = ordert;
}
Controller.cs:
class Controller
{
private Model model;
public Controller()
{
model = new Model();
}
public View CreateProduct(Customer_Information info)
{
string billto = info.txtbillto.Text;
string shipto = info.txtshipto.Text;
string vendor = info.txtvendor.Text;
string buyer = info.txtbuyer.Text;
string terms = info.txtterms.Text;
string contacts = info.txtcontact.Text;
string currency = info.cmbcurrrecncy.Text;
string ponum = info.txtponum.Text;
string entryd = info.txtentrydate.Text;
string shipd = info.txtshipdate.Text;
string canceld = info.txtcanceldate.Text;
string ordert = info.txtorder.Text;
View view = new View(billto, shipto, vendor, buyer, terms, contacts, currency, ponum, entryd, shipd, canceld, ordert);
return view;
}
public void InsertProduct(View view)
{
model.InsertProduct(view);
}
Model.cs:
class Model{
SqlConnection connect;
SqlDataAdapter data = new SqlDataAdapter();
public Model()
{
connect = new SqlConnection("connection");
}
public void InsertProduct(View view)
{
string billto = view.BILL_TO;
string shipto = view.SHIP_TO;
string vendor = view.VENDOR;
string buyer = view.BUYER;
string terms = view.TERMS;
string contacts = view.CONTACTS;
string currency = view.CURRENCY;
string ponum = view.PONUM;
string entryd = view.ENTRYDATE;
string shipd = view.SHIPDATE;
string canceld = view.CANCELDATE;
string ordert = view.ORDERTYPE;
data.InsertCommand = new SqlCommand("INSERT INTO PURCHASE VALUES(#Bill_to, #Ship_to, #Vendor, #Buyer, #Terms, #Contact, #Currency, #PO_number, #Entry_date, #Ship_date, #Cancel_Date, #Order_type)", connect);
data.InsertCommand.Parameters.Add("#Bill_to", SqlDbType.VarChar).Value = billto;
data.InsertCommand.Parameters.Add("#Ship_to", SqlDbType.VarChar).Value = shipto;
data.InsertCommand.Parameters.Add("#Vendor", SqlDbType.VarChar).Value = vendor;
data.InsertCommand.Parameters.Add("#Buyer", SqlDbType.VarChar).Value = buyer;
data.InsertCommand.Parameters.Add("#Terms", SqlDbType.VarChar).Value = terms;
data.InsertCommand.Parameters.Add("#Contact", SqlDbType.VarChar).Value = contacts;
data.InsertCommand.Parameters.Add("#Currency", SqlDbType.VarChar).Value = currency;
data.InsertCommand.Parameters.Add("#PO_number", SqlDbType.VarChar).Value = ponum;
data.InsertCommand.Parameters.Add("#Entry_date", SqlDbType.VarChar).Value = entryd;
data.InsertCommand.Parameters.Add("#Ship_date", SqlDbType.VarChar).Value = shipd;
data.InsertCommand.Parameters.Add("#Cancel_Date", SqlDbType.VarChar).Value = canceld;
data.InsertCommand.Parameters.Add("#Order_type", SqlDbType.VarChar).Value = ordert;
connect.Open();
data.InsertCommand.ExecuteNonQuery();
connect.Close();
}
The program completes, but upon checking the database, the values passed are empty.

You can use
TableName object=new Tablename();
object.field1=value;
object.field2=value;
db.TableName.AddObject(object);

Related

how to call class object to perform search in textbox?

I have text boxes to search for data, and 6 text boxes to display data if the data I am looking for is found. I'm trying to use an object class to make the code in the form look a little neat. the class is named ClsSearch. This is the class code snippet:
public string Name { get; set; }
public string txtCode { get; set; }
public string txtBarcode { get; set; }
public string txtUnit { get; set; }
public string txtQty { get; set; }
public string txtCost_price { get; set; }
public string txtSales_price { get; set; }
string mainconn = ConfigurationManager.ConnectionStrings["DbLearn"].ConnectionString;
public void X001_TextChanged()
{
MySqlConnection mysqlconn = new MySqlConnection(mainconn);
string sqlquery = "SELECT * FROM tb_stock_product WHERE Item_Name='" + Name + "'";
MySqlCommand sqlcmd = new MySqlCommand(sqlquery, mysqlconn);
mysqlconn.Open();
MySqlDataReader sdr;
sdr = sqlcmd.ExecuteReader();
if (sdr.Read())
{
txtCode = sdr.GetString("Code");
txtBarcode = sdr.GetString("Barcode");
txtUnit = sdr.GetString("Unit");
txtQty = sdr.GetDouble("Qty").ToString();
txtCost_price = sdr.GetInt32("Cost_price").ToString();
txtSales_price = sdr.GetInt32("Sales_price").ToString();
}
mysqlconn.Close();
then I tried calling the class in the form, exactly when the button was pressed, and this is the code:
private void X_001_Click(object sender, EventArgs e)
{
Connection_Frm_Ordering load = new Connection_Frm_Ordering();
load.X001_TextChanged();
load.Name = X_001.Text;
load.txtCode = X_002.Text;
load.txtBarcode = X_003.Text;
load.txtUnit = X_004.Text;
load.txtQty = X_005.Text;
load.txtCost_price = X_006.Text;
load.txtSales_price = X_007.Text;
}
but the code i made is not working.. can anyone help me where is the error ? sorry if this code might be messy, I'm still learning :)

display more than one database query in .net MVC

I am creating my first project using asp.net MVC - I have successfully connected to the database and displayed the information on the index page. My question is how do I get more than one query result on the one index page
for e.g
SELECT student ID,first name,surname FROM STUDENT Notes WHERE student ID = 7
Do I need to create new controllers/models for each query or need to add to the current and if I add to the current how would I do it? Below is the code I currently have in my controller.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
//int sNumber = 1;
List<CustomerModel> customers = new List<CustomerModel>();
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "SELECT title, `first name`, surname FROM `STUDENT REGISTER`";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
customers.Add(new CustomerModel
{
// CustomerId = Convert.ToInt32(sdr["Student Number"]),
Title = sdr["title"].ToString(),
Name = sdr["first name"].ToString(),
Surname = sdr["surname"].ToString()
});
}
}
con.Close();
}
}
return View(customers);
}
Create a view model with two result set for e.g. Student and Marks
public class Result
{
public Student Student { get; set; }
public Marks Marks { get; set; }
}
Load/Construct this Result view model in controller /service with appropriate data and pass this view model to view.
I hope this helps!
You have to create a new class with all the properties you want to display in your View.
Example:
public class StudentModel {
public int Id { get; set; }
public string Title { get; set; }
public string Name { get; set; }
public strign Surname { get; set; }
}
public class MarkModel {
public int Id { get; set; }
public int StudentId { get; set; }
public int SubjectId { get; set; }
public int Mark { get; set; }
}
public class ResultModel
{
public StudentModel Student { get; set; }
public List<MarkModel> Marks { get; set; }
}
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
//int sNumber = 1;
var model= new ResultModel{
Student = new StudentModel(),
Marks = new List<MarkModel>();
}
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string queryStudent = "SELECT id, title, `first name`, surname FROM `STUDENT` WHERE Id=1";
using (MySqlCommand cmd = new MySqlCommand(queryStudent))
{
cmd.Connection = con;
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
model.student.Id = Convert.ToInt32(sdr["id"]),
model.student.Title = sdr["title"].ToString(),
model.student.Name = sdr["first name"].ToString(),
model.student.Surname = sdr["surname"].ToString()
}
}
}
string queryMarks = "SELECT Id, `StudentId`, StudentId,Mark FROM `MARK` WHERE StudentId=1";
using (MySqlCommand cmd = new MySqlCommand(queryMarks))
{
cmd.Connection = con;
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
model.Marks.Add(new MarkModel
{
Id = Convert.ToInt32(sdr["Id"]),
StudentId = Convert.ToInt32(sdr["StudentId"]),
StudentId = Convert.ToInt32(sdr["StudentId"]),
Mark = Convert.ToInt32(sdr["Mark"]),
});
}
}
}
}
return View(model);
}
You should create a new ViewModel class with all the properties you want to display in your View. Then you model your View after it.
From the properties you provided so far, the class should look like this:
public class StudentViewModel {
public int Id { get; set; }
public string Title { get; set; }
public string Name { get; set; }
public strign Surname { get; set; }
}
Then you do the value x property assignment
string query = "SELECT title, `first name`, surname FROM `STUDENT REGISTER`";
List<StudentViewModel> model = new List<StudentViewModel>();
using (MySqlCommand cmd = new MySqlCommand(query)) {
cmd.Connection = con;
con.Open();
using (MySqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
model.Add(new StudentViewModel
{
Id = Convert.ToInt32(sdr["StudentNumber"]),
Title = Convert.ToString(sdr["title"]),
Name = Convert.ToString(sdr["first name"]),
Surname = Convert.ToString(sdr["surname"])
});
}
}
con.Close();
}
return View(model);

How to convert a function into a class to be used from any page

I have the following function which is accessible from one of my asp.net page:
/* QUERY TO RUN FROM ANY FUNCTION */
public void runQuery()
{
strMainSql = #"SELECT
CT.OBJECTID 'Object ID'
FROM HSI.RMOBJECTINSTANCE1224 CT
WHERE CT.ACTIVESTATUS = 0 AND CT.OBJECTID = '" + s + "'";
using (SqlConnection scConn = new SqlConnection(strConn))
{
scConn.Open();
using (SqlCommand scComm = new SqlCommand(strMainSql, scConn))
{
sdrRead = scComm.ExecuteReader();
while (sdrRead.Read())
{
/* CAN BE USED IN OTHER PAGES */
strTaskName = sdrRead[1].ToString();
strTaskDetail = sdrRead[2].ToString();
strTaskStartDate = sdrRead[3].ToString();
strIdentifier = sdrRead[4].ToString();
strStatus = sdrRead[5].ToString();
strDueDate = sdrRead[6].ToString();
strIssueDate = sdrRead[7].ToString();
strCompleted = sdrRead[8].ToString();
strNotes = sdrRead[9].ToString();
strProvider = sdrRead[10].ToString();
strService = sdrRead[11].ToString();
strCheckedDate = sdrRead[12].ToString();
strCheckedStatus = sdrRead[13].ToString();
strCheckedUser = sdrRead[14].ToString();
strClient = sdrRead[15].ToString();
hfMemoID.Value = sdrRead[16].ToString();
hfObjectID.Value = sdrRead[0].ToString();
break;
}
}
}
/* SPECIFIC TO THE PAGE ONLY */
lblUser.Text = strCheckedUser;
lblDateTime.Text = strCheckedDate;
lblTaskName.Text = strTaskName;
lblClient.Text = strClient;
lblID.Text = strIdentifier;
lblSvc.Text = strService;
lblProvider.Text = strProvider;
lblStat.Text = strStatus;
lblDueDate.Text = strDueDate;
lblDetail.Text = strTaskDetail;
lblTaskIssue.Text = strIssueDate;
lblStartDate.Text = strTaskStartDate;
lblCompleted.Text = strCompleted;
}
The question I have is, if I have to use the above function in multiple pages, instead of having a multiple copies of the same function which might lead to issue later on when updating, how do I make it into a class by itself so I can call it from any page and get the value from the SQL query?
What you can do is expose the results from the query as properties and then use the properties in the ASPX page.
using System.Data.SqlClient;
namespace MyNamespace
{
public class Task
{
public string strTaskName { get; set; }
public string strTaskDetail { get; set; }
public string strTaskStartDate { get; set; }
public string strIdentifier { get; set; }
public string strStatus { get; set; }
public string strDueDate { get; set; }
public string strIssueDate { get; set; }
public string strCompleted { get; set; }
public string strNotes { get; set; }
public string strProvider { get; set; }
public string strService { get; set; }
public string strCheckedDate { get; set; }
public string strCheckedStatus { get; set; }
public string strCheckedUser { get; set; }
public string strClient { get; set; }
// you need to define properties for the appropriate datatype on these
//hfMemoID
//hfObjectID
public string strConn { get; set; }
public void Load(string objectid)
{
var strMainSql = #"SELECT
CT.OBJECTID 'Object ID'
FROM HSI.RMOBJECTINSTANCE1224 CT
WHERE CT.ACTIVESTATUS = 0 AND CT.OBJECTID = '" + objectid + "'";
using (SqlConnection scConn = new SqlConnection(strConn))
{
scConn.Open();
using (SqlCommand scComm = new SqlCommand(strMainSql, scConn))
{
var sdrRead = scComm.ExecuteReader();
while (sdrRead.Read())
{
/* CAN BE USED IN OTHER PAGES */
this.strTaskName = sdrRead[1].ToString();
this.strTaskDetail = sdrRead[2].ToString();
this.strTaskStartDate = sdrRead[3].ToString();
this.strIdentifier = sdrRead[4].ToString();
this.strStatus = sdrRead[5].ToString();
this.strDueDate = sdrRead[6].ToString();
this.strIssueDate = sdrRead[7].ToString();
this.strCompleted = sdrRead[8].ToString();
this.strNotes = sdrRead[9].ToString();
this.strProvider = sdrRead[10].ToString();
this.strService = sdrRead[11].ToString();
this.strCheckedDate = sdrRead[12].ToString();
this.strCheckedStatus = sdrRead[13].ToString();
this.strCheckedUser = sdrRead[14].ToString();
this.strClient = sdrRead[15].ToString();
//
//hfMemoID.Value = sdrRead[16].ToString();
//hfObjectID.Value = sdrRead[0].ToString();
break;
}
}
}
}
}
}
In the code behind use the class to load the data and then set the controls using the properties
private MyNamespace.Task Task = new MyNamespace.Task();
protected void Page_Load(object sender, EventArgs e)
{
Task.strConn = "my connection string.";
Task.Load("task id to load");
// set the value into the controls.
lblUser.Text = Task.strCheckedUser;
lblDateTime.Text = Task.strCheckedDate;
lblTaskName.Text = Task.strTaskName;
lblClient.Text = Task.strClient;
lblID.Text = Task.strIdentifier;
lblSvc.Text = Task.strService;
lblProvider.Text = Task.strProvider;
lblStat.Text = Task.strStatus;
lblDueDate.Text = Task.strDueDate;
lblDetail.Text = Task.strTaskDetail;
lblTaskIssue.Text = Task.strIssueDate;
lblStartDate.Text = Task.strTaskStartDate;
lblCompleted.Text = Task.strCompleted;
}

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.

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