Language - C Sharp: Difference between revisions

From Phidgets Support
No edit summary
 
(325 intermediate revisions by 10 users not shown)
Line 1: Line 1:
Preamble about the language and its general strengths and weaknesses.
{{#seo:|description=Learn how to use Phidget USB devices with C#.}}
[[Category:Language]]


==Assessment for use with Phidgets==
==Get Started==
Our honest opinion on how well this language is suited to controlling Phidgets. If it is a poor choice, suggest and link similar (better) languages.
With the Phidget22.NET library, it's easy to create C# applications that work with Phidget devices.


==Support==
==C# Libraries==
C# is a [[Levels of Support|fully supported]] language.
===Nuget Package===
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.


==Restrictions==
====macOS Considerations====
In this section, list any restrictions or limitations that this particular language may impose. For example, incompatibility with certain operating systems.
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]).


==Development Environments and Compilers==
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.


===Visual Studio 2003===
[[Image:Javascript_networkserver_webusb_spec.png|center|600px|link=https://cdn.phidgets.com/docs/images/8/80/Javascript_networkserver_webusb_spec.png]]
Describe each major version and notable differences relating to programming Phidgets.
===Visual Studio 2005===
===Visual Studio 2008===
===Visual Studio 2010===


==Drivers and Libraries==
====Linux Considerations====
Before you can run your program, you need to set up the proper environment and get the necessary files off the Phidgets website.
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.
Visit the drivers section at www.phidgets.com and get the latest:
* [http://www.phidgets.com/drivers.php Phidget Framework]
You will need the Phidget Framework to use 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/Programming_Manual.pdf Programming Manual]
* The Product Manual for your device (link to the "Device Functionality" page)
* 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]]
The .NET API manual lists calls and events for every type of Phidget and can be used as a reference.
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.


==Getting Started==
===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].


===Setting up a Phidgets Project===
==Development Environment Configuration==
The Phidget examples were written using Visual C# 2005 and this tutorial assumes its use. Newer
===Visual Studio===
versions of Visual Studio Express are freely available for download from Microsoft. Older versions of
{| style="margin:auto;" class="table-no-border mw-collapsible mw-collapsed"
Visual Studio work as well and would be set up in a similar manner (Note: you would have to recreate
|+ '''Instructions'''
the user interface in the examples for Visual Studio versions earlier than 2005). In Visual Studio:
| 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]]
* Generate a new C# Windows Application with a descriptive name such as PhidgetTest.  
|-
* Launch the Add Reference window (Project | Add Reference).
| 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]]
* 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.
| 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]]
* Hook the form's Load and FormClosing events. Phidget initialization and shutdown will take place
|-
there.
| 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]]
The project now has access to Phidgets and we are ready to begin coding.
|-
|}


===Coding For Your Phidget===
===Visual Studio Code===
Before you can use the Phidget, you must include a reference in the code to the libraries. Launch the
{| style="margin:auto;" class="table-no-border mw-collapsible mw-collapsed"
code editor for your form and add this to your using statements:Getting_Started_CSharp created: 11/10/10 Page 2
|+ '''Instructions'''
using Phidgets;
| 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]]
using Phidgets.Events;
|-
Afterwards, a Phidget object will need to be declared and then initialized. For example, we can
| 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]]
declare a PhidgetInterfaceKit inside our form with:
|-
| 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]]
|-
|}


<div style="background-color: #f3f3f3; border-color: #1c9edb; border-width:1px; border-style: dashed;">
===.NET Command-Line Interface (CLI)===
<font size="3">
{| style="margin:auto;" class="table-no-border mw-collapsible mw-collapsed"
<source lang=CSharp>
|+ '''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:


    namespace PhidgetTest
<syntaxhighlight lang=bash>
    {
dotnet new console
        public partial class Form1 : Form
</syntaxhighlight>
        {
            //The Phidget object declaration
            private InterfaceKit ifKit;
            public Form1()
            {
                InitializeComponent();
            }
            //... Form1_Load and Form1_OnClosing here
        }
    }
</source>
</font>
</div>


|| [[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:


The object name for any type of Phidget is listed in the API manual. Every type of Phidget also
<syntaxhighlight lang=bash>
inherits functionality from the Phidget base class.
dotnet add package Phidget22.NET
</syntaxhighlight>


===Connecting to the Phidget===
|| [[Image:Language_csharp_cli_addpackage.png|center|350px|link=https://cdn.phidgets.com/docs/images/7/78/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:


Next, the program needs to try and connect to the Phidget through a call to open(). Open will tell the
<syntaxhighlight lang=bash>
program to continuously try to connect to a Phidget, based on the parameters given, even trying to
dotnet run
reconnect if it gets disconnected. This means that simply calling open does not guarantee you can
</syntaxhighlight>
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===
|| [[Image:Language_csharp_cli_runcode.png|center|350px|link=https://cdn.phidgets.com/docs/images/f/f3/Language_csharp_cli_runcode.png]]
|-
|}


We recommend the use of event driven programming when working with Phidgets. In C# we can
==Example Code==
hook an event handler at loading with the following code:  
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.
<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);
[[Image:Language_csharp_codesample.png|center|600px|link=https://cdn.phidgets.com/docs/images/0/03/Language_csharp_codesample.png]]


</source>
===Phidget Programming Basics===
</font>
{{PhidgetProgrammingBasicsLink}}
</div>


The ifKit_SensorChange method is defined as follows:
==API==
 
[{{SERVER}}/?view=api&lang=CSharp Phidget22 API]
<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.
 
==Building your Project==
Describe the different ways a project could be built using this language.
 
==Common Problems and Solutions/Workarounds==
Here you can put various frequent problems and our recommended solutions.
 
==API Reference==
This language uses the .NET API, which can be found [http://www.phidgets.com/documentation/web/NETDoc/Index.html here].

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