Language - C Sharp: Difference between revisions

From Phidgets Support
 
(316 intermediate revisions by 10 users not shown)
Line 1: Line 1:
C# is a modern, object-oriented programming language developed by Microsoft.
{{#seo:|description=Learn how to use Phidget USB devices with C#.}}
[[Category:Language]]


==Assessment for use with Phidgets==
==Get Started==
Since C# supports event-driven programming and is object-oriented, it is capable of using all of the functionality Phidgets has to offer.
With the Phidget22.NET library, it's easy to create C# applications that work with Phidget devices.


Due to the popularity of C#, you can also find plenty of other programmers on the C# section of [http://www.phidgets.com/phorum/viewforum.php?f=22 our forums].
==C# Libraries==
==Support==
===Nuget Package===
C# has a complete API and sample code for all Phidgets devices.
The Phidget22.NET library is available as a [https://www.nuget.org/packages/Phidget22.NET/ nuget package]. This is the recommend way to install and manage the Phidget22.NET library.


For a complete list of our supported languages and their support status, [[Levels of Support|click here]].
====macOS Considerations====
Phidget devices running a HID USB stack require the installation of the macOS libraries or the standalone Phidget Control Panel ([{{SERVER}}/docs/OS_-_macOS download here]).


==Restrictions==
To determine what USB stack your Phidget device is on, navigate to the product page and then to the specification tab, and look for the ''USB Stack'' specification. If you are using a VINT device, navigate to the product page for the VINT Hub you are using.
In this section, list any restrictions or limitations that this particular language may impose. For example, incompatibility with certain operating systems.


==Development Environments and Compilers==
[[Image:Javascript_networkserver_webusb_spec.png|center|600px|link=https://cdn.phidgets.com/docs/images/8/80/Javascript_networkserver_webusb_spec.png]]


===Mono===
====Linux Considerations====
Mono is a free, open-source C# compiler. If you want to program with Phidgets using C# on Linux, Mono is your best option.  
Linux restricts access to USB devices to the root user. To run your .NET application as a regular user, you'll need to [{{SERVER}}/docs/OS_-_Linux#Setting_udev_Rules set up udev rules] on your system.


You can visit Mono's website [http://www.mono-project.com/Main_Page here].
===Library Files===
If you would like to manually manage the Phidget22.NET library files, you can download them [https://cdn.phidgets.com/downloads/phidget22/libraries/windows/Phidget22-windevel.zip here].


===Visual Studio 2003===
==Development Environment Configuration==
Visual Studio 2003 requires our .NET 1.1 libraries. Make sure you download the latest version of our [http://www.phidgets.com/drivers.php drivers] and add a reference in your project to Phidget21.NET version 1.1.
===Visual Studio===
{| style="margin:auto;" class="table-no-border mw-collapsible mw-collapsed"
|+ '''Instructions'''
| Create your Visual Studio project, and navigate to the '''Solution Explorer'''. From there, right-click on '''Dependencies''' and select '''Manage NuGet Packages...'''|| [[Image:Language_csharp_vs_managenuget.png|center|350px|link=https://cdn.phidgets.com/docs/images/c/cc/Language_csharp_vs_managenuget.png]]
|-
| Next, click '''Browse''' and enter '''Phidget22.NET''' in the search bar. || [[Image:Language_csharp_vs_browsenuget.png|center|350px|link=https://cdn.phidgets.com/docs/images/6/61/Language_csharp_vs_browsenuget.png]]
|-
| Click on the package and press the '''Install''' button. || [[Image:Language_csharp_vs_installnuget.png|center|350px|link=https://cdn.phidgets.com/docs/images/b/b8/Language_csharp_vs_installnuget.png]]
|-
| Finally, add your C# code and run it using the button at the top of the screen. || [[Image:Language_csharp_vs_run.png|center|350px|link=https://cdn.phidgets.com/docs/images/5/5a/Language_csharp_vs_run.png]]
|-
|}


Our code samples were designed for use with Visual Studio 2005 or 2008. You can try to build a new project in Visual Studio 2003 using the source code we provide, but we cannot guarantee that it will work.  
===Visual Studio Code===
{| style="margin:auto;" class="table-no-border mw-collapsible mw-collapsed"
|+ '''Instructions'''
| Install the [https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csdevkit C# Dev Kit extension for Visual Studio Code].|| [[Image:Language_csharp_vscode_installext.png|center|350px|link=https://cdn.phidgets.com/docs/images/b/b8/Language_csharp_vscode_installext.png]]
|-
| Next, create a directory and open it in Visual Studio Code. You can do this by opening Visual Studio Code and selecting '''File > Open Folder...''' || [[Image:Language_csharp_vscode_newfolder.png|center|350px|link=https://cdn.phidgets.com/docs/images/4/43/Language_csharp_vscode_newfolder.png]]
|-
| Open the Command Palette (Ctrl + Shift + P), type '''.NET: New Project''', and press Enter. A list of supported project types will appear. || [[Image:Language_csharp_vscode_netnewproject.png|center|350px|link=https://cdn.phidgets.com/docs/images/f/f7/Language_csharp_vscode_netnewproject.png]]
|-
| Select your preferred project type from the list. For this example, we will select '''Console App'''. || [[Image:Language_csharp_vscode_netconsoleapp.png|center|350px|link=https://cdn.phidgets.com/docs/images/b/bc/Language_csharp_vscode_netconsoleapp.png]]
|-
| Next, we need to add the Phidget22.NET library using NuGet. Open the Command Palette again (Ctrl + Shift + P), and enter '''NuGet: Add NuGet package...'''.
|| [[Image:Language_csharp_vscode_addnugetpackage.png|center|350px|link=https://cdn.phidgets.com/docs/images/2/26/Language_csharp_vscode_addnugetpackage.png]]
|-
| When prompted, enter '''Phidget22.NET''' and install the latest package.<br><br>'''Note''': Ensure you are downloading the latest version which can be seen [{{SERVER}}/?view=changelog here]. Visual Studio Code may incorrectly show an older version as the ''latest'' by default.|| [[Image:Language_csharp_vscode_phidget22net.png|center|350px|link=https://cdn.phidgets.com/docs/images/d/d5/Language_csharp_vscode_phidget22net.png]]
|-
|-
| Finally, add your C# code and run it using the button at the top of the screen. || [[Image:Language_csharp_vscode_runcodepng.png|center|350px|link=https://cdn.phidgets.com/docs/images/d/dc/Language_csharp_vscode_runcodepng.png]]
|-
|}


===Visual Studio 2005===
===.NET Command-Line Interface (CLI)===
Visual Studio 2005 requires our .NET 2.0 libraries. Make sure you download the latest version of our [http://www.phidgets.com/drivers.php drivers] and add a reference in your project to Phidget21.NET version 2.0.
{| style="margin:auto;" class="table-no-border mw-collapsible mw-collapsed"
|+ '''Instructions'''
| Download and install the latest version of.NET from [https://dotnet.microsoft.com/en-us/download/dotnet Microsoft's .NET download page].|| [[Image:Language_csharp_cli_download.png|center|350px|link=https://cdn.phidgets.com/docs/images/9/90/Language_csharp_cli_download.png]]
|-
| Next, open a command prompt or terminal in a new folder and enter the following command:


<syntaxhighlight lang=bash>
dotnet new console
</syntaxhighlight>


|| [[Image:Language_csharp_cli_newconsole.png|center|350px|link=https://cdn.phidgets.com/docs/images/3/3a/Language_csharp_cli_newconsole.png]]
|-
| This previous command will create a new console application at the folder location. || [[Image:Language_csharp_cli_newproject.png|center|350px|link=https://cdn.phidgets.com/docs/images/c/cb/Language_csharp_cli_newproject.png]]
|-
| Navigate back to the command prompt or terminal, and add the Phidget22.NET package with the following command:


===Visual Studio 2008===
<syntaxhighlight lang=bash>
===Visual Studio 2010===
dotnet add package Phidget22.NET
</syntaxhighlight>


==Drivers, Libraries and Resources==
|| [[Image:Language_csharp_cli_addpackage.png|center|350px|link=https://cdn.phidgets.com/docs/images/7/78/Language_csharp_cli_addpackage.png]]
Before you can run your program, you need to set up the proper environment and get the necessary files off the Phidgets website.
|-
Visit the drivers section at www.phidgets.com and get the latest:
| You can now open the '''Program.cs''' file and add your code. Run the program by entering the following command into your command prompt or terminal:
* [http://www.phidgets.com/drivers.php Phidget Framework]
You will need the Phidget Framework to use and to program with Phidgets. We also recommend that you download the following reference materials:
* [http://www.phidgets.com/documentation/Phidget21.NET.zip .NET API Manual]
* [http://www.phidgets.com/documentation/web/NETDoc/Index.html .NET API Reference].
The .NET API manual lists calls and events for every type of Phidget and can be used as a reference.
* Example Programs written in C# [[http://www.phidgets.com/downloads/examples/CSharp_2.1.8.20110615.zip Windows]] [[http://www.phidgets.com/downloads/examples/CE_2.1.8.20110615.zip .NET Compact Framework]]
* You can find a high level discussion about programming with Phidgets in general on the [[General API]] page.  
* The [[Device Functionality]] page explains the general operational information for your device.


You may want to have these pages open while working through these instructions.
<syntaxhighlight lang=bash>
dotnet run
</syntaxhighlight>


==Getting Started==
|| [[Image:Language_csharp_cli_runcode.png|center|350px|link=https://cdn.phidgets.com/docs/images/f/f3/Language_csharp_cli_runcode.png]]
|-
|}


===Setting up a Phidgets Project===
==Example Code==
The Phidget examples were written using Visual C# 2005 and this tutorial assumes its use. Newer
Navigate to our [https://www.phidgets.com/?view=code_samples&lang=CSharp Code Sample Generator] to view and download code samples that are tailored to your specific device.
versions of Visual Studio Express are freely available for download from Microsoft. Older versions of
Visual Studio work as well and would be set up in a similar manner (Note: you would have to recreate
the user interface in the examples for Visual Studio versions earlier than 2005). In Visual Studio:
* Generate a new C# Windows Application with a descriptive name such as PhidgetTest.  
* Launch the Add Reference window (Project | Add Reference).
* Under the .NET tab, select the most recent Phidget21.NET library. If it does not appear in this list, then you can Browse to the Phidget Framework installation directory and add the Phidget21.NET. dll. For earlier versions of Visual Studio, you will want to use the Phidget21.NET1.1.dll instead.
* Place a TextBox on your main form for the purpose of capturing output.
* Hook the form's Load and FormClosing events. Phidget initialization and shutdown will take place
there.
The project now has access to Phidgets and we are ready to begin coding.


===Coding For Your Phidget===
[[Image:Language_csharp_codesample.png|center|600px|link=https://cdn.phidgets.com/docs/images/0/03/Language_csharp_codesample.png]]
Before you can use the Phidget, you must include a reference in the code to the libraries. Launch the
code editor for your form and add this to your using statements:Getting_Started_CSharp created: 11/10/10 Page 2
using Phidgets;
using Phidgets.Events;
Afterwards, a Phidget object will need to be declared and then initialized. For example, we can
declare a PhidgetInterfaceKit inside our form with:


<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
===Phidget Programming Basics===
<font size="3">
{{PhidgetProgrammingBasicsLink}}
<source lang=CSharp>


    namespace PhidgetTest
==API==
    {
[{{SERVER}}/?view=api&lang=CSharp Phidget22 API]
        public partial class Form1 : Form
        {
            //The Phidget object declaration
            private InterfaceKit ifKit;
            public Form1()
            {
                InitializeComponent();
            }
            //... Form1_Load and Form1_OnClosing here
        }
    }
</source>
</font>
</div>
 
 
The object name for any type of Phidget is listed in the API manual. Every type of Phidget also
inherits functionality from the Phidget base class.
 
===Connecting to the Phidget===
 
Next, the program needs to try and connect to the Phidget through a call to open(). Open will tell the
program to continuously try to connect to a Phidget, based on the parameters given, even trying to
reconnect if it gets disconnected. This means that simply calling open does not guarantee you can
use the Phidget immediately. We can handle this by using event driven programming and tracking
the AttachEvents and DetachEvents, or by calling waitForAttachment. WaitForAttachment will block
indefinitely until a connection is made to the Phidget, or an optional timeout is exceeded.
 
<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<font size="3">
<source lang=CSharp>
   
private void Form1_Load(object sender, EventArgs e)
{
    ifKit = new InterfaceKit();
    ifKit.open();
    ifKit.waitForAttachment(3000);
}
</source>
</font>
</div>
The different types of open can be used with parameters to try and get the first device it can find,
open based on its serial number, or even open across the network. The API manual lists all of the
available modes that open provides. One important thing to remember is that when working with
Phidgets, a local connection will reserve the device until closed. This prevents any other instances
from retrieving data from the Phidget, including other programs. The one connection per device limit
does not apply when exclusively using the Phidget Webservice.
 
===Event Driven Programming===
 
We recommend the use of event driven programming when working with Phidgets. In C# we can
hook an event handler at loading with the following code:
<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<font size="3">
<source lang=CSharp>
 
ifKit.SensorChange += new SensorChangeEventHandler(ifKit_SensorChange);
 
</source>
</font>
</div>
 
The ifKit_SensorChange method is defined as follows:
 
<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<font size="3">
<source lang=CSharp>
 
        void ifKit_SensorChange(object sender, SensorChangeEventArgs e)
        {
            textBox1.Text = "Index " + e.Index + " Value: " + e.Value;
        }
 
</source>
</font>
</div>
 
With this function, the code inside ifKit_SensorChange will get executed every time the
PhidgetInterfaceKit reports a change on one of its analog inputs. Some events such as Attach and
Detach belong to the base Phidget object and thus are common to all types of Phidgets. Please refer
to the API manual for a full list of events and their usage.
At the end of your program, unhook any events and call Application.DoEvents(). This will make sure
there are no outstanding events being processed before calling close.
 
<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
<font size="3">
<source lang=CSharp>
 
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            ifKit.SensorChange -= new SensorChangeEventHandler(ifKit_SensorChange);
            //run any events in the message queue
            Application.DoEvents();
            ifKit.close();
        }
 
</source>
</font>
</div>
Working directly with the Phidget
Some values can be read and sent directly to the Phidget, simply use the instance members and
properties. This is also how you would set properties on the Phidget such as the output state or
sensor sensitivity. These functions can be used inside a polling loop as an alternative to event driven
programming.
int val = ifKit.sensors[0].Value;
 
===Working with multiple Phidgets===
 
Multiple Phidgets of the same type can easily be run inside the same program. In our case, it 
requires another PhidgetInterfaceKit instance to be defined and initialized. The new instance can then
be set up, opened and used in the same process as the previous one.
If the application needs to distinguish between the devices, open can be called with the serial
number of a specific Phidget.
 
===Other Phidgets===
 
The design given in this document can also be followed for almost all Phidgets. For example, if
you were using a PhidgetRFID instead of an PhidgetInterfacekit, you would declare an RFID object
instead of an InterfaceKit. The methods and events available would change but they can be accessed
in a similar manner.
 
<!-- Not sure if this section is even necessary
==Building your Project==
Describe the different ways a project could be built using this language.
-->
==Common Problems and Solutions/Workarounds==
 
There are no known issues specific to C# at this time.

Latest revision as of 19:47, 13 June 2025


Get Started

With the Phidget22.NET library, it's easy to create C# applications that work with Phidget devices.

C# Libraries

Nuget Package

The Phidget22.NET library is available as a nuget package. This is the recommend way to install and manage the Phidget22.NET library.

macOS Considerations

Phidget devices running a HID USB stack require the installation of the macOS libraries or the standalone Phidget Control Panel (download here).

To determine what USB stack your Phidget device is on, navigate to the product page and then to the specification tab, and look for the USB Stack specification. If you are using a VINT device, navigate to the product page for the VINT Hub you are using.

Javascript networkserver webusb spec.png

Linux Considerations

Linux restricts access to USB devices to the root user. To run your .NET application as a regular user, you'll need to set up udev rules on your system.

Library Files

If you would like to manually manage the Phidget22.NET library files, you can download them here.

Development Environment Configuration

Visual Studio

Instructions
Create your Visual Studio project, and navigate to the Solution Explorer. From there, right-click on Dependencies and select Manage NuGet Packages...
Language csharp vs managenuget.png
Next, click Browse and enter Phidget22.NET in the search bar.
Language csharp vs browsenuget.png
Click on the package and press the Install button.
Language csharp vs installnuget.png
Finally, add your C# code and run it using the button at the top of the screen.
Language csharp vs run.png

Visual Studio Code

Instructions
Install the C# Dev Kit extension for Visual Studio Code.
Language csharp vscode installext.png
Next, create a directory and open it in Visual Studio Code. You can do this by opening Visual Studio Code and selecting File > Open Folder...
Language csharp vscode newfolder.png
Open the Command Palette (Ctrl + Shift + P), type .NET: New Project, and press Enter. A list of supported project types will appear.
Language csharp vscode netnewproject.png
Select your preferred project type from the list. For this example, we will select Console App.
Language csharp vscode netconsoleapp.png
Next, we need to add the Phidget22.NET library using NuGet. Open the Command Palette again (Ctrl + Shift + P), and enter NuGet: Add NuGet package....
Language csharp vscode addnugetpackage.png
When prompted, enter Phidget22.NET and install the latest package.

Note: Ensure you are downloading the latest version which can be seen here. Visual Studio Code may incorrectly show an older version as the latest by default.
Language csharp vscode phidget22net.png
Finally, add your C# code and run it using the button at the top of the screen.
Language csharp vscode runcodepng.png

.NET Command-Line Interface (CLI)

Instructions
Download and install the latest version of.NET from Microsoft's .NET download page.
Language csharp cli download.png
Next, open a command prompt or terminal in a new folder and enter the following command:
dotnet new console
Language csharp cli newconsole.png
This previous command will create a new console application at the folder location.
Language csharp cli newproject.png
Navigate back to the command prompt or terminal, and add the Phidget22.NET package with the following command:
dotnet add package Phidget22.NET
Language csharp cli addpackage.png
You can now open the Program.cs file and add your code. Run the program by entering the following command into your command prompt or terminal:
dotnet run
Language csharp cli runcode.png

Example Code

Navigate to our Code Sample Generator to view and download code samples that are tailored to your specific device.

Language csharp codesample.png

Phidget Programming Basics

To learn more about the structure of the example code, visit our Phidget Programming Basics guide.

API

Phidget22 API