void CollectKeyEvents() { if (IsMacOS()) { int eventCount = UnityEPL.CountKeyEvents(); if (eventCount >= 1) { int keyCode = UnityEPL.PopKeyKeycode(); double timestamp = UnityEPL.PopKeyTimestamp(); bool downState; keyDownStates.TryGetValue(keyCode, out downState); keyDownStates[keyCode] = !downState; ReportKey(keyCode, keyDownStates[keyCode], OSXTimestampToTimestamp(timestamp)); } } else { foreach (KeyCode keyCode in System.Enum.GetValues(typeof(KeyCode))) { if (Input.GetKeyDown(keyCode)) { ReportKey((int)keyCode, true, DataReporter.RealWorldTime()); } if (Input.GetKeyUp(keyCode)) { ReportKey((int)keyCode, false, DataReporter.RealWorldTime()); } } } }
/// <summary> /// Called when the PlaybackDeviceAvailableMessage message is received /// If this is a change then report it /// </summary> /// <param name="message"></param> private static void DeviceAvailable(PlaybackDevice newDevice) { PlaybackDevice oldDevice = PlaybackManagerModel.AvailableDevice; // Check for no new device if (newDevice == null) { // If there was an exisiting availabel device then repoprt this change if (oldDevice != null) { PlaybackManagerModel.AvailableDevice = null; DataReporter?.SelectPlaybackDevice(oldDevice); } } // If there was no available device then save the new device and report the change else if (oldDevice == null) { PlaybackManagerModel.AvailableDevice = newDevice; DataReporter?.SelectPlaybackDevice(oldDevice); } // If the old and new are different type (local/remote) then report the change else if (oldDevice.IsLocal != newDevice.IsLocal) { PlaybackManagerModel.AvailableDevice = newDevice; DataReporter?.SelectPlaybackDevice(oldDevice); } // If both devices are remote but different then report the change else if ((oldDevice.IsLocal == false) && (newDevice.IsLocal == false) && (oldDevice.FriendlyName != newDevice.FriendlyName)) { PlaybackManagerModel.AvailableDevice = newDevice; DataReporter?.SelectPlaybackDevice(oldDevice); } }
void CollectMousePosition() { Dictionary <string, object> dataDict = new Dictionary <string, object>(); dataDict.Add("position", Input.mousePosition); eventQueue.Enqueue(new DataPoint("mouse position", DataReporter.RealWorldTime(), dataDict)); lastMousePositionReportFrame = Time.frameCount; }
//ramulator expects this when you display words to the subject. //for words, stateName is "WORD" public void SetState(string stateName, bool stateToggle, System.Collections.Generic.Dictionary <string, object> sessionData) { sessionData.Add("name", stateName); sessionData.Add("value", stateToggle.ToString()); DataPoint sessionDataPoint = new DataPoint("STATE", DataReporter.RealWorldTime(), sessionData); SendMessageToRamulator(sessionDataPoint.ToJSON()); }
/// <summary> /// Called when a MediaPlayingMessage is received. /// If this is a change of play state then let the view know /// </summary> /// <param name="message"></param> private static void MediaPlaying(bool isPlaying) { if (MediaControllerViewModel.IsPlaying != isPlaying) { MediaControllerViewModel.IsPlaying = isPlaying; DataReporter?.PlayStateChanged(); } }
////////// // Microphone testing states ////////// protected void DoRecordTest() { state.micTestIndex++; string file = System.IO.Path.Combine(manager.fileManager.SessionPath(), "microphone_test_" + DataReporter.TimeStamp().ToString("yyyy-MM-dd_HH_mm_ss") + ".wav"); state.recordTestPath = file; RecordTest(file); }
public void Init() { if (Marshal.PtrToStringAuto(OpenUSB()) == "didn't open usb...") { im.ReportEvent("syncbox disconnected", null, DataReporter.TimeStamp()); } StopPulse(); Start(); }
/// <summary> /// Called when the PlaybackDeviceAvailableMessage message is received /// If this is a change then report it /// </summary> /// <param name="message"></param> private static void DeviceAvailable(PlaybackDevice newDevice) { // If the view data is not available yet, just update the model. // Otherwise report to the view and then update the model MediaControllerViewModel.PlaybackDeviceAvailable = (newDevice != null); if (dataReporter.DataAvailable == true) { DataReporter?.DeviceAvailable(); } }
public void SendMathMessage(string problem, string response, int responseTimeMs, bool correct) { Dictionary <string, object> mathData = new Dictionary <string, object>(); mathData.Add("problem", problem); mathData.Add("response", response); mathData.Add("response_time_ms", responseTimeMs.ToString()); mathData.Add("correct", correct.ToString()); DataPoint mathDataPoint = new DataPoint("MATH", DataReporter.RealWorldTime(), mathData); SendMessageToRamulator(mathDataPoint.ToJSON()); }
//ramulator expects this before the beginning of a new list public void BeginNewTrial(int trialNumber) { if (zmqSocket == null) { throw new Exception("Please begin a session before beginning trials"); } System.Collections.Generic.Dictionary <string, object> sessionData = new Dictionary <string, object>(); sessionData.Add("trial", trialNumber.ToString()); DataPoint sessionDataPoint = new DataPoint("TRIAL", DataReporter.RealWorldTime(), sessionData); SendMessageToRamulator(sessionDataPoint.ToJSON()); }
/// <summary> /// Called during startup, or library change, when the storage data is available /// </summary> /// <param name="message"></param> private static void StorageDataAvailable() { // Save the current playback mode obtained from the Playback object PlaybackModeModel.AutoOn = Playback.AutoPlayOn; PlaybackModeModel.RepeatOn = Playback.RepeatPlayOn; PlaybackModeModel.ShuffleOn = Playback.ShufflePlayOn; // Update the summary state in the model PlaybackModeModel.UpdateActivePlayMode(); DataReporter?.DataAvailable(); }
/// <summary> /// Called when a SongSelectedMessage has been received /// Get the selected Song from the Now Playing playlist and report it /// </summary> private static void SongSelected() { int currentSongIndex = Playlists.CurrentSongIndex; // Only pass this on if a song has been selected. If no song is selected then SongFinished should have been called. if (currentSongIndex != -1) { MediaControllerViewModel.SongPlaying = (( SongPlaylistItem )Playlists.GetNowPlayingPlaylist(ConnectionDetailsModel.LibraryId).PlaylistItems[currentSongIndex]).Song; DataReporter?.SongPlayingChanged(); } }
/// <summary> /// Called in response to the receipt of a PlaySongMessage /// </summary> private static void PlaySong(Song songToPlay, bool dontPlay) { PlaybackManagerModel.CurrentSong = songToPlay; if ((PlaybackManagerModel.CurrentSong != null) && (dontPlay == false)) { DataReporter?.PlayCurrentSong(); } else { DataReporter?.Stop(); } }
/// <summary> /// Called when the playback data is available to be displayed /// </summary> private static void StorageDataAvailable() { // Save the libray being used locally to detect changes PlaybackManagerModel.LibraryId = ConnectionDetailsModel.LibraryId; // Get the sources associated with the library PlaybackManagerModel.Sources = Sources.GetSourcesForLibrary(PlaybackManagerModel.LibraryId); PlaybackManagerModel.DataValid = true; // Let the views know that playback data is available DataReporter?.DataAvailable(); }
public override void SendMessage(string type, Dictionary <string, object> data) { DataPoint point = new DataPoint(type, DataReporter.TimeStamp(), data); string message = point.ToJSON(); UnityEngine.Debug.Log("Sent Message"); UnityEngine.Debug.Log(message); Byte[] bytes = System.Text.Encoding.UTF8.GetBytes(message); NetworkStream stream = GetWriteStream(); stream.Write(bytes, 0, bytes.Length); ReportMessage(message, true); }
private void buttonSaveReport_Click(object sender, EventArgs e) { if (textBoxReport.Text == string.Empty) { MessageBox.Show("Нету отчёта для сохранения."); } DataReporter dr = new DataReporter(); if (!dr.SaveReport(textBoxReport.Text, IsTrainer ? "trainer" : "student")) { MessageBox.Show("Произошла ошибка при сохранении отчёта."); } else { this.Close(); } }
public async Task WatchAMovieAsync() { var watchMovieInteration = new WatchMovieInteraction(Identifier); var arr = new[] { @" __ __ _ ", @"| \/ | _____ _(_) ___ ", @"| |\/| |/ _ \ \ / / |/ _ \", @"| | | | (_) \ V /| | __/", @"|_| |_|\___/ \_/ |_|\___|", }; DrawStepTitle(arr); await watchMovieInteration.ExecuteInteraction(); var reporter = new DataReporter(); var knownDataHelper = new KnownDataHelper(); KnownDataXConnect knownData = await knownDataHelper.GetKnownDataByIdentifierViaXConnect(Identifier); if (knownData?.PersonalInformationDetails != null) { System.Console.WriteLine("Enjoy your movie, " + knownData.PersonalInformationDetails.FirstName + "!"); System.Console.WriteLine("Since you're a loyalty card holder, we'll take payment for your ticket now."); } else { System.Console.WriteLine("Details was null"); } // Initialize a client using the validate configuration if (watchMovieInteration.XConnectContact != null) { DrawTriggerMessage("You scanned your ticket - the bar code has your loyalty card information embedded in it."); } System.Console.ReadKey(); }
//this coroutine connects to ramulator and communicates how ramulator expects it to //in order to start the experiment session. follow it up with BeginNewTrial and //SetState calls public IEnumerator BeginNewSession(int sessionNumber) { //Connect to ramulator/////////////////////////////////////////////////////////////////// zmqSocket = new NetMQ.Sockets.PairSocket(); zmqSocket.Bind(address); //Debug.Log ("socket bound"); yield return(WaitForMessage("CONNECTED", "Ramulated not connected.")); //SendSessionEvent////////////////////////////////////////////////////////////////////// System.Collections.Generic.Dictionary <string, object> sessionData = new Dictionary <string, object>(); sessionData.Add("name", UnityEPL.GetExperimentName()); sessionData.Add("version", Application.version); sessionData.Add("subject", UnityEPL.GetParticipants()[0]); sessionData.Add("session_number", sessionNumber.ToString()); DataPoint sessionDataPoint = new DataPoint("SESSION", DataReporter.RealWorldTime(), sessionData); SendMessageToRamulator(sessionDataPoint.ToJSON()); yield return(null); //Begin Heartbeats/////////////////////////////////////////////////////////////////////// InvokeRepeating("SendHeartbeat", 0, 1); //SendReadyEvent//////////////////////////////////////////////////////////////////// DataPoint ready = new DataPoint("READY", DataReporter.RealWorldTime(), new Dictionary <string, object>()); SendMessageToRamulator(ready.ToJSON()); yield return(null); yield return(WaitForMessage("START", "Start signal not received")); InvokeRepeating("ReceiveHeartbeat", 0, 1); }
private void buttonCreateReport_Click(object sender, EventArgs e) { if (CurrentTargetId == -1) { textBoxReport.Text = ""; MessageBox.Show("Не выбран " + (IsTrainer ? "тренер" : "ученик") + "."); return; } DataReporter dr = new DataReporter(); string reportText = string.Empty; if (IsTrainer) { try { reportText = dr.GetTrainerReport(CurrentTargetId, dtStart.Value, dtEnd.Value, false); } catch { MessageBox.Show("Произошла ошибка при формировании отчёта."); return; } } else { try { reportText = dr.GetStudentReport(CurrentTargetId, dtStart.Value, dtEnd.Value); } catch { MessageBox.Show("Произошла ошибка при формировании отчёта."); return; } } textBoxReport.Text = reportText; tabControl1.SelectTab(1); }
/** * Flushes the event buffer. * The buffer is flushed to an HTTP backend. * Failing to flush to the HTTP backend, the data will be flushed to a file. */ private static async Task FlushBufferThread(string username, List <string> buffer) { string bufferLines = "sessiontime(ms);event"; // Read lines from bufferfile first. DataReporter.ensureBufferFile(BUFFER_FILE); string[] fileLines = System.IO.File.ReadAllLines(BUFFER_FILE); bufferLines += "\n" + String.Join("\n", fileLines.Skip(1)); // Add all lines from the in-memory buffer. lock (buffer) { foreach (string line in buffer) { bufferLines += "\n" + line; } buffer.Clear(); } // Overwrite the buffer file with it's new contents. System.IO.File.WriteAllText(BUFFER_FILE, bufferLines); try { // Try to upload data to server. string url = string.Format("http://{0}/?app={1}&username={2}", DataReporter.REMOTE_IP, DataReporter.APP_ID, username); HttpClient client = new HttpClient(); HttpResponseMessage response = await client.PostAsync(url, new ByteArrayContent(Encoding.ASCII.GetBytes(bufferLines))); response.EnsureSuccessStatusCode(); // Clear the buffer file. System.IO.File.WriteAllText(BUFFER_FILE, "sessiontime(ms);event"); } catch (Exception e) { // Ignore all exceptions here, just log them. Debug.LogError("[DataReporter] Encountered an exception while attempting to upload the data. (" + e.Message + ")"); } }
/// <summary> /// Displays custom columns /// </summary> private void DisplayCustomColumns() { int roleID = 0; LabelQueryResult.Text = Resources.Labels.BlankText; if (Session["isPortalAdmin"] != null) { bool isPortalAdmin = (bool)Session["isPortalAdmin"]; if (isPortalAdmin) { roleID = 1; } else { DataSet dsRoles = (DataSet)Session["UserRoles"]; // Assumption : for a product one user can have only one Role [Product Admin/Product Guest/Product CSR] DataRow[] drRoles = dsRoles.Tables[0].Select("PRDCT_ID='" + Session["SelectedProduct"].ToString() + "'"); if (drRoles.Length > 0) { roleID = int.Parse(drRoles[0]["ROLE_ID"].ToString(), CultureInfo.InvariantCulture); } } } string[] columnArray = DataProvider.GetConfiguredDisplayFields(Session["SelectedProduct"].ToString(), "Registration", roleID); string systemFieldID = String.Empty; string systemFieldValue = String.Empty; string customFieldID = String.Empty; string customFieldValue = String.Empty; bool isDataReferenceField = false; if (columnArray != null && columnArray.Length > 0) { string filterCiteria = string.Empty; if (RadioButtonFilterOn.Checked) { Session["IsReportOnDateRange"] = false; string[] arrFilterValue = DropDownListFilterOn.SelectedValue.Split("^".ToCharArray()); Session["FilterOn"] = DropDownListFilterOn.SelectedValue; string filterValue = GetFilterValue(); #region Display Serial Number Details [if filter is on Serial Number] PanelSerialKeyDetails.Visible = false; if (DropDownListFilterOn.SelectedValue.IndexOf("REG_SERIAL_KEY") > 0) { DisplayLicenseDetails(); } #endregion isDataReferenceField = bool.Parse(arrFilterValue[3].ToLower()); if (arrFilterValue[0] == "True") { systemFieldID = arrFilterValue[1]; systemFieldValue = filterValue; //if (!string.IsNullOrEmpty(filterValue)) //{ // filterCiteria += " and [" + arrFilterValue[1] + "] like N'" + filterValue.Replace("'", "''") + "'"; //} //else //{ // filterCiteria += " and ([" + arrFilterValue[1] + "] ='' or [" + arrFilterValue[1] + "] is null)"; //} } else { customFieldID = arrFilterValue[2]; customFieldValue = filterValue; /* * if (!string.IsNullOrEmpty(filterValue)) * { * customFieldFilter += " [" + arrFilterValue[1] + "] like N'" + filterValue.Replace("'", "''") + "'"; * } * else * { * customFieldFilter += " ([" + arrFilterValue[1] + "] = '' or [" + arrFilterValue[1] + "] is null)"; * }*/ } } if (RadioButtonDateRange.Checked) { PanelSerialKeyDetails.Visible = false; //filterCiteria += " and ( REC_DATE >= '" + TextBoxDateFrom.Text + " 00:00:00' and REC_DATE <='" + TextBoxDateTo.Text + " 23:59:59')"; filterCiteria = " ( REC_DATE BETWEEN '" + TextBoxDateFrom.Text + " 00:00:00' and '" + TextBoxDateTo.Text + " 23:59:59')"; Session["IsReportOnDateRange"] = true; Session["FilterFrom"] = TextBoxDateFrom.Text; Session["FilterTo"] = TextBoxDateTo.Text; } int pageSize = 0; if (RadioButtonCSV.Checked == true) { pageSize = int.Parse(DataProvider.GetDBConfigValue("REPORT_CSV_MAX_RECORDS"), CultureInfo.CurrentCulture); } if (RadioButtonOnscreen.Checked == true) { pageSize = int.Parse(DataProvider.GetDBConfigValue("REPORT_ONSCREEN_MAX_RECORDS"), CultureInfo.CurrentCulture); } DataSet dsRegistrationDetails = DataReporter.GetRegistrationDetails(Session["SelectedProduct"].ToString(), 1, pageSize, "REC_ID desc", isDataReferenceField, systemFieldID, systemFieldValue, customFieldID, customFieldValue, filterCiteria); DataTable dtRegistrationDetails = dsRegistrationDetails.Tables[0]; int MaxDisplayCount = int.Parse(DataProvider.GetDBConfigValue("REPORT_ONSCREEN_MAX_RECORDS"), CultureInfo.CurrentCulture); LabelResultCount.Text = dtRegistrationDetails.Rows.Count.ToString(CultureInfo.InvariantCulture) + Resources.Labels.Space + Resources.Labels.RecordsFound; LabelResultCount.ForeColor = Color.Blue; if (RadioButtonCSV.Checked == true || dtRegistrationDetails.Rows.Count > MaxDisplayCount) { Session["ReportMode"] = "CSV"; #region Write Result to CSV File RadioButtonCSV.Checked = true; PanelRegistrationDetails.Visible = false; ImageButtonPrint.Visible = false; if (dtRegistrationDetails.Rows.Count > 0) { // Create CSV file in TempReports. string reportFileName = Server.MapPath("..") + "/TempReports/" + Session["UserID"].ToString() + "_" + Session.SessionID + ".csv"; StreamWriter swReportFile = File.CreateText(reportFileName); // Write filter Criteria to CSV string filterCriteria = GetFilterCriteria(); swReportFile.WriteLine("Filter Criteria: " + filterCriteria); swReportFile.WriteLine(""); // Write PanelSerialKeyDetails to CSV if (PanelSerialKeyDetails.Visible) { swReportFile.WriteLine("Serial Number Details"); swReportFile.WriteLine("Serial Number " + "," + LabelSerialKey.Text); swReportFile.WriteLine("Total Licenses " + "," + LabelTotalLicenses.Text); swReportFile.WriteLine("Used Licenses " + "," + LabelUsedLicenses.Text); swReportFile.WriteLine("Remaining Licenses " + "," + LabelRemainingLicenses.Text); swReportFile.WriteLine(""); swReportFile.WriteLine("Registration Details"); swReportFile.WriteLine(""); } WriteColumnHeaders(columnArray, dsRegistrationDetails.Tables[1], swReportFile); swReportFile.WriteLine(""); for (int rowCount = 0; rowCount < dtRegistrationDetails.Rows.Count; rowCount++) { string data = ""; for (int col = 0; col < columnArray.Length; col++) { data = dtRegistrationDetails.Rows[rowCount][columnArray[col]].ToString(); data = "\"" + data.Replace("\"", "\"\"") + "\""; if (col < columnArray.Length - 1) { swReportFile.Write(data + ","); } else { swReportFile.WriteLine(data); } } } swReportFile.Close(); string reportUrl = "<a href='../TempReports/" + Session["UserID"].ToString() + "_" + Session.SessionID + ".csv'>"; StringBuilder successMessage = new StringBuilder(); successMessage.Append(Resources.SuccessMessages.ReportGeneratedSuccessfully); successMessage.Append(Resources.Labels.FullStop); successMessage.Append(Resources.Labels.Space); successMessage.Append(reportUrl); successMessage.Append(Resources.Labels.ClickHere); successMessage.Append(Resources.Labels.Space); successMessage.Append(Resources.Labels.ToDownload); successMessage.Append(Resources.Labels.FullStop); LabelQueryResult.Text = successMessage.ToString(); LabelQueryResult.ForeColor = Color.Green; } #endregion } else if (RadioButtonOnscreen.Checked) { Session["ReportMode"] = "Onscreen"; RadioButtonOnscreen.Checked = true; if (dtRegistrationDetails.Rows.Count > 0) { PanelRegistrationDetails.Visible = true; ImageButtonPrint.Visible = true; DisplayColumnHeaders(columnArray, dsRegistrationDetails.Tables[1]); #region Display Result on Screen for (int rowCount = 0; rowCount < dtRegistrationDetails.Rows.Count; rowCount++) { TableRow tr = new TableRow(); tr.BackColor = Color.White; bool isFirstColumn = true; foreach (string coulumnName in columnArray) { try { TableCell td = new TableCell(); if (isFirstColumn) { StringBuilder sbLink = new StringBuilder("<a href='../DataCapture/ManageRegistration.aspx?source=../Reports/ReportIndex.aspx?refererpager=Reports&action=update&REC_ID=" + dtRegistrationDetails.Rows[rowCount]["REC_ID"].ToString() + "&pid=" + Session["SelectedProduct"].ToString() + "' style='text-decoration:underline'>" + dtRegistrationDetails.Rows[rowCount][coulumnName.Trim()].ToString() + "</a>"); td.Text = sbLink.ToString(); } else if (coulumnName.Equals("REG_SERIAL_KEY") == true) { isFirstColumn = true; StringBuilder sbLink = new StringBuilder("<a href='../Views/SerialKeys.aspx?" + Session.SessionID + "=" + dtRegistrationDetails.Rows[rowCount]["REG_SERIAL_KEY"].ToString() + "' style='text-decoration:underline'>" + dtRegistrationDetails.Rows[rowCount][coulumnName.Trim()].ToString() + "</a>"); td.Text = sbLink.ToString(); } else { td.Text = dtRegistrationDetails.Rows[rowCount][coulumnName.Trim()].ToString(); } td.Wrap = false; tr.Cells.Add(td); isFirstColumn = false; } catch (DataException) { } } TableRegistrationDetails.Rows.Add(tr); } } #endregion } } }
/// <summary> /// Called when a SongFinishedMessage has been received /// Update the model and report the change /// </summary> /// <param name="_"></param> private static void SongFinished(Song _) { MediaControllerViewModel.SongPlaying = null; DataReporter?.SongPlayingChanged(); }
/// <summary> /// Called when a MediaProgressMessage has been received. /// Update the values held in the model and inform the DataReporter /// </summary> /// <param name="message"></param> private static void MediaProgress(int currentPosition, int duration) { MediaControllerViewModel.CurrentPosition = currentPosition; MediaControllerViewModel.Duration = duration; DataReporter?.MediaProgress(); }
public static double MillisecondsSinceTheEpoch() { return(DataPoint.ConvertToMillisecondsSinceEpoch(DataReporter.RealWorldTime())); }
private void Pulse() { if (!stopped) { // Send a pulse im.Do(new EventBase <string, Dictionary <string, object>, DateTime>(im.ReportEvent, "syncPulse", null, DataReporter.TimeStamp())); SyncPulse(); // Wait a random interval between min and max int timeBetweenPulses = (int)(TIME_BETWEEN_PULSES_MIN + (int)(InterfaceManager.rnd.NextDouble() * (TIME_BETWEEN_PULSES_MAX - TIME_BETWEEN_PULSES_MIN))); DoIn(new EventBase(Pulse), timeBetweenPulses); } }
/// <summary> /// Called when a SongFinishedMessage has been received. /// </summary> private static void SongFinished(Song _) => DataReporter?.SongFinished();
/// <summary> /// Called when a SongStartedMessage has been received. /// </summary> /// <param name="message"></param> private static void SongStarted(Song songStarted) => DataReporter?.SongStarted(songStarted);
/// <summary> /// Called when a MediaPlayingMessage has been received. /// </summary> /// <param name="message"></param> private static void MediaPlaying(bool isPlaying) => DataReporter?.IsPlaying(isPlaying);
/// <summary> /// Called during startup when the storage data is available /// </summary> private static void StorageDataAvailable() { DataReporter?.DataAvailable(); }
private void SendHeartbeat() { DataPoint sessionDataPoint = new DataPoint("HEARTBEAT", DataReporter.RealWorldTime(), null); SendMessageToRamulator(sessionDataPoint.ToJSON()); }