/// <summary> /// The <see cref="Control.Click"/> event handler for the /// <see cref="ToolStripMenuItem"/> <see cref="cmuShuffle"/>. /// Occurs when the context menues shuffle entry is clicked. /// Sets ur unsets the nodes randomize flag. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">An empty <see cref="EventArgs"/>.</param> private void cmuShuffle_Click(object sender, EventArgs e) { NodesCollection selectedNodes = this.trvSlideshow.SelectedNodes; if (selectedNodes.Count != 1) { return; } SlideshowTreeNode node = this.trvSlideshow.SelectedNodes[0] as SlideshowTreeNode; if (node != null) { if (node.Slide == null) { node.Randomize = this.cmuShuffle.Checked; } else { ExceptionMethods.ProcessMessage( "Please note:", "You cannot shuffle/unshuffle single slides, please select the parent node"); } } this.trvSlideshow.Invalidate(); this.lsvDetails.Invalidate(); }
/// <summary> /// Set up the UDP data stream in the Smart Eye tracker core /// </summary> public void SetupNetworkDataSubscription() { var dataList = new List <TrackerDataId>(); dataList.AddRange(new[] { TrackerDataId.GazeDirectionQ, TrackerDataId.HeadPositionQ, TrackerDataId.RealTimeClock, TrackerDataId.ClosestWorldIntersection, TrackerDataId.LeftPupilDiameter, TrackerDataId.RightPupilDiameter }); string dataIds = dataList.Aggregate(string.Empty, (current, dataId) => current + (TrackerDataTypes.GetData(dataId).Name + ";")); try { this.RpcClient.OpenDataStreamUDP(this.smartEyeSettings.OgamaPort, dataIds); } catch (Exception ex) { if (this.smartEyeSettings.SilentMode) { ExceptionMethods.HandleExceptionSilent(ex); } else { ExceptionMethods.HandleException(ex); } } }
/// <summary> /// Gets the UInt32 at the specified index. /// </summary> /// <param name="index">The index of the UInt32 to get.</param> /// <returns>The UInt32 at the specified index.</returns> /// <exception cref="Kernel.FOS_System.Exceptions.IndexOutOfRangeException"> /// Throws IndexOutOfRangeException if "index" is < 0 or greater than the length of the list. /// </exception> public UInt32 this[int index] { [Drivers.Compiler.Attributes.NoDebug] get { if (index >= nextIndex) { ExceptionMethods.Throw(new Exceptions.IndexOutOfRangeException(index, nextIndex)); } else if (index < 0) { ExceptionMethods.Throw(new Exceptions.IndexOutOfRangeException(index, nextIndex)); } return(_array[index]); } [Drivers.Compiler.Attributes.NoDebug] set { //Throw an exception if the index to set is beyond the length of // the list. //Note: Beyond the length of the list not the capacity! if (index >= nextIndex) { ExceptionMethods.Throw(new Exceptions.IndexOutOfRangeException(index, nextIndex)); } else if (index < 0) { ExceptionMethods.Throw(new Exceptions.IndexOutOfRangeException(index, nextIndex)); } _array[index] = value; } }
/// <summary> /// Wait for data from server. /// </summary> /// <param name="connection"> Current connection on which we are waiting data </param> private void WaitForData(Connections connection) { try { if (connection.ConnectionStream == null) { return; } if (this.memDataReceivedCallback == null) { // Create a callback used by the "BeginRead(...)" function // Called when data is received this.memDataReceivedCallback = new AsyncCallback(this.OnDataReceived); } connection.BytesArrayQueue.Enqueue(new byte[2048]); // TODO : We are not sure that 2048 will be sufficient ! More efficient to read exactly the expected number of bytes // Doing this also insure that we are not currently reading the next message, beacause this can cause an exception in the message parsing. connection.ConnectionStream.BeginRead(connection.BytesArrayQueue.Last(), 0, connection.BytesArrayQueue.Last().Length, this.memDataReceivedCallback, connection); } catch (Exception e) { string message = " Exception catched in WaitForData(...) Method ; Unable to read datas from server : {" + connection.Id + "}" + Environment.NewLine + e.Message; ExceptionMethods.ProcessErrorMessage(message); } }
/////////////////////////////////////////////////////////////////////////////// // Public methods // /////////////////////////////////////////////////////////////////////////////// #region PUBLICMETHODS /// <summary> /// Opens a file dialog to choose the ogamas export file that /// should be imported into the programs database. /// </summary> public static void Start() { try { asciiSettings = new ASCIISettings(); if (asciiSettings.FileDialog.ShowDialog() == DialogResult.OK) { // Save filename string filename = asciiSettings.FileDialog.FileName; // Save import file asciiSettings.Filename = filename; NumberFormatInfo nfi = CultureInfo.CurrentCulture.NumberFormat; // Set locale separator character asciiSettings.DecimalSeparatorCharacter = nfi.NumberDecimalSeparator.ToCharArray()[0]; // Show import splash window asciiSettings.WaitingSplash.RunWorkerAsync(); // Give some time to show the splash ... Application.DoEvents(); // Generate the import tables GenerateSubjectTrialRawdataList(); // Save the import into ogamas database and the mdf file. var successful = SaveImportIntoTablesAndDB(); // Import has finished. asciiSettings.WaitingSplash.CancelAsync(); // Inform user about success. if (successful) { ExceptionMethods.ProcessMessage("Success", "Import data successfully written to database."); } else { string message = "Import had errors. Some or all of the import data " + "could not be written the database."; ExceptionMethods.ProcessErrorMessage(message); } } } catch (Exception ex) { string message = "Something failed during import." + Environment.NewLine + "Please try again with other settings. " + Environment.NewLine + "Error: " + ex.Message; ExceptionMethods.ProcessErrorMessage(message); if (asciiSettings.WaitingSplash.IsBusy) { asciiSettings.WaitingSplash.CancelAsync(); } } }
public static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Support for command line arguments. string fileName = string.Empty; if (args.Length == 1) { if (File.Exists(args[0])) { fileName = args[0]; } } try { // Show splash screen with copyright InitialSplash objfrmSplash = new InitialSplash(); objfrmSplash.ShowDialog(); // Start Application Application.Run(new Ogama.MainWindow.MainForm(fileName)); } catch (Exception ex) { ExceptionMethods.ProcessUnhandledException(ex); } }
/// <summary> /// Start tracking. /// </summary> public override void Record() { try { if (this.memNetworkManager.AllConnected) { if (!this.memIsRecording) { this.memIsRecording = true; //this.memTimeOfRecordingStart.Reset(); //this.memTimeOfRecordingStart.Start(); this.memNetworkManager.SendMessage("<SET ID=\"ENABLE_SEND_TIME_TICK\" STATE=\"1\"/> \r\n"); this.memNetworkManager.SendMessage("<SET ID=\"ENABLE_SEND_POG_BEST\" STATE=\"1\"/> \r\n"); this.memNetworkManager.SendMessage("<SET ID=\"ENABLE_SEND_PUPIL_LEFT\" STATE=\"1\"/> \r\n"); this.memNetworkManager.SendMessage("<SET ID=\"ENABLE_SEND_PUPIL_RIGHT\" STATE=\"1\"/> \r\n"); this.memNetworkManager.SendMessage("<SET ID=\"ENABLE_SEND_DATA\" STATE=\"1\" /> \r\n"); } } } catch (Exception e) { string message = "Exception catched in Record(...) Method : " + Environment.NewLine + e.Message; ExceptionMethods.ProcessErrorMessage(message); MessageBox.Show("Failed to Record. Got exception " + e, "Record Failed", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// The <see cref="BackgroundWorker.RunWorkerCompleted"/> event handler for the /// <see cref="BackgroundWorker"/> <see cref="bgwCalcMap"/>. /// This event handler deals with the results of the /// background operation and updates the UI. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">A <see cref="RunWorkerCompletedEventArgs"/> with the event data.</param> private void bgwCalcMap_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // First, handle the case where an exception was thrown. if (e.Error != null) { ExceptionMethods.HandleException(e.Error); } else if (e.Cancelled) { ((MainForm)this.MdiParent).StatusLabel.Text = "Status: Attentionmap calculation cancelled."; } else { // Finally, handle the case where the operation succeeded. ((MainForm)this.MdiParent).StatusLabel.Text = "Ready"; } ((MainForm)this.MdiParent).StatusProgressbar.Value = 0; // Enable the Start button. this.btnStartCalculation.Enabled = true; // Redraw Image this.Refresh(); }
public ELFFile(File file) { theFile = file; if (theFile == null) { Console.Default.ErrorColour(); Console.Default.Write("Error constructing ELF file! theFile is null"); BasicConsole.Write("Error constructing ELF file! theFile is null"); if (file == null) { Console.Default.Write(" and file is null"); BasicConsole.Write(" and file is null"); } else { Console.Default.Write(" and file is NOT null"); BasicConsole.Write(" and file is NOT null"); } Console.Default.WriteLine("."); BasicConsole.WriteLine("."); Console.Default.DefaultColour(); ExceptionMethods.Throw(new FOS_System.Exception("Error loading ELF file! Supplied file is null.")); } theStream = new CachedFileStream(theFile.GetStream()); ReadHeader(); if (IsValidFile()) { ReadSectionHeaders(); ReadSegmentHeaders(); } }
/// <summary> /// Waits for a pipe to connect to the outpoint. /// </summary> /// <returns>The Id of the newly connected pipe.</returns> public int WaitForConnect() { int aPipeId; SystemCallResults SysCallResult = SystemCalls.WaitOnPipeCreate(Class, Subclass, out aPipeId); switch (SysCallResult) { case SystemCallResults.Unhandled: //BasicConsole.WriteLine("BasicOutPipe > WaitOnPipeCreate: Unhandled!"); ExceptionMethods.Throw(new FOS_System.Exceptions.ArgumentException("BasicOutPipe : Wait On Pipe Create unhandled!")); break; case SystemCallResults.Fail: //BasicConsole.WriteLine("BasicOutPipe > WaitOnPipeCreate: Failed!"); ExceptionMethods.Throw(new FOS_System.Exceptions.ArgumentException("BasicOutPipe : Wait On Pipe Create failed!")); break; case SystemCallResults.OK: //BasicConsole.WriteLine("BasicOutPipe > WaitOnPipeCreate: Succeeded."); //BasicConsole.Write("BasicOutPipe > New pipe id: "); //BasicConsole.WriteLine(aPipeId); break; default: //BasicConsole.WriteLine("BasicOutPipe > WaitOnPipeCreate: Unexpected system call result!"); ExceptionMethods.Throw(new FOS_System.Exceptions.ArgumentException("BasicOutPipe : Wait On Pipe Create unexpected result!")); break; } return(aPipeId); }
/// <summary> /// This method shows the child nodes of the given <see cref="TreeNode"/> /// in the <see cref="ListView"/>, if it is itself a child node without childs /// its parent child collection is shown instead. /// </summary> /// <param name="node">The <see cref="TreeNode"/> thats child /// collection is to be shown in the <see cref="TreeView"/>.</param> private void UpdateListView(TreeNode node) { if (node == null) { return; } try { this.InitializeDetailListView(); if (node.FirstNode != null) { this.lsvDetails.SetObjects(node.Nodes); } else if (node.Parent != null) { this.lsvDetails.SetObjects(node.Parent.Nodes); this.lsvDetails.EnsureVisible(node.Index); } else if (node.Level == 0) { this.lsvDetails.ClearObjects(); } this.SelectedNode = node; } catch (Exception ex) { ExceptionMethods.HandleException(ex); } }
/// <summary> /// Creates and registers a new outpoint of the specified class and subclass. /// </summary> /// <param name="aClass">The class of pipe allowed to connect to the outpoint.</param> /// <param name="aSubclass">The subclass of pipe allowed to connect to the outpoint.</param> /// <param name="MaxConnections"> /// The maximum number of connections allowed. Use <see cref="PipeConstants.UnlimitedConnections"/> for unlimited connections. /// </param> public BasicOutpoint(PipeClasses aClass, PipeSubclasses aSubclass, int MaxConnections) { Class = aClass; Subclass = aSubclass; SystemCallResults SysCallResult = SystemCalls.RegisterPipeOutpoint(Class, Subclass, MaxConnections); switch (SysCallResult) { case SystemCallResults.Unhandled: //BasicConsole.WriteLine("BasicOutPipe > RegisterPipeOutpoint: Unhandled!"); ExceptionMethods.Throw(new FOS_System.Exceptions.ArgumentException("BasicOutPipe : Register Pipe Outpoint system call unhandled!")); break; case SystemCallResults.Fail: //BasicConsole.WriteLine("BasicOutPipe > RegisterPipeOutpoint: Failed!"); ExceptionMethods.Throw(new FOS_System.Exceptions.ArgumentException("BasicOutPipe : Register Pipe Outpoint system call failed!")); break; case SystemCallResults.OK: //BasicConsole.WriteLine("BasicOutPipe > RegisterPipeOutpoint: Succeeded."); break; default: //BasicConsole.WriteLine("BasicOutPipe > RegisterPipeOutpoint: Unexpected system call result!"); ExceptionMethods.Throw(new FOS_System.Exceptions.ArgumentException("BasicOutPipe : Register Pipe Outpoint system call unexpected result!")); break; } }
/// <summary> /// Start collecting gaze samples for current calibration point. /// </summary> /// <param name="collectionId">Current ID.</param> /// <param name="screenPoint">The actual screen target.</param> private void CollectSamples(int collectionId, Point2D screenPoint) { this.goToNextPointTimer.Stop(); this.state = CalibrationState.CollectingSamples; var x = screenPoint.X * PresentationScreen.GetPresentationResolution().Width; var y = screenPoint.Y * PresentationScreen.GetPresentationResolution().Height; try { this.client.RpcClient.StartCollectSamplesObject(collectionId, this.screenName, x, y, 0, this.calibTime * 2); } catch (Exception ex) { if (this.settings.SilentMode) { ExceptionMethods.HandleExceptionSilent(ex); } else { ExceptionMethods.HandleException(ex); this.HasShownMessage = true; } this.AbortCalibration(); return; } this.collectSamplesStopwatch = new Stopwatch(); this.collectSamplesStopwatch.Start(); this.collectSamplesTimer.Start(); }
/// <summary> /// The <see cref="ToolStripComboBox.SelectedIndexChanged"/> event handler for the /// <see cref="ToolStripComboBox"/> <see cref="cmuCountCombo"/>. /// Indicates the number of items in the child nodes collection /// that should be used during presentation of the shuffled collection. /// </summary> /// <remarks>Use this to reduce the stimuli that are shown during presentation /// to a limited number of shuffled items of the child collection.</remarks> /// <param name="sender">Source of the event.</param> /// <param name="e">An empty <see cref="EventArgs"/>.</param> private void cmuCountCombo_SelectedIndexChanged(object sender, EventArgs e) { NodesCollection selectedNodes = this.trvSlideshow.SelectedNodes; if (selectedNodes.Count != 1) { return; } SlideshowTreeNode node = this.trvSlideshow.SelectedNodes[0] as SlideshowTreeNode; if (node != null) { if (node.Slide == null) { if (this.cmuCountCombo.SelectedItem.ToString() == "All") { node.NumberOfItemsToUse = node.Nodes.Count; } else { node.NumberOfItemsToUse = (int)this.cmuCountCombo.SelectedItem; } } else { ExceptionMethods.ProcessMessage( "Please note:", "You cannot change subitem range for single slides, please select the parent node"); } } this.trvSlideshow.Invalidate(); this.lsvDetails.Invalidate(); }
public UInt64 this[UInt64 key] { get { KeyValuePair *cPair = list; while (cPair != null) { if (cPair->Key == key) { return(cPair->Value); } cPair = cPair->Prev; } ExceptionMethods.Throw(new Exceptions.ArgumentException("Key not found in dictionary!")); return(0); } set { KeyValuePair *cPair = list; while (cPair != null) { if (cPair->Key == key) { cPair->Value = value; break; } cPair = cPair->Prev; } if (cPair == null) { Add(key, value); } } }
/////////////////////////////////////////////////////////////////////////////// // Methods for doing main class job // /////////////////////////////////////////////////////////////////////////////// #region PRIVATEMETHODS /// <summary> /// Saves current list of slides into the experiment settings xml file. /// Also calculates slide bitmaps for all modified slides and copies /// them into the slides folders. /// </summary> /// <param name="silent"><strong>True</strong>, if it should be saved /// without a question.</param> private void SaveToExperimentSettings(bool silent) { if (Document.ActiveDocument != null && Document.ActiveDocument.ExperimentSettings != null) { if (Document.ActiveDocument.ExperimentSettings.SlideShow.IsModified) { bool doIt = true; if (!silent) { doIt = MessageBox.Show( "The slideshow has changed, would you like to store it to the experiments file ?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes; } if (doIt) { this.Cursor = Cursors.WaitCursor; Document.ActiveDocument.ExperimentSettings.SlideShow = this.slideshow; ((MainForm)this.MdiParent).StatusLabel.Text = "Saving slideshow to file ..."; if (!Document.ActiveDocument.SaveSettingsToFile(Document.ActiveDocument.ExperimentSettings.DocumentFilename)) { ExceptionMethods.ProcessErrorMessage("Couldn't save slideshow to experiment settings."); } } } } }
/////////////////////////////////////////////////////////////////////////////// // Construction and Initializing methods // /////////////////////////////////////////////////////////////////////////////// #region CONSTRUCTION /// <summary> /// Initializes a new instance of the MainForm class. /// </summary> /// <param name="fileName">A <see cref="string"/> with an optional filename /// from the command line to load.</param> public MainForm(string fileName) { if (fileName == string.Empty) { this.loadFileFromCommandLine = false; } else { this.loadFileFromCommandLine = true; this.commandLineFileName = fileName; } this.InitializeComponent(); this.InitAccelerators(); try { TobiiTracker.StaticInitialize(); } catch (Exception ex) { ExceptionMethods.ProcessErrorMessage( "The tobii SDK could not be initialized, the tobii record interface will not be" + "available. Please install apple bonjour, if this is a module load error." + ex.Message); } }
public override int Read(byte[] buffer, int offset, int count) { int maxToRead = FOS_System.Math.Min(count, CachedData.Length - (int)Position); if (count < 0) { ExceptionMethods.Throw(new Exceptions.ArgumentException("CachedFileStream.Read: count must be > 0")); } else if (offset < 0) { ExceptionMethods.Throw(new Exceptions.ArgumentException("CachedFileStream.Read: offset must be > 0")); } else if (buffer == null) { ExceptionMethods.Throw(new Exceptions.ArgumentException("CachedFileStream.Read: buffer must not be null!")); } else if (buffer.Length - offset < count) { ExceptionMethods.Throw(new Exceptions.ArgumentException("CachedFileStream.Read: Invalid offset / length values!")); } FOS_System.Array.Copy(CachedData, (int)Position, buffer, offset, maxToRead); return(maxToRead); }
public virtual void Reset() { IO.Control.Write_Byte(0x4); Wait(); IO.Control.Write_Byte(0x0); Status xStatus; int timeout = 20000000; do { Wait(); xStatus = (Status)IO.Control.Read_Byte(); } while ((xStatus & Status.Busy) != 0 && (xStatus & Status.Error) == 0 && timeout-- > 0); // Error occurred if ((xStatus & Status.Error) != 0) { ExceptionMethods.Throw(new FOS_System.Exception("ATA software reset error!")); } else if (timeout == 0) { ExceptionMethods.Throw(new FOS_System.Exception("ATA software reset timeout!")); } //Reselect the correct drive SelectDrive(0, false); }
public override void Write(byte[] buffer, int offset, int count) { if (count < 0) { ExceptionMethods.Throw(new Exceptions.ArgumentException("CachedFileStream.Write: count must be > 0")); } else if (offset < 0) { ExceptionMethods.Throw(new Exceptions.ArgumentException("CachedFileStream.Write: offset must be > 0")); } else if (buffer == null) { ExceptionMethods.Throw(new Exceptions.ArgumentException("CachedFileStream.Write: buffer must not be null!")); } else if (buffer.Length - offset < count) { ExceptionMethods.Throw(new Exceptions.ArgumentException("CachedFileStream.Write: Invalid offset / length values!")); } if (CachedData.Length < ((int)Position + count)) { byte[] NewCachedData = new byte[offset + count]; FOS_System.Array.Copy(CachedData, 0, NewCachedData, 0, CachedData.Length); CachedData = NewCachedData; } FOS_System.Array.Copy(buffer, offset, CachedData, (int)Position, count); UnderlyingStream.Write(buffer, offset, count); }
/// <summary> /// Process received message from server. /// This method is called when a asynchronous waiting for data from server(s) completes /// </summary> /// <param name="callbackResults">Additional data received from the caller</param> private void OnDataReceived(IAsyncResult callbackResults) { Connections serverConnection = (Connections)callbackResults.AsyncState; try { if (serverConnection.ConnectionStream == null || !serverConnection.ConnectionStream.CanRead) { return; } int readBytes = serverConnection.ConnectionStream.EndRead(callbackResults); string stringFromBytes = System.Text.Encoding.ASCII.GetString(serverConnection.BytesArrayQueue.First(), 0, serverConnection.BytesArrayQueue.First().Length); // We remove received bytes when they are processed serverConnection.BytesArrayQueue.Dequeue(); // Warn GazepointTracker class about incoming message this.MessageReceived(new StringEventArgs(stringFromBytes)); this.WaitForData(serverConnection); } catch (Exception e) { string message = "Exception catched in OnDataReceived(...) Method : " + Environment.NewLine + e.Message; ExceptionMethods.ProcessErrorMessage(message); } }
/// <summary> /// This method checks for assigning of all minimum relevant columns, /// and returns false if some are missing. /// </summary> /// <returns> /// <strong>True</strong> if successful, otherwise /// <strong>false</strong>. /// </returns> private bool ValidateAssignments() { // Check for missing time column. if (ImportFixations.ASCIISettings.ColumnAssignments["StartTime"] == null || ImportFixations.ASCIISettings.ColumnAssignments["StartTime"] == string.Empty || ImportFixations.ASCIISettings.ColumnAssignments["PosX"] == null || ImportFixations.ASCIISettings.ColumnAssignments["PosX"] == string.Empty || ImportFixations.ASCIISettings.ColumnAssignments["PosY"] == null || ImportFixations.ASCIISettings.ColumnAssignments["PosY"] == string.Empty) { string message = "You have to define at least the trial id, start time, posx and posY columns ..."; ExceptionMethods.ProcessMessage("Define columns", message); return(false); } // If no subject column is specified show subject name dialog. if (ImportFixations.ASCIISettings.ColumnAssignments["SubjectName"] == null || ImportFixations.ASCIISettings.ColumnAssignments["SubjectName"] == string.Empty) { var dlg = new AskForSubjectNameDialog(true); dlg.SubjectName = ImportFixations.DetectionSetting.SubjectName; if (dlg.ShowDialog() == DialogResult.OK) { ImportFixations.DetectionSetting.SubjectName = dlg.SubjectName; } else { return(false); } } return(true); }
/// <summary> /// This is the callback method to receive the samples from the udp stream. /// </summary> private void StartListen() { // IPEndPoint object will allow us to read datagrams sent from any source. IPEndPoint remoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); while (!this.stopListenThread) { if (this.udpClient.Client == null) { break; } try { // Blocks until a message returns on this socket from a remote host. byte[] receiveBytes = this.udpClient.Receive(ref remoteIpEndPoint); string returnData = Encoding.ASCII.GetString(receiveBytes); if (returnData.Length > 0) { this.NewBytesReceived(returnData); } } catch (Exception ex) { ExceptionMethods.HandleExceptionSilent(ex); } } }
/// <summary> /// <see cref="Control.Click"/> event handler /// for the <see cref="btnBackgroundImage"/> <see cref="Button"/>. /// Opens the <see cref="ofdBackgroundImage"/> <see cref="OpenFileDialog"/> /// to ask for the background image file, then updates slide and preview /// with the new background image. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">An empty <see cref="EventArgs"/></param> private void btnBackgroundImage_Click(object sender, EventArgs e) { if (this.ofdBackgroundImage.ShowDialog() == DialogResult.OK) { if (File.Exists(this.ofdBackgroundImage.FileName)) { using (FileStream fs = File.OpenRead(this.ofdBackgroundImage.FileName)) { Image original = Image.FromStream(fs); this.designPicture.BackgroundImage = new Bitmap(original); } } else { this.designPicture.BackgroundImage = null; string message = "Background image file: " + Environment.NewLine + this.ofdBackgroundImage.FileName + Environment.NewLine + " could not be found"; ExceptionMethods.ProcessMessage("File not found", message); } } this.designPicture.Invalidate(); }
/////////////////////////////////////////////////////////////////////////////// // Public methods // /////////////////////////////////////////////////////////////////////////////// #region PUBLICMETHODS /// <summary> /// Create the Smart Eye RPC client. /// </summary> public void CreateRPC() { this.IsClosingDown = false; this.IsCalibrating = false; if (this.RpcClient != null) { try { this.RpcClient.Disconnect(); } catch (Exception ex) { if (this.smartEyeSettings.SilentMode) { ExceptionMethods.HandleExceptionSilent(ex); } else { ExceptionMethods.HandleException(ex); } } } this.RpcIsConnected = false; this.RpcClient = new JsonRpcClient(); this.ConnectRPC(); }
/// <summary> /// Reads up to the specified length of data into the specified buffer at the specified offset in the buffer. /// </summary> /// <param name="Data">The buffer to read into.</param> /// <param name="Offset">The offset in the buffer to write data to.</param> /// <param name="Length">The maximum length of data to read.</param> /// <param name="Blocking">Whether the read should be blocking or non-blocking.</param> /// <returns>The actual number of bytes read.</returns> public int Read(byte[] Data, int Offset, int Length, bool Blocking) { int BytesRead = 0; Pipes.ReadPipeRequest *ReadPipeRequestPtr = (Pipes.ReadPipeRequest *)Heap.AllocZeroed((uint)sizeof(Pipes.ReadPipeRequest), "BasicInPipe : Alloc ReadPipeRequest"); try { if (ReadPipeRequestPtr != null) { ReadPipeRequestPtr->PipeId = PipeId; ReadPipeRequestPtr->Offset = Offset; ReadPipeRequestPtr->Length = FOS_System.Math.Min(Data.Length - Offset, Length); ReadPipeRequestPtr->OutBuffer = (byte *)Utilities.ObjectUtilities.GetHandle(Data) + FOS_System.Array.FieldsBytesSize; ReadPipeRequestPtr->Blocking = Blocking; SystemCallResults SysCallResult = SystemCalls.ReadPipe(ReadPipeRequestPtr, out BytesRead); switch (SysCallResult) { case SystemCallResults.Unhandled: //BasicConsole.WriteLine("BasicInPipe > ReadPipe: Unhandled!"); ExceptionMethods.Throw(new Exceptions.RWUnhandledException("BasicInPipe : Read Pipe unexpected unhandled!")); break; case SystemCallResults.Fail: //BasicConsole.WriteLine("BasicInPipe > ReadPipe: Failed!"); if (Blocking) { ExceptionMethods.Throw(new Exceptions.RWFailedException("BasicInPipe : Write Pipe unexpected failed! (Blocking call)")); } else { ExceptionMethods.Throw(new Exceptions.RWFailedException("BasicInPipe : Write Pipe failed. (Non-blocking call)")); } break; case SystemCallResults.OK: //BasicConsole.WriteLine("BasicInPipe > ReadPipe: Succeeded."); break; default: //BasicConsole.WriteLine("BasicInPipe > ReadPipe: Unexpected system call result!"); ExceptionMethods.Throw(new Exceptions.RWUnhandledException("BasicInPipe : Read Pipe unexpected result!")); break; } } else { ExceptionMethods.Throw(new FOS_System.Exceptions.ArgumentException("BasicInPipe : Couldn't allocate memory to read from pipe!")); } } finally { if (ReadPipeRequestPtr != null) { Heap.Free(ReadPipeRequestPtr); } } return(BytesRead); }
/// <summary> /// Dispose the SmartEyeClient. /// </summary> public void Dispose() { this.IsClosingDown = true; if (this.RpcClient != null) { try { this.RpcClient.Shutdown(); } catch (Exception ex) { ExceptionMethods.HandleExceptionSilent(ex); this.KillRunningEyeTrackerProcess(); } } else { ExceptionMethods.ProcessMessage("Warning", "Smart Eye Tracker Core could not be shut down."); } this.RpcClient.Dispose(); this.DisconnectUDP(); this.RpcClient = null; this.UdpSocket = null; }
/// <summary> /// <see cref="Control.Click"/> event handler /// for the <see cref="btnSelectFlashMovie"/> <see cref="Button"/> /// Opens file open dialog. /// </summary> /// <param name="sender">Source of the event.</param> /// <param name="e">An empty <see cref="EventArgs"/>.</param> private void btnSelectFlashMovie_Click(object sender, EventArgs e) { if (this.ofdFlashMovie.ShowDialog() == DialogResult.OK) { if (Path.GetFileName(this.ofdFlashMovie.FileName).Contains("#")) { ExceptionMethods.ProcessMessage("Invalid filename", "Please do not use hashes '#' in the filename."); } else { string fileName = this.ofdFlashMovie.FileName; this.txbFlashFilename.Text = fileName; string templatePath = Document.ActiveDocument.ExperimentSettings.SlideResourcesPath; if (Path.GetDirectoryName(fileName) != templatePath) { string target = Path.Combine(templatePath, Path.GetFileName(fileName)); if (!File.Exists(target)) { File.Copy(fileName, target); string message = "A copy of this movie file is saved to the following slide resources folder of the current project :" + Environment.NewLine + target + Environment.NewLine + "This is done because of easy movement of experiments between different computers or locations."; ExceptionMethods.ProcessMessage("File is copied", message); } this.txbFlashFilename.Text = target; } this.designPicture.DrawForeground(true); } } }
public FOS_System.Object Peek() { AccessLock.Enter(); try { if (WriteIdx == -1) { if (ThrowExceptions) { ExceptionMethods.Throw(new Exceptions.OverflowException("Circular buffer cannot Peek because the buffer is empty.")); } return(null); } int tmpReadIdx = ReadIdx; tmpReadIdx++; if (tmpReadIdx == _array.Length) { tmpReadIdx = 0; } return(_array[tmpReadIdx]); } finally { AccessLock.Exit(); } }
/////////////////////////////////////////////////////////////////////////////// // Methods and Eventhandling for Background tasks // /////////////////////////////////////////////////////////////////////////////// #region BACKGROUNDWORKER #endregion //BACKGROUNDWORKER /////////////////////////////////////////////////////////////////////////////// // Methods for doing main class job // /////////////////////////////////////////////////////////////////////////////// #region PRIVATEMETHODS /// <summary> /// Deserializes the <see cref="SMISetting"/> from the given xml file. /// </summary> /// <param name="filePath">Full file path to the xml settings file.</param> /// <returns>A <see cref="SMISetting"/> object.</returns> private SMISetting DeserializeSettings(string filePath) { var settings = new SMISetting(); // Create an instance of the XmlSerializer class; // specify the type of object to be deserialized var serializer = new XmlSerializer(typeof(SMISetting)); // * If the XML document has been altered with unknown // nodes or attributes, handle them with the // UnknownNode and UnknownAttribute events.*/ serializer.UnknownNode += this.SerializerUnknownNode; serializer.UnknownAttribute += this.SerializerUnknownAttribute; try { // A FileStream is needed to read the XML document. var fs = new FileStream(filePath, FileMode.Open); // Use the Deserialize method to restore the object's state with // data from the XML document. settings = (SMISetting)serializer.Deserialize(fs); fs.Close(); } catch (Exception ex) { string message = "Deserialization of SMISettings failed with the following message: " + Environment.NewLine + ex.Message; ExceptionMethods.ProcessErrorMessage(message); } return(settings); }