├── .gitattributes ├── .gitignore ├── CreateDeviceIdentity ├── App.config ├── CreateDeviceIdentity.csproj ├── Program.cs ├── Properties │ └── AssemblyInfo.cs └── packages.config ├── IoTHubGetStarted.sln ├── LICENSE ├── README.md ├── ReadDeviceToCloudMessages ├── App.config ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── ReadDeviceToCloudMessages.csproj └── packages.config ├── SimulatedDevice ├── App.config ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── SimulatedDevice.csproj └── packages.config └── Telemetry ├── ApplicationInsights.config ├── Telemetry.cs ├── Telemetry.csproj ├── app.config └── packages.config /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.userosscache 8 | *.sln.docstates 9 | 10 | # User-specific files (MonoDevelop/Xamarin Studio) 11 | *.userprefs 12 | 13 | # Build results 14 | [Dd]ebug/ 15 | [Dd]ebugPublic/ 16 | [Rr]elease/ 17 | [Rr]eleases/ 18 | x64/ 19 | x86/ 20 | bld/ 21 | [Bb]in/ 22 | [Oo]bj/ 23 | [Ll]og/ 24 | 25 | # Visual Studio 2015 cache/options directory 26 | .vs/ 27 | # Uncomment if you have tasks that create the project's static files in wwwroot 28 | #wwwroot/ 29 | 30 | # MSTest test Results 31 | [Tt]est[Rr]esult*/ 32 | [Bb]uild[Ll]og.* 33 | 34 | # NUNIT 35 | *.VisualState.xml 36 | TestResult.xml 37 | 38 | # Build Results of an ATL Project 39 | [Dd]ebugPS/ 40 | [Rr]eleasePS/ 41 | dlldata.c 42 | 43 | # DNX 44 | project.lock.json 45 | artifacts/ 46 | 47 | *_i.c 48 | *_p.c 49 | *_i.h 50 | *.ilk 51 | *.meta 52 | *.obj 53 | *.pch 54 | *.pdb 55 | *.pgc 56 | *.pgd 57 | *.rsp 58 | *.sbr 59 | *.tlb 60 | *.tli 61 | *.tlh 62 | *.tmp 63 | *.tmp_proj 64 | *.log 65 | *.vspscc 66 | *.vssscc 67 | .builds 68 | *.pidb 69 | *.svclog 70 | *.scc 71 | 72 | # Chutzpah Test files 73 | _Chutzpah* 74 | 75 | # Visual C++ cache files 76 | ipch/ 77 | *.aps 78 | *.ncb 79 | *.opendb 80 | *.opensdf 81 | *.sdf 82 | *.cachefile 83 | *.VC.db 84 | *.VC.VC.opendb 85 | 86 | # Visual Studio profiler 87 | *.psess 88 | *.vsp 89 | *.vspx 90 | *.sap 91 | 92 | # TFS 2012 Local Workspace 93 | $tf/ 94 | 95 | # Guidance Automation Toolkit 96 | *.gpState 97 | 98 | # ReSharper is a .NET coding add-in 99 | _ReSharper*/ 100 | *.[Rr]e[Ss]harper 101 | *.DotSettings.user 102 | 103 | # JustCode is a .NET coding add-in 104 | .JustCode 105 | 106 | # TeamCity is a build add-in 107 | _TeamCity* 108 | 109 | # DotCover is a Code Coverage Tool 110 | *.dotCover 111 | 112 | # NCrunch 113 | _NCrunch_* 114 | .*crunch*.local.xml 115 | nCrunchTemp_* 116 | 117 | # MightyMoose 118 | *.mm.* 119 | AutoTest.Net/ 120 | 121 | # Web workbench (sass) 122 | .sass-cache/ 123 | 124 | # Installshield output folder 125 | [Ee]xpress/ 126 | 127 | # DocProject is a documentation generator add-in 128 | DocProject/buildhelp/ 129 | DocProject/Help/*.HxT 130 | DocProject/Help/*.HxC 131 | DocProject/Help/*.hhc 132 | DocProject/Help/*.hhk 133 | DocProject/Help/*.hhp 134 | DocProject/Help/Html2 135 | DocProject/Help/html 136 | 137 | # Click-Once directory 138 | publish/ 139 | 140 | # Publish Web Output 141 | *.[Pp]ublish.xml 142 | *.azurePubxml 143 | # TODO: Comment the next line if you want to checkin your web deploy settings 144 | # but database connection strings (with potential passwords) will be unencrypted 145 | *.pubxml 146 | *.publishproj 147 | 148 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 149 | # checkin your Azure Web App publish settings, but sensitive information contained 150 | # in these scripts will be unencrypted 151 | PublishScripts/ 152 | 153 | # NuGet Packages 154 | *.nupkg 155 | # The packages folder can be ignored because of Package Restore 156 | **/packages/* 157 | # except build/, which is used as an MSBuild target. 158 | !**/packages/build/ 159 | # Uncomment if necessary however generally it will be regenerated when needed 160 | #!**/packages/repositories.config 161 | # NuGet v3's project.json files produces more ignoreable files 162 | *.nuget.props 163 | *.nuget.targets 164 | 165 | # Microsoft Azure Build Output 166 | csx/ 167 | *.build.csdef 168 | 169 | # Microsoft Azure Emulator 170 | ecf/ 171 | rcf/ 172 | 173 | # Windows Store app package directories and files 174 | AppPackages/ 175 | BundleArtifacts/ 176 | Package.StoreAssociation.xml 177 | _pkginfo.txt 178 | 179 | # Visual Studio cache files 180 | # files ending in .cache can be ignored 181 | *.[Cc]ache 182 | # but keep track of directories ending in .cache 183 | !*.[Cc]ache/ 184 | 185 | # Others 186 | ClientBin/ 187 | ~$* 188 | *~ 189 | *.dbmdl 190 | *.dbproj.schemaview 191 | *.pfx 192 | *.publishsettings 193 | node_modules/ 194 | orleans.codegen.cs 195 | 196 | # Since there are multiple workflows, uncomment next line to ignore bower_components 197 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 198 | #bower_components/ 199 | 200 | # RIA/Silverlight projects 201 | Generated_Code/ 202 | 203 | # Backup & report files from converting an old project file 204 | # to a newer Visual Studio version. Backup files are not needed, 205 | # because we have git ;-) 206 | _UpgradeReport_Files/ 207 | Backup*/ 208 | UpgradeLog*.XML 209 | UpgradeLog*.htm 210 | 211 | # SQL Server files 212 | *.mdf 213 | *.ldf 214 | 215 | # Business Intelligence projects 216 | *.rdl.data 217 | *.bim.layout 218 | *.bim_*.settings 219 | 220 | # Microsoft Fakes 221 | FakesAssemblies/ 222 | 223 | # GhostDoc plugin setting file 224 | *.GhostDoc.xml 225 | 226 | # Node.js Tools for Visual Studio 227 | .ntvs_analysis.dat 228 | 229 | # Visual Studio 6 build log 230 | *.plg 231 | 232 | # Visual Studio 6 workspace options file 233 | *.opt 234 | 235 | # Visual Studio LightSwitch build output 236 | **/*.HTMLClient/GeneratedArtifacts 237 | **/*.DesktopClient/GeneratedArtifacts 238 | **/*.DesktopClient/ModelManifest.xml 239 | **/*.Server/GeneratedArtifacts 240 | **/*.Server/ModelManifest.xml 241 | _Pvt_Extensions 242 | 243 | # Paket dependency manager 244 | .paket/paket.exe 245 | paket-files/ 246 | 247 | # FAKE - F# Make 248 | .fake/ 249 | 250 | # JetBrains Rider 251 | .idea/ 252 | *.sln.iml 253 | -------------------------------------------------------------------------------- /CreateDeviceIdentity/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /CreateDeviceIdentity/CreateDeviceIdentity.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {52C23EA2-9F82-49C1-A729-A97C84106EA7} 8 | Exe 9 | CreateDeviceIdentity 10 | CreateDeviceIdentity 11 | v4.5.2 12 | 512 13 | true 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | ..\packages\Microsoft.Azure.Amqp.2.0.3\lib\net45\Microsoft.Azure.Amqp.dll 37 | 38 | 39 | ..\packages\Microsoft.Azure.Devices.1.2.4\lib\net451\Microsoft.Azure.Devices.dll 40 | 41 | 42 | ..\packages\Microsoft.Azure.Devices.Shared.1.0.8\lib\net45\Microsoft.Azure.Devices.Shared.dll 43 | 44 | 45 | ..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll 46 | True 47 | 48 | 49 | ..\packages\PCLCrypto.2.0.147\lib\net45\PCLCrypto.dll 50 | 51 | 52 | ..\packages\PInvoke.BCrypt.0.3.2\lib\net40\PInvoke.BCrypt.dll 53 | 54 | 55 | ..\packages\PInvoke.Kernel32.0.3.2\lib\net40\PInvoke.Kernel32.dll 56 | 57 | 58 | ..\packages\PInvoke.NCrypt.0.3.2\lib\net40\PInvoke.NCrypt.dll 59 | 60 | 61 | ..\packages\PInvoke.Windows.Core.0.3.2\lib\portable-net45+win+wpa81+MonoAndroid10+xamarinios10+MonoTouch10\PInvoke.Windows.Core.dll 62 | 63 | 64 | 65 | 66 | 67 | ..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll 68 | 69 | 70 | 71 | ..\packages\Microsoft.AspNet.WebApi.Core.5.2.3\lib\net45\System.Web.Http.dll 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | ..\packages\Validation.2.2.8\lib\dotnet\Validation.dll 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | {34AAD631-2425-43C3-ABC2-23EDA9EEF3AF} 94 | Telemetry 95 | 96 | 97 | 98 | -------------------------------------------------------------------------------- /CreateDeviceIdentity/Program.cs: -------------------------------------------------------------------------------- 1 | namespace CreateDeviceIdentity 2 | { 3 | using System; 4 | using System.Configuration; 5 | using System.Threading.Tasks; 6 | using Microsoft.Azure.Devices; 7 | using Microsoft.Azure.Devices.Common.Exceptions; 8 | using Telemetry; 9 | 10 | public class Program 11 | { 12 | private static RegistryManager _registryManager; 13 | private const string ConnectionString = "{iot hub connection string}"; 14 | private const string Name = "createdeviceidentity"; 15 | private const string DeviceId = "myFirstDevice"; 16 | private const string TelemetryKey = "telemetry"; 17 | private const string InstrumentationKey = "instrumentationKey"; 18 | private static Telemetry TelemetryClient; 19 | private static readonly Configuration Config = ConfigurationManager.OpenExeConfiguration(System.IO.Path.Combine( 20 | Environment.CurrentDirectory, System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name)); 21 | 22 | private static void Main(string[] args) 23 | { 24 | OptIn(); 25 | _registryManager = RegistryManager.CreateFromConnectionString(ConnectionString); 26 | AddDeviceAsync().Wait(); 27 | Console.ReadLine(); 28 | } 29 | 30 | private static async Task AddDeviceAsync() 31 | { 32 | Device device; 33 | try 34 | { 35 | device = await _registryManager.AddDeviceAsync(new Device(DeviceId)); 36 | SendTelemetry("success", "register new device"); 37 | } 38 | catch (DeviceAlreadyExistsException) 39 | { 40 | device = await _registryManager.GetDeviceAsync(DeviceId); 41 | SendTelemetry("success", "device existed"); 42 | } 43 | catch (Exception e) 44 | { 45 | SendTelemetry("failed", $"register device failed: {e.Message}"); 46 | Console.WriteLine($"register device failed: {e.Message}"); 47 | throw; 48 | } 49 | 50 | Console.WriteLine($"device key : {device.Authentication.SymmetricKey.PrimaryKey}"); 51 | } 52 | 53 | private static void OptIn() 54 | { 55 | if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings[TelemetryKey])) 56 | { 57 | return; 58 | } 59 | 60 | try 61 | { 62 | string response; 63 | TelemetryClient = new Telemetry(ConfigurationManager.AppSettings[InstrumentationKey]); 64 | Console.WriteLine(Telemetry.PromptText); 65 | do 66 | { 67 | Console.Write("Select y to enable data collection :(y/n, default is y) "); 68 | response = Console.ReadLine(); 69 | } while (response != "" && response.ToLower() != "y" && response.ToLower() != "n"); 70 | 71 | var choice = response == "" || response.ToLower() == "y"; 72 | Config.AppSettings.Settings.Remove(TelemetryKey); 73 | Config.AppSettings.Settings.Add(TelemetryKey, choice.ToString()); 74 | Config.Save(ConfigurationSaveMode.Modified); 75 | TelemetryClient.TrackUserChoice(response); 76 | } 77 | catch (Exception) 78 | { 79 | // Ignore 80 | } 81 | } 82 | 83 | private static void SendTelemetry(string eventName, string message) 84 | { 85 | if(TelemetryClient != null) 86 | { 87 | bool shouldSend; 88 | bool.TryParse(Config.AppSettings.Settings[TelemetryKey].Value, out shouldSend); 89 | if (shouldSend) 90 | { 91 | TelemetryClient.Track(eventName, ConnectionString, Name, message); 92 | } 93 | } 94 | 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /CreateDeviceIdentity/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("CreateDeviceIdentity")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("CreateDeviceIdentity")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("52c23ea2-9f82-49c1-a729-a97c84106ea7")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /CreateDeviceIdentity/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /IoTHubGetStarted.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 14 4 | VisualStudioVersion = 14.0.25420.1 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CreateDeviceIdentity", "CreateDeviceIdentity\CreateDeviceIdentity.csproj", "{52C23EA2-9F82-49C1-A729-A97C84106EA7}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ReadDeviceToCloudMessages", "ReadDeviceToCloudMessages\ReadDeviceToCloudMessages.csproj", "{04C177ED-A458-4DBC-855E-8AAF1D8C0432}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SimulatedDevice", "SimulatedDevice\SimulatedDevice.csproj", "{F19A36A4-D8F7-420A-933E-1FFF2667780D}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{45A192A0-472C-4D96-812F-883011CE5A6A}" 13 | ProjectSection(SolutionItems) = preProject 14 | README.md = README.md 15 | EndProjectSection 16 | EndProject 17 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Telemetry", "Telemetry\Telemetry.csproj", "{34AAD631-2425-43C3-ABC2-23EDA9EEF3AF}" 18 | EndProject 19 | Global 20 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 21 | Debug|Any CPU = Debug|Any CPU 22 | Release|Any CPU = Release|Any CPU 23 | EndGlobalSection 24 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 25 | {52C23EA2-9F82-49C1-A729-A97C84106EA7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 26 | {52C23EA2-9F82-49C1-A729-A97C84106EA7}.Debug|Any CPU.Build.0 = Debug|Any CPU 27 | {52C23EA2-9F82-49C1-A729-A97C84106EA7}.Release|Any CPU.ActiveCfg = Release|Any CPU 28 | {52C23EA2-9F82-49C1-A729-A97C84106EA7}.Release|Any CPU.Build.0 = Release|Any CPU 29 | {04C177ED-A458-4DBC-855E-8AAF1D8C0432}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 30 | {04C177ED-A458-4DBC-855E-8AAF1D8C0432}.Debug|Any CPU.Build.0 = Debug|Any CPU 31 | {04C177ED-A458-4DBC-855E-8AAF1D8C0432}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 | {04C177ED-A458-4DBC-855E-8AAF1D8C0432}.Release|Any CPU.Build.0 = Release|Any CPU 33 | {F19A36A4-D8F7-420A-933E-1FFF2667780D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {F19A36A4-D8F7-420A-933E-1FFF2667780D}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {F19A36A4-D8F7-420A-933E-1FFF2667780D}.Release|Any CPU.ActiveCfg = Release|Any CPU 36 | {F19A36A4-D8F7-420A-933E-1FFF2667780D}.Release|Any CPU.Build.0 = Release|Any CPU 37 | {34AAD631-2425-43C3-ABC2-23EDA9EEF3AF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {34AAD631-2425-43C3-ABC2-23EDA9EEF3AF}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {34AAD631-2425-43C3-ABC2-23EDA9EEF3AF}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {34AAD631-2425-43C3-ABC2-23EDA9EEF3AF}.Release|Any CPU.Build.0 = Release|Any CPU 41 | EndGlobalSection 42 | GlobalSection(SolutionProperties) = preSolution 43 | HideSolutionNode = FALSE 44 | EndGlobalSection 45 | GlobalSection(ExtensibilityGlobals) = postSolution 46 | EnterpriseLibraryConfigurationToolBinariesPathV6 = packages\EnterpriseLibrary.TransientFaultHandling.6.0.1304.0\lib\portable-net45+win+wp8 47 | EndGlobalSection 48 | EndGlobal 49 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. All rights reserved. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Connect your simulated device to your IoT hub using .NET 2 | 3 | Please follow the tutorial https://docs.microsoft.com/azure/iot-hub/iot-hub-csharp-csharp-getstarted to learn about this sample. 4 | 5 | ## Contributing 6 | 7 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. 8 | -------------------------------------------------------------------------------- /ReadDeviceToCloudMessages/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 12 | 14 | 16 | 17 | 18 | 20 | 22 | 24 | 26 | 28 | 29 | 30 | 32 | 34 | 36 | 38 | 40 | 42 | 44 | 45 | 46 | 47 | 48 | 49 | 51 | 52 | -------------------------------------------------------------------------------- /ReadDeviceToCloudMessages/Program.cs: -------------------------------------------------------------------------------- 1 | namespace ReadDeviceToCloudMessages 2 | { 3 | using System; 4 | using System.Threading.Tasks; 5 | using System.Text; 6 | using Microsoft.ServiceBus.Messaging; 7 | using System.Threading; 8 | using System.Linq; 9 | 10 | public class Program 11 | { 12 | private const string ConnectionString = "{iothub connection string}"; 13 | private const string IotHubD2CEndpoint = "messages/events"; 14 | private static EventHubClient _eventHubClient; 15 | 16 | private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken cancellationToken) 17 | { 18 | var eventHubReceiver = _eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow); 19 | while (true) 20 | { 21 | if (cancellationToken.IsCancellationRequested) break; 22 | var eventData = await eventHubReceiver.ReceiveAsync(); 23 | if (eventData == null) continue; 24 | 25 | var data = Encoding.UTF8.GetString(eventData.GetBytes()); 26 | Console.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data); 27 | } 28 | } 29 | 30 | private static void Main(string[] args) 31 | { 32 | Console.WriteLine("Receive messages. Ctrl-C to exit.\n"); 33 | _eventHubClient = EventHubClient.CreateFromConnectionString(ConnectionString, IotHubD2CEndpoint); 34 | var partitions = _eventHubClient.GetRuntimeInformation().PartitionIds; 35 | var cts = new CancellationTokenSource(); 36 | 37 | Console.CancelKeyPress += (s, e) => 38 | { 39 | e.Cancel = true; 40 | cts.Cancel(); 41 | Console.WriteLine("Exiting..."); 42 | }; 43 | 44 | var tasks = partitions.Select(partition => ReceiveMessagesFromDeviceAsync(partition, cts.Token)); 45 | Task.WaitAll(tasks.ToArray()); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /ReadDeviceToCloudMessages/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("ReadDeviceToCloudMessages")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("ReadDeviceToCloudMessages")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("04c177ed-a458-4dbc-855e-8aaf1d8c0432")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /ReadDeviceToCloudMessages/ReadDeviceToCloudMessages.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {04C177ED-A458-4DBC-855E-8AAF1D8C0432} 8 | Exe 9 | ReadDeviceToCloudMessages 10 | ReadDeviceToCloudMessages 11 | v4.5.2 12 | 512 13 | true 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | ..\packages\WindowsAzure.ServiceBus.4.0.0\lib\net45-full\Microsoft.ServiceBus.dll 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /ReadDeviceToCloudMessages/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /SimulatedDevice/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /SimulatedDevice/Program.cs: -------------------------------------------------------------------------------- 1 | namespace SimulatedDevice 2 | { 3 | using System; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Microsoft.Azure.Devices.Client; 7 | using Newtonsoft.Json; 8 | 9 | public class Program 10 | { 11 | private const string IotHubUri = "{iot hub hostname}"; 12 | private const string DeviceKey = "{device key}"; 13 | private const string DeviceId = "myFirstDevice"; 14 | private const double MinTemperature = 20; 15 | private const double MinHumidity = 60; 16 | private static readonly Random Rand = new Random(); 17 | private static DeviceClient _deviceClient; 18 | private static int _messageId = 1; 19 | 20 | private static async void SendDeviceToCloudMessagesAsync() 21 | { 22 | while (true) 23 | { 24 | var currentTemperature = MinTemperature + Rand.NextDouble() * 15; 25 | var currentHumidity = MinHumidity + Rand.NextDouble() * 20; 26 | 27 | var telemetryDataPoint = new 28 | { 29 | messageId = _messageId++, 30 | deviceId = DeviceId, 31 | temperature = currentTemperature, 32 | humidity = currentHumidity 33 | }; 34 | var messageString = JsonConvert.SerializeObject(telemetryDataPoint); 35 | var message = new Message(Encoding.ASCII.GetBytes(messageString)); 36 | message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false"); 37 | 38 | await _deviceClient.SendEventAsync(message); 39 | Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString); 40 | 41 | await Task.Delay(1000); 42 | } 43 | } 44 | 45 | private static void Main(string[] args) 46 | { 47 | Console.WriteLine("Simulated device\n"); 48 | _deviceClient = DeviceClient.Create(IotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey(DeviceId, DeviceKey), TransportType.Mqtt); 49 | _deviceClient.ProductInfo = "HappyPath_Simulated-CSharp"; 50 | 51 | SendDeviceToCloudMessagesAsync(); 52 | Console.ReadLine(); 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /SimulatedDevice/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("SimulatedDevice")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("SimulatedDevice")] 13 | [assembly: AssemblyCopyright("Copyright © 2017")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("f19a36a4-d8f7-420a-933e-1fff2667780d")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /SimulatedDevice/SimulatedDevice.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {F19A36A4-D8F7-420A-933E-1FFF2667780D} 8 | Exe 9 | SimulatedDevice 10 | SimulatedDevice 11 | v4.5.2 12 | 512 13 | true 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | pdbonly 28 | true 29 | bin\Release\ 30 | TRACE 31 | prompt 32 | 4 33 | 34 | 35 | 36 | ..\packages\DotNetty.Buffers.0.4.6\lib\net45\DotNetty.Buffers.dll 37 | 38 | 39 | ..\packages\DotNetty.Codecs.0.4.6\lib\net45\DotNetty.Codecs.dll 40 | 41 | 42 | ..\packages\DotNetty.Codecs.Mqtt.0.4.6\lib\net45\DotNetty.Codecs.Mqtt.dll 43 | 44 | 45 | ..\packages\DotNetty.Common.0.4.6\lib\net45\DotNetty.Common.dll 46 | 47 | 48 | ..\packages\DotNetty.Handlers.0.4.6\lib\net45\DotNetty.Handlers.dll 49 | 50 | 51 | ..\packages\DotNetty.Transport.0.4.6\lib\net45\DotNetty.Transport.dll 52 | 53 | 54 | ..\packages\Microsoft.Azure.Amqp.2.0.6\lib\net45\Microsoft.Azure.Amqp.dll 55 | 56 | 57 | ..\packages\Microsoft.Azure.Devices.Client.1.6.0\lib\net45\Microsoft.Azure.Devices.Client.dll 58 | 59 | 60 | ..\packages\Microsoft.Azure.Devices.Shared.1.3.0\lib\net45\Microsoft.Azure.Devices.Shared.dll 61 | 62 | 63 | ..\packages\Microsoft.Azure.KeyVault.Core.1.0.0\lib\net40\Microsoft.Azure.KeyVault.Core.dll 64 | 65 | 66 | ..\packages\Microsoft.Data.Edm.5.6.4\lib\net40\Microsoft.Data.Edm.dll 67 | 68 | 69 | ..\packages\Microsoft.Data.OData.5.6.4\lib\net40\Microsoft.Data.OData.dll 70 | 71 | 72 | ..\packages\Microsoft.Data.Services.Client.5.6.4\lib\net40\Microsoft.Data.Services.Client.dll 73 | 74 | 75 | ..\packages\Microsoft.Extensions.DependencyInjection.Abstractions.1.1.0\lib\netstandard1.0\Microsoft.Extensions.DependencyInjection.Abstractions.dll 76 | 77 | 78 | ..\packages\Microsoft.Extensions.Logging.1.1.1\lib\netstandard1.1\Microsoft.Extensions.Logging.dll 79 | 80 | 81 | ..\packages\Microsoft.Extensions.Logging.Abstractions.1.1.1\lib\netstandard1.1\Microsoft.Extensions.Logging.Abstractions.dll 82 | 83 | 84 | ..\packages\EnterpriseLibrary.TransientFaultHandling.6.0.1304.0\lib\portable-net45+win+wp8\Microsoft.Practices.EnterpriseLibrary.TransientFaultHandling.dll 85 | 86 | 87 | ..\packages\WindowsAzure.Storage.7.0.0\lib\net40\Microsoft.WindowsAzure.Storage.dll 88 | 89 | 90 | ..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll 91 | True 92 | 93 | 94 | ..\packages\PCLCrypto.2.0.147\lib\net45\PCLCrypto.dll 95 | 96 | 97 | ..\packages\PInvoke.BCrypt.0.3.2\lib\net40\PInvoke.BCrypt.dll 98 | 99 | 100 | ..\packages\PInvoke.Kernel32.0.3.2\lib\net40\PInvoke.Kernel32.dll 101 | 102 | 103 | ..\packages\PInvoke.NCrypt.0.3.2\lib\net40\PInvoke.NCrypt.dll 104 | 105 | 106 | ..\packages\PInvoke.Windows.Core.0.3.2\lib\portable-net45+win+wpa81+MonoAndroid10+xamarinios10+MonoTouch10\PInvoke.Windows.Core.dll 107 | 108 | 109 | 110 | 111 | 112 | 113 | ..\packages\Microsoft.AspNet.WebApi.Client.5.2.3\lib\net45\System.Net.Http.Formatting.dll 114 | 115 | 116 | 117 | ..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll 118 | 119 | 120 | ..\packages\System.Spatial.5.6.4\lib\net40\System.Spatial.dll 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | ..\packages\Validation.2.2.8\lib\dotnet\Validation.dll 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | -------------------------------------------------------------------------------- /SimulatedDevice/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /Telemetry/ApplicationInsights.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 5 7 | 8 | 9 | -------------------------------------------------------------------------------- /Telemetry/Telemetry.cs: -------------------------------------------------------------------------------- 1 | namespace Telemetry 2 | { 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Linq; 6 | using System.Net.NetworkInformation; 7 | using System.Security.Cryptography; 8 | using System.Text; 9 | using Microsoft.ApplicationInsights; 10 | using Microsoft.ApplicationInsights.Extensibility; 11 | using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel; 12 | 13 | public class Telemetry 14 | { 15 | private static TelemetryClient Client; 16 | public static string PromptText = 17 | "Microsoft would like to collect data about how users use Azure IoT samples and some problems they encounter.\r\n" + 18 | "Microsoft uses this information to improve our tooling experience.\r\n" + 19 | "Participation is voluntary and when you choose to participate, your device will automatically sends information to Microsoft about how you use Azure IoT samples\r\n" + 20 | "Telemetry setting will be remembered. If you would like to reset, please delete following file and run the sample again\r\n" + 21 | "CreateDeviceIdentity.exe.config (which is in the same folder with CreateDeviceIdentity.exe)"; 22 | 23 | public Telemetry(string instrumentationKey) 24 | { 25 | var config = TelemetryConfiguration.CreateDefault(); 26 | config.InstrumentationKey = instrumentationKey; 27 | config.TelemetryChannel = new ServerTelemetryChannel(); 28 | Client = new TelemetryClient(config); 29 | } 30 | 31 | private const string SimulatedDevice = "simulated device"; 32 | 33 | private static string SHA256Hash(string value) 34 | { 35 | using (var hash = SHA256.Create()) 36 | { 37 | return string.Concat(hash.ComputeHash(Encoding.UTF8.GetBytes(value)).Select(item => item.ToString("x2"))); 38 | } 39 | } 40 | 41 | private static string GetMac() 42 | { 43 | return 44 | NetworkInterface.GetAllNetworkInterfaces() 45 | .Where(p => p.OperationalStatus == OperationalStatus.Up) 46 | .Select(p => p.GetPhysicalAddress().ToString()) 47 | .FirstOrDefault(); 48 | } 49 | 50 | public void TrackUserChoice(string choice) 51 | { 52 | try 53 | { 54 | if (string.IsNullOrEmpty(choice)) 55 | { 56 | choice = "y"; 57 | } 58 | if(choice == "n") 59 | { 60 | Client.Context.Location.Ip = "0.0.0.0"; 61 | } 62 | Client.TrackEvent("success", new Dictionary 63 | { 64 | {"language", "C#"}, 65 | {"device", SimulatedDevice}, 66 | {"userchoice", choice} 67 | }); 68 | Client.Flush(); 69 | } 70 | catch (Exception) 71 | { 72 | //ignore 73 | } 74 | } 75 | 76 | public void Track(string eventName, string connectionstring, string projectName, string message) 77 | { 78 | try 79 | { 80 | Client.TrackEvent(eventName, new Dictionary 81 | { 82 | {"iothub", SHA256Hash(connectionstring.Split('.').FirstOrDefault())}, 83 | {"language", "C#"}, 84 | {"device", SimulatedDevice}, 85 | {"project_name", projectName}, 86 | {"osversion", Environment.OSVersion.ToString()}, 87 | {"mac", SHA256Hash(GetMac())}, 88 | {"message", message} 89 | }); 90 | Client.Flush(); 91 | } 92 | catch (Exception) 93 | { 94 | // ignored 95 | } 96 | } 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /Telemetry/Telemetry.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {34AAD631-2425-43C3-ABC2-23EDA9EEF3AF} 8 | Library 9 | Properties 10 | Telemetry 11 | Telemetry 12 | v4.5.2 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | 24 | 25 | pdbonly 26 | true 27 | bin\Release\ 28 | TRACE 29 | prompt 30 | 4 31 | 32 | 33 | 34 | ..\packages\Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel.2.3.0\lib\net45\Microsoft.AI.ServerTelemetryChannel.dll 35 | 36 | 37 | ..\packages\Microsoft.ApplicationInsights.2.3.0\lib\net45\Microsoft.ApplicationInsights.dll 38 | True 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 65 | -------------------------------------------------------------------------------- /Telemetry/app.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Telemetry/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | --------------------------------------------------------------------------------