public static Models.Json.Record ToRecord(this Models.Record record) { return(new Models.Json.Record { id = record.Id }); }
public HttpResponseMessage Post(Models.Record value) { try { if (ModelState.IsValid) { var p = new Person(); p.FirstName = value.FirstName; p.LastName = value.LastName; p.Gender = value.Gender; p.FavoriteColor = value.FavoriteColor; p.DateOfBirth = value.DateOfBirth; _recordsRepository.Insert(p); return(new HttpResponseMessage(HttpStatusCode.OK)); } else { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } } catch (Exception) { return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } }
public List <Models.Record> FindByStationID(string stationID) { var result = new List <Models.Record>(); var connection = new System.Data.SqlClient.SqlConnection(_connectionString); connection.Open(); var command = new System.Data.SqlClient.SqlCommand("", connection); command.CommandText = string.Format(@" Select * from Record Where StationID='{0}'", stationID ); var reader = command.ExecuteReader(); while (reader.Read()) { Models.Record item = new Models.Record(); item.ID = int.Parse(reader["ID"].ToString()); item.CreateTime = DateTime.Parse(reader["CreateTime"].ToString()); if (!string.IsNullOrEmpty(reader["WaterLevel"].ToString())) { item.WaterLevel = double.Parse(reader["WaterLevel"].ToString()); } if (!string.IsNullOrEmpty(reader["RecordTime"].ToString())) { item.RecordTime = DateTime.Parse(reader["RecordTime"].ToString()); } result.Add(item); } connection.Close(); return(result); }
public bool IsExist(Models.Record record) { var id = record.StationID; var datetime = record.RecordTime; var connection = new System.Data.SqlClient.SqlConnection(); connection.ConnectionString = _connectionString; var command = new System.Data.SqlClient.SqlCommand("", connection); command.CommandText = string.Format(@" Select count(*) from Record where StationID='{0}' and RecordTime='{1}' ", record.StationID, record.RecordTime.ToString("yyyy/MM/dd HH:mm")); connection.Open(); int countResult = int.Parse(command.ExecuteScalar().ToString()); connection.Close(); return(countResult > 0); }
public async void removeCoursePackgeAsync(Object Sender, EventArgs args) { DownloadImageButton button = (DownloadImageButton)Sender; string id = button.ClassId; StackLayout item = (StackLayout)button.Parent.Parent; Models.Record course = await App.Database.GetCourseByID(id); course.Deleted = "true"; course.Downloaded = false; int del = await App.Database.SaveItemAsync(course); Container.Children.Remove(item); // let's delete the downloaded files to clear up space // string courseindex = "Courses/" + id; string localFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); string coursePath = Path.GetDirectoryName(Path.Combine(localFolder, courseindex)); System.IO.DirectoryInfo di = new DirectoryInfo(coursePath); foreach (FileInfo file in di.EnumerateFiles()) { file.Delete(); } foreach (DirectoryInfo dir in di.EnumerateDirectories()) { dir.Delete(true); } await Task.Delay(500).ContinueWith(t => getFreeStorage()); }
public IActionResult Create(Models.Record record) { _context.Records.Add(record); _context.SaveChanges(); return(CreatedAtRoute("GetRecord", new { id = record.Id }, record)); }
public void addRecord(string name, long time, DateTime date) { var db = App.conn; //insert into db string sql_insert = @"INSERT INTO Record(Name, FinishTime, Date) VALUES (?,?,?)"; var id = (long)0; string sql_select = @"SELECT last_insert_rowid() FROM Record"; try { using (var statement = db.Prepare(sql_insert)) { statement.Bind(1, name); statement.Bind(2, time); statement.Bind(3, date.ToString()); statement.Step(); } using (var statement = db.Prepare(sql_select)) { while (statement.Step() != SQLiteResult.DONE) { id = (long)statement[0]; } } } catch (System.Exception ex) { //todo:handling exception } var newRecord = new Models.Record(id, name, time, date); this._recordList.Add(newRecord); }
public int SaveImportedRecord(Models.Record record, string userId) { using (SqlConnection con = new SqlConnection(ConnectionString)) { using (SqlCommand cmd = new SqlCommand("SaveImportedRecord", con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@RecordId", record.Id); cmd.Parameters.AddWithValue("@ExpirationDate", record.ExpirationDate); cmd.Parameters.AddWithValue("@CreationDate", record.CreationDate); cmd.Parameters.AddWithValue("@CarRegistartionNumber", record.CarRegistartionNumber); cmd.Parameters.AddWithValue("@AdditionalInfo", record.AdditionalInfo); cmd.Parameters.AddWithValue("@RecordTypeName", record.RecordTypeName); cmd.Parameters.AddWithValue("@Email", record.Email); cmd.Parameters.AddWithValue("@PhoneNumber", record.PhoneNumber); cmd.Parameters.AddWithValue("@ClientName", record.ClientName); cmd.Parameters.AddWithValue("@ModifiedByUser", Guid.Parse(userId)); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } } return(0); }
public async void PostAddsRecord() { var mockRecordRepository = new Mock <IRecordRepository>(); mockRecordRepository .Setup(p => p.Add(It.IsAny <Models.Record>())) .Returns(async() => { await Task.Yield(); }); var recordRepository = mockRecordRepository.Object; var target = new RecordsController(recordRepository); var recordToPost = new Models.Record { Id = "", Value = "This is a good record." }; var result = await target.Post(recordToPost); Assert.IsAssignableFrom <HttpOkObjectResult>(result); var record = ((HttpOkObjectResult)result).Value as Models.Record; Assert.NotNull(record); Assert.False(string.IsNullOrWhiteSpace(record.Id), "Record Id should not be null."); Assert.Equal(recordToPost.Value, record.Value); }
public Guid SaveRecord(Models.Record record, Guid userId) { using (SqlConnection con = new SqlConnection(ConnectionString)) { using (SqlCommand cmd = new SqlCommand("SaveRecords", con)) { var isNew = record.Id == Guid.Empty; record.Id = isNew ? Guid.NewGuid() : record.Id; record.CreationDate = DateTime.Now; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@IsNew", isNew); cmd.Parameters.AddWithValue("@RecordId", record.Id); cmd.Parameters.AddWithValue("@PhoneNumber", record.PhoneNumber); cmd.Parameters.AddWithValue("@ExpirationDate", record.ExpirationDate); cmd.Parameters.AddWithValue("@CreationDate", record.CreationDate); cmd.Parameters.AddWithValue("@CarRegistartionNumber", record.CarRegistartionNumber); cmd.Parameters.AddWithValue("@ClientId", record.ClientId); cmd.Parameters.AddWithValue("@AdditionalInfo", record.AdditionalInfo); cmd.Parameters.AddWithValue("@Email", record.Email); cmd.Parameters.AddWithValue("@ClientName", record.ClientName); cmd.Parameters.AddWithValue("@RecordType", record.RecordType); cmd.Parameters.AddWithValue("@VehicleTypeId", record.VehicleTypeId); cmd.Parameters.AddWithValue("@ClientInformedStatusId", record.ClientInformedStatusId); cmd.Parameters.AddWithValue("@ModifiedByUser", userId); con.Open(); var reader = cmd.ExecuteNonQuery(); con.Close(); return(record.Id); } } }
private async void RemoveCourseClick(object sender, EventArgs args) { Button button = (Button)sender; string id = button.ClassId; Models.Record course = await App.Database.GetCourseByID(id); await App.Database.DeleteItemAsync(course); }
public async void buildSettings() { Container.Children.Clear(); Courses c = new Courses(); List <Models.Record> courses = await c.CheckForCourses(); foreach (Models.Record course in courses) { if (course.Deleted == "false") { StackLayout layout; Models.Record courseRecord = await App.Database.GetCourseByID(course.CourseID); layout = new StackLayout { Spacing = 1, ClassId = "course_" + course.CourseID }; Label title = new Label { Text = course.CourseName, Style = (Style)Application.Current.Resources["headerStyle"] }; DownloadImageButton delete = new DownloadImageButton { Source = "outline_remove_circle_outline_black_48.png", ClassId = course.CourseID, BackgroundColor = Color.Transparent, BorderColor = Color.Transparent }; delete.Clicked += removeCoursePackgeAsync; /// layout in a grid Grid btnGrid = new Grid() { HorizontalOptions = LayoutOptions.Center }; btnGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(50) }); btnGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); btnGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(80) }); btnGrid.Children.Add(title, 0, 0); btnGrid.Children.Add(delete, 1, 0); layout.Children.Add(btnGrid); Container.Children.Add(layout); } } }
/// <summary> /// 保存记录 /// </summary> /// <param name="model"></param> public static void SaveRecord(Models.Record model) { var lstModel = GetRecord(); lstModel.Add(model); var json = Newtonsoft.Json.JsonConvert.SerializeObject(lstModel); SaveJson("Record", json); }
public Task <int> SaveItemAsync(Models.Record item) { if (item.ID != 0) { return(database.UpdateAsync(item)); } else { return(database.InsertAsync(item)); } }
private void MyListView_SelectionChanged(object sender, SelectionChangedEventArgs e) { Models.Record model = e.CurrentSelection.FirstOrDefault() as Models.Record; if (model != null) { Navigation.PushAsync(new Pages.EditRecordPage(model, this)); } //Deselect Item ((CollectionView)sender).SelectedItem = null; }
public EditRecordPage(Models.Record _record, ShowRecordsPage _page) { InitializeComponent(); page = _page as Pages.ShowRecordsPage; record = _record; amount.Text = record.amount.ToString(); at.Text = record.description; if (!string.IsNullOrWhiteSpace(record.category.name)) { clist.Text = record.category.name; } }
public List <Models.Record> GetAllRecords(FilterModel filters, int pageSize = 50, int pageNumber = 0) { using (SqlConnection con = new SqlConnection(ConnectionString)) { using (SqlCommand cmd = new SqlCommand("GetAllRecords", con)) { var from = filters.ExpirationDateFrom.HasValue ? filters.ExpirationDateFrom.Value : DateTime.Parse("01/01/2010"); var until = filters.ExpirationDateUntil.HasValue ? filters.ExpirationDateUntil.Value : DateTime.Parse("01/01/2090"); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@PageNumber", pageNumber); cmd.Parameters.AddWithValue("@PageSize", pageSize); cmd.Parameters.AddWithValue("@StartDate", from); cmd.Parameters.AddWithValue("@EndDate", until); cmd.Parameters.AddWithValue("@ClientId", filters.ClientId); cmd.Parameters.AddWithValue("@CarRegistrationNumber", filters.CarRegistrationNumber); cmd.Parameters.AddWithValue("@RecordType", filters.RecordType); cmd.Parameters.AddWithValue("@PhoneNumber", filters.PhoneNumber); con.Open(); var reader = cmd.ExecuteReader(); var records = new List <Models.Record>(); while (reader.Read()) { var record = new Models.Record() { Id = Guid.Parse(reader["Id"].ToString()), AdditionalInfo = reader["AdditionalInfo"].ToString(), CarRegistartionNumber = reader["CarRegistartionNumber"].ToString(), ClientId = Guid.Parse(reader["ClientId"].ToString()), ClientName = reader["ClientName"].ToString(), CreationDate = DateTime.Parse(reader["CreationDate"].ToString()), ExpirationDate = DateTime.Parse(reader["ExpirationDate"].ToString()), Email = reader["Email"].ToString(), PhoneNumber = reader["PhoneNumber"].ToString(), RecordType = string.IsNullOrEmpty(reader["RecordType"].ToString()) ? (int?)null : int.Parse(reader["RecordType"].ToString()), RecordTypeName = reader["RecordTypeName"].ToString(), VehicleTypeId = string.IsNullOrEmpty(reader["VehicleType"].ToString()) ? (int?)null : int.Parse(reader["VehicleType"].ToString()), VehicleTypeName = reader["VehicleTypeName"].ToString(), ClientInformedStatusName = reader["ClientInformedStatusName"].ToString(), TotalRows = int.Parse(reader["TotalRows"].ToString()), }; records.Add(record); } con.Close(); return(records); } } }
public async void Add() { var target = new RecordRepository(); var record = new Models.Record { Id = Guid.NewGuid().ToString(), Value = "This value was added programmatically!" }; await target.Add(record); var persistedRecord = await target.Get(record.Id); Assert.Equal(JsonConvert.SerializeObject(record), JsonConvert.SerializeObject(persistedRecord)); await target.Delete(record.Id); }
// GET: Records/Details/5 public ActionResult Details(string filename) { filename = "C:/Users/Renuka/Dropbox/WORK/devcodecamp/CAPSTONE/Pages from OfficeRecords_1969952.pdf"; if (filename == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Record record = new Models.Record(); string pdfText = record.ReadPdfFile(filename); if (record == null) { return(HttpNotFound()); } return(View(pdfText)); }
public IActionResult Update(long id, Models.Record record) { var recordToUpdate = _context.Records.Find(id); if (recordToUpdate == null) { return(NotFound()); } recordToUpdate.F1 = record.F1; recordToUpdate.F2 = record.F2; recordToUpdate.F3 = record.F3; _context.Records.Update(recordToUpdate); _context.SaveChanges(); return(NoContent()); }
public async void GetByIdReturnsNotFoundWhenNoMatchExists() { Models.Record record = null; var mockRecordRepository = new Mock <IRecordRepository>(); mockRecordRepository .Setup(p => p.Get("2")) .Returns(async() => { await Task.Yield(); return(record); }); var recordRepository = mockRecordRepository.Object; var target = new RecordsController(recordRepository); var result = await target.Get("2"); Assert.IsAssignableFrom <HttpNotFoundResult>(result); }
private void WriteRecordFields(object recordObj, WriteStep[] writers, IWriter encoder, RecordSchema schema) { var record = new Models.Record(schema); if (recordObj is Dictionary <string, object> obj) { record.Contents = obj; } else { record.Contents = SplitKeyValues(recordObj, schema); } foreach (var writer in writers) { writer.WriteField(record[writer.Field.Name], encoder); } }
public Models.Record GetRecordById(Guid recordId) { using (SqlConnection con = new SqlConnection(ConnectionString)) { using (SqlCommand cmd = new SqlCommand("GetRecordById", con)) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@recordId", recordId); con.Open(); var reader = cmd.ExecuteReader(); var records = new List <Models.Record>(); while (reader.Read()) { var record = new Models.Record() { Id = Guid.Parse(reader["Id"].ToString()), AdditionalInfo = reader["AdditionalInfo"].ToString(), CarRegistartionNumber = reader["CarRegistartionNumber"].ToString(), ClientId = Guid.Parse(reader["ClientId"].ToString()), ClientName = reader["ClientName"].ToString(), CreationDate = DateTime.Parse(reader["CreationDate"].ToString()), ExpirationDate = DateTime.Parse(reader["ExpirationDate"].ToString()), Email = reader["Email"].ToString(), PhoneNumber = reader["PhoneNumber"].ToString(), RecordType = string.IsNullOrEmpty(reader["RecordType"].ToString()) ? (int?)null : int.Parse(reader["RecordType"].ToString()), RecordTypeName = reader["RecordTypeName"].ToString(), VehicleTypeId = string.IsNullOrEmpty(reader["VehicleType"].ToString()) ? (int?)null : int.Parse(reader["VehicleType"].ToString()), VehicleTypeName = reader["VehicleTypeName"].ToString(), ClientInformedStatusId = string.IsNullOrEmpty(reader["ClientInformedStatusId"].ToString()) ? (int?)null : int.Parse(reader["ClientInformedStatusId"].ToString()), ClientInformedStatusName = reader["ClientInformedStatusName"].ToString(), }; records.Add(record); } con.Close(); return(records.Any() ? records.FirstOrDefault() : new Models.Record()); } } }
public async void GetAllReturnsNoResultsWhenRepositoryIsEmpty() { var records = new Models.Record[] { }; var mockRecordRepository = new Mock <IRecordRepository>(); mockRecordRepository .Setup(p => p.GetAll()) .Returns(async() => { await Task.Yield(); return(records); }); var recordRepository = mockRecordRepository.Object; var target = new RecordsController(recordRepository); var result = await target.Get(); Assert.IsAssignableFrom <ObjectResult>(result); var expected = JsonConvert.SerializeObject(new { items = records }); Assert.Equal(expected, JsonConvert.SerializeObject(((ObjectResult)result).Value)); }
public async void GetByIdReturnsMatch() { var record = new Models.Record { Id = "1", Value = "Value 1" }; var recordRepositoryMock = new Mock <IRecordRepository>(); recordRepositoryMock .Setup(p => p.Get(It.Is <string>(s => s == "1"))) .Returns(async() => { await Task.Yield(); return(record); }); var recordRepository = recordRepositoryMock.Object; var target = new RecordsController(recordRepository); var result = await target.Get("1"); Assert.IsAssignableFrom <ObjectResult>(result); var expected = JsonConvert.SerializeObject(record); Assert.Equal(expected, JsonConvert.SerializeObject(((ObjectResult)result).Value)); }
public async Task UpdateAsync(Models.Record obj) { }
public async void buildTranscripts() { Courses.Children.Clear(); Courses c = new Courses(); List <Models.Record> courses = await c.CheckForCourses(); if (courses.Count() > 0) { foreach (Models.Record course in courses) { Frame card; Models.Record courseRecord = await App.Database.GetCourseByID(course.CourseID); card = new MaterialFrame { ClassId = "course_" + course.CourseID }; Label title = new Label { Text = course.CourseName, Style = (Style)Application.Current.Resources["headerStyle"] }; string htmlText = @"<html> <head> <meta name='viewport' content='width=device-width; height=device-height; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;'/> <style type='text/css'> body{font-family:Segoe UI, Helvetica Neue,'Lucida Sans Unicode', Skia, sans-serif; border:0px;padding:0px;margin:0px; background-color:transparent; overflow:hidden; } </style> </head> <body>" + HttpUtility.HtmlDecode(course.CourseDescription) + "</body></html>"; var description = new CustomWebview { HeightRequest = 300, Source = new HtmlWebViewSource { Html = htmlText }, Style = (Style)Application.Current.Resources["descriptionWebView"] }; Grid chartGrid = new Grid() { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, Padding = 0, Margin = 0 }; chartGrid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(100) }); chartGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); chartGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); string completion = (course.CompletionStatus == "") ? (course.CompletionStatus == "unknown") ? "In Progress" : "Not Attempted" : course.CompletionStatus; string success = (course.SuccessStatus == "" || course.SuccessStatus == "unknown") ? "" : "/" + course.SuccessStatus; string score; float score_a = 0; float score_b = 0; float perc_complete; float perc_incomplete; if (String.IsNullOrEmpty(course.ProgressMeasure)) { perc_complete = (course.CompletionStatus == "") ? 0 : (course.CompletionStatus == "Completed") ? 100 : 50; perc_incomplete = 100 - perc_complete; } else { perc_complete = (float.Parse(courseRecord.ProgressMeasure) < 0) ? float.Parse(courseRecord.ProgressMeasure) * 100 : float.Parse(courseRecord.ProgressMeasure); perc_incomplete = 100 - perc_complete; } bool hasScore = false; if (!String.IsNullOrEmpty(course.ScoreRaw) && String.IsNullOrEmpty(course.Score)) { int raw = Convert.ToInt32(course.ScoreRaw); int max = Convert.ToInt32(course.ScoreMax); int min = Convert.ToInt32(course.ScoreMin); int scaled = ((raw - min) / (max - min)) * 100; score = scaled.ToString(); score_a = scaled; score_b = (scaled < 100) ? 100 - score_a : 0; hasScore = true; } else { if (!String.IsNullOrEmpty(course.Score)) { score = (course.Score == "") ? "" : " " + Math.Round(double.Parse(course.Score)).ToString() + "%"; score_a = (double.Parse(course.Score) < 1) ? (float)Math.Round(double.Parse(course.Score) * 100, 0, MidpointRounding.AwayFromZero) : (float)double.Parse(course.Score); score_b = ((Math.Round(score_a)) < 100) ? 100 - score_a : 0; hasScore = true; } } Doughnut doughnut = new Doughnut(); Grid doughnutContainer = (hasScore == false) ? null : doughnut.CompletionChart("Score", (float)Math.Round(score_a, 0, MidpointRounding.AwayFromZero), score_b); Label status = new Label { Text = completion + success, Style = (Style)Application.Current.Resources["headerStyle"] }; Doughnut completeDoughnut = new Doughnut(); Grid completeDoughnutContainer = completeDoughnut.CompletionChart("Complete", (float)Math.Round(perc_complete, 0, MidpointRounding.AwayFromZero), perc_incomplete); if (doughnutContainer != null) { doughnutContainer.VerticalOptions = LayoutOptions.CenterAndExpand; doughnutContainer.HorizontalOptions = LayoutOptions.CenterAndExpand; chartGrid.Children.Add(doughnutContainer, 0, 0); } StackLayout layout = new StackLayout(); card.Content = layout; layout.Children.Add(title); completeDoughnutContainer.VerticalOptions = LayoutOptions.CenterAndExpand; completeDoughnutContainer.HorizontalOptions = LayoutOptions.CenterAndExpand; chartGrid.Children.Add(completeDoughnutContainer, 1, 0); layout.Children.Add(chartGrid); Courses.Children.Add(card); } } else { Label message = new Label { Text = "You have not started any courses on this device.", Style = (Style)Application.Current.Resources["headerStyle"] }; Courses.Children.Add(message); } }
private async void launchCourse(string courseid) { // create an api object API api = new API(); Models.Record courseRecord = await App.Database.GetCourseByID(courseid); // use MessagingCenter to talk to the webview // MessagingCenter.Subscribe <string>(this, "API", async(cmi) => { message APIMessage = JsonConvert.DeserializeObject <message>(cmi); string status = APIMessage.status; string CMIString = APIMessage.cmi; // if it's a commit then save the cmi object to the course record if (status == "Commit") { try { Device.BeginInvokeOnMainThread(async() => await api.Commit(CMIString, courseid)); } catch (Exception ex) { Crashes.TrackError(ex); } } else if (status == "Terminate") { // api.CommitToLMS(CMIString, courseid); // not working yet //Navigation.PopAsync(); // Models.Record courseRecord = await App.Database.GetCourseByID(courseid); var connection = Connectivity.NetworkAccess; try { if (connection == NetworkAccess.Internet) { Device.BeginInvokeOnMainThread(async() => await api.CommitToLMS(CMIString, courseid)); courseRecord.Synced = true; } else { courseRecord.Synced = false; } Device.BeginInvokeOnMainThread(async() => await Navigation.PopModalAsync()); MessagingCenter.Send("", "RefreshLP"); } catch (Exception ex) { courseRecord.Synced = false; Crashes.TrackError(ex); } await App.Database.SaveItemAsync(courseRecord); } }); // find the html path string launch = (!courseRecord.PDF) ? itemPath(courseid) : ""; string item_id = (!courseRecord.PDF) ? itemID(courseid) : courseid; // get the cmi object string CMI = await cmiInit(courseid); // build the path to the local file string courseindex = (!String.IsNullOrEmpty(launch)) ? "Courses/" + courseid + "/" + launch : "Courses/" + courseid + "/CoursePackage.pdf"; string localFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); string coursePath = Path.Combine(localFolder, courseindex); // get the api connector var assembly = IntrospectionExtensions.GetTypeInfo(typeof(ViewCourse)).Assembly; string APIJS = ""; using (var APIStream = assembly.GetManifestResourceStream("TCMobile.API.js")) { StreamReader apiReader = new StreamReader(APIStream); APIJS = apiReader.ReadToEnd(); } // get the baseurl String baseUrl = "file:/" + Path.GetDirectoryName(coursePath); FileStream stream = File.OpenRead(coursePath); if (stream == null) { throw new InvalidOperationException( String.Format("Cannot create stream from specified URL: {0}", "course.htm")); } StreamReader reader = new StreamReader(stream); string htmlString = reader.ReadToEnd(); courseWindow = new HybridWebView { VerticalOptions = LayoutOptions.FillAndExpand, HorizontalOptions = LayoutOptions.FillAndExpand, HeightRequest = 20, AutomationId = "TCMobile_CourseView", Margin = new Thickness(0) }; // add the webview // create the webview HtmlWebViewSource html = new HtmlWebViewSource(); if (!String.IsNullOrEmpty(CMI)) { courseWindow.APIJS = APIJS + " var cmi=" + CMI; } else { API.Cmi cmi = new API.Cmi(); cmi.course_id = courseid; cmi._version = "2004"; cmi.sco_id = item_id; cmi.session_guid = new Guid().ToString(); cmi.entry = "normal"; cmi.learner_id = Constants.StudentID; cmi.learner_name = Constants.firstName + " " + Constants.lastName; cmi.score = new API.Score(); cmi.comments = ""; cmi.completion_status = "unknown"; cmi.success_status = "unknown"; cmi.suspend_data = ""; cmi.session_time = ""; cmi.total_time = ""; cmi.score.scaled = ""; cmi.score.raw = ""; cmi.location = ""; cmi.exit = ""; cmi.objectives = new List <API.Objectives>(); cmi.interactions_data = new API.Interactions_Data(); cmi.objectives_data = new API.Objectives_Data(); cmi.objectives_data.objectives = new List <API.Objective>(); cmi.interactions_data.interactions = new List <API.Interactions>(); cmi.interactions_data._children = "id,type,objectives,timestamp,correct_responses,weighting,learner_response,result,latency,description"; cmi.objectives_data._children = "id,score,success_status,completion_status,description"; cmi.nav_request = new API.NavRequest(); cmi.nav_request.@continue = "false"; cmi.nav_request.previous = "false"; cmi.nav_request.choice = "unknown"; cmi.comments_from_learner = new API.CommentsFromLearner(); cmi.interactions = new List <API.Interactions>(); cmi.comments_from_learner.comments = new List <object>(); cmi.comments_from_learner._children = "comment,location,timestamp"; string cmiString = JsonConvert.SerializeObject(cmi); courseWindow.APIJS = APIJS + " var cmi=" + cmiString; } // set the base url html.BaseUrl = baseUrl; // pass in the API connector // // pass in the html courseWindow.Source = htmlString; // pass in the file Android courseWindow.Uri = coursePath; // pass in the file iOS courseWindow.iOSPath = courseindex; WebViewContainer.Children.Add(courseWindow); }
// GET:rain/realTime //TODO 实时降雨的查询 public ActionResult realTime() { //DateTime from = Convert.ToDateTime(Request.Params.Get("from")); //DateTime to = Convert.ToDateTime(Request.Params.Get("to")); //string stationId = Request.Params.Get("station-id"); //var list = new List<KeyValuePair<string, IQueryable<Models.rain>>>(); //list.Add(new KeyValuePair<string, IQueryable<Models.rain>>("data", DAL.RainHandler.singleRainRecord(from, to, stationId))); //ViewData.Add("data",list); //ViewBag.Title = "实时降雨信息"; //return View(); /*显示所有站点的今日降雨*/ #region 初始化查询条件 DateTime today = DateTime.Now; //还不到8点,今日按照从昨天早上8点开始计算 if (today.Hour <= 8) { today = today.AddDays(-1); } DateTime from = new DateTime( year: today.Year, month: today.Month, day: today.Day, hour: 8, minute: 0, second: 0 ); DateTime to = new DateTime( year: today.Year, month: today.Month, day: today.Day + 1, hour: DateTime.Now.Hour, minute: 0, second: 0 ); long?subcenterId = null; List <Models.Station> stations = DAL.StationHandler.station(subcenterId); #endregion //初始化查询结果 Models.QueryResult result = new Models.QueryResult(); //为查询结果添加表头 result.dataTitles.Add("站号"); result.dataTitles.Add("站名"); result.dataTitles.Add("站类"); result.dataTitles.Add("所在地"); result.dataTitles.Add("累计"); DateTime current = DateTime.Now; List <DateTime> period = new List <DateTime>(); while (from < current) { period.Add(current); result.dataTitles.Add((current.AddHours(-1).Hour) + "-" + current.Hour); current = current.AddHours(-1); } foreach (Models.Station station in stations) { IQueryable <Models.rain> queryResult = DAL.RainHandler.singleRainRecord(from, to, station.stationId); //添加累计和 Models.Record record = new Models.Record(); decimal sum = queryResult.Where(r => r.datatime <= period.First() && r.datatime >= period.Last()).Sum(r => r.periodrain).Value; record.station = station; record.datas.Add(sum); //每个时间段都分别求出结果 foreach (DateTime time in period) { decimal data = queryResult.Where(r => r.datatime < time.AddHours(1) && r.datatime >= time).Sum(r => r.periodrain).Value; record.datas.Add(data); } result.records.Add(record); ViewData.Add("table", result); } return(View()); }
public Task <int> DeleteItemAsync(Models.Record item) { return(database.DeleteAsync(item)); }