├── dotnet-basic-send-receive-filters.yml ├── BasicSendReceiveTutorialWithFilters ├── BasicSendReceiveTutorialWithFilters.csproj ├── Extensions.cs ├── Item.cs ├── SendReceive.cs └── Program.cs ├── BasicSendReceiveTutorialWithFilters.sln ├── .gitattributes └── .gitignore /dotnet-basic-send-receive-filters.yml: -------------------------------------------------------------------------------- 1 | ### YamlMime:Sample 2 | sample: 3 | - name: 'Azure Service Bus - Basic Send/Receieve with Filters in .NET' 4 | description: 'A sample demonstrating the basic send/receive operations with Azure Service Bus, using the .NET platform.' 5 | generateZip: true 6 | author: celemensv 7 | languages: 8 | - csharp 9 | technologies: 10 | - service-bus 11 | - service-bus-messaging 12 | - azure 13 | -------------------------------------------------------------------------------- /BasicSendReceiveTutorialWithFilters/BasicSendReceiveTutorialWithFilters.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | netcoreapp3.1 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /BasicSendReceiveTutorialWithFilters/Extensions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Text; 3 | using Azure.Messaging.ServiceBus; 4 | using Newtonsoft.Json; //using Microsoft.Azure.ServiceBus; 5 | 6 | namespace BasicSendReceiveTutorialWithFilters 7 | { 8 | public static class Extensions 9 | { 10 | public static T As(this ServiceBusReceivedMessage message) where T : class 11 | { 12 | return JsonConvert.DeserializeObject(Encoding.UTF8.GetString(message.Body.ToArray())); 13 | } 14 | 15 | public static ServiceBusMessage AsMessage(this object obj) 16 | { 17 | return new ServiceBusMessage(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj))); 18 | } 19 | 20 | public static bool Any(this IList collection) 21 | { 22 | return collection != null && collection.Count > 0; 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /BasicSendReceiveTutorialWithFilters.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.27004.2006 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BasicSendReceiveTutorialWithFilters", "BasicSendReceiveTutorialWithFilters\BasicSendReceiveTutorialWithFilters.csproj", "{C548819A-76C5-4A78-A24B-DE296BEB3FFB}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {C548819A-76C5-4A78-A24B-DE296BEB3FFB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {C548819A-76C5-4A78-A24B-DE296BEB3FFB}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {C548819A-76C5-4A78-A24B-DE296BEB3FFB}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {C548819A-76C5-4A78-A24B-DE296BEB3FFB}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {65B83604-FD21-41AE-9745-1EBAB6BE03B8} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /BasicSendReceiveTutorialWithFilters/Item.cs: -------------------------------------------------------------------------------- 1 | namespace BasicSendReceiveTutorialWithFilters 2 | { 3 | internal class Item 4 | { 5 | public string ItemCategory; 6 | public string theColor; 7 | public double thePrice; 8 | 9 | public Item() 10 | { 11 | } 12 | 13 | public Item(int color, int price, int ItmCat) 14 | { 15 | SetColor(color); 16 | SetPrice(price); 17 | SetItemCategory(ItmCat); 18 | } 19 | 20 | public string GetColor() 21 | { 22 | return theColor; 23 | } 24 | 25 | public double GetPrice() 26 | { 27 | return thePrice; 28 | } 29 | 30 | public string GetItemCategory() 31 | { 32 | return ItemCategory; 33 | } 34 | 35 | public void SetColor(int color) 36 | { 37 | string[] Color = {"Red", "Green", "Blue", "Orange", "Yellow"}; 38 | theColor = Color[color]; 39 | } 40 | 41 | public void SetPrice(int price) 42 | { 43 | double[] Price = {1.4, 2.3, 3.2, 4.1, 5.1}; 44 | thePrice = Price[price]; 45 | } 46 | 47 | public void SetItemCategory(int ItmCat) 48 | { 49 | string[] CategoryList = {"Vegetables", "Beverage", "Meat", "Bread", "Other"}; 50 | ItemCategory = CategoryList[ItmCat]; 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /BasicSendReceiveTutorialWithFilters/SendReceive.cs: -------------------------------------------------------------------------------- 1 | //using Microsoft.Azure.ServiceBus; 2 | //using Microsoft.Azure.ServiceBus.Core; 3 | 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Threading.Tasks; 8 | using Azure.Messaging.ServiceBus; 9 | 10 | namespace BasicSendReceiveTutorialWithFilters 11 | { 12 | internal class SendReceive 13 | { 14 | public int NrOfMessagesPerStore; 15 | public string ServiceBusConnectionString; 16 | public string[] Store; 17 | public string[] Subscriptions; 18 | public string TopicName; 19 | 20 | public async Task SendMessages() 21 | { 22 | try 23 | { 24 | await using var client = new ServiceBusClient(ServiceBusConnectionString); 25 | var taskList = Store.Select(t => SendItems(client, t)).ToList(); 26 | await Task.WhenAll(taskList); 27 | } 28 | catch (Exception ex) 29 | { 30 | Console.WriteLine(ex.ToString()); 31 | } 32 | 33 | Console.WriteLine("\nAll messages sent.\n"); 34 | } 35 | 36 | private async Task SendItems(ServiceBusClient client, string store) 37 | { 38 | // create the sender 39 | var tc = client.CreateSender(TopicName); 40 | for (var i = 0; i < NrOfMessagesPerStore; i++) 41 | { 42 | var r = new Random(); 43 | var item = new Item(r.Next(5), r.Next(5), r.Next(5)); 44 | // Note the extension class which is serializing an deserializing messages 45 | var message = item.AsMessage(); 46 | message.To = store; 47 | message.ApplicationProperties.Add("StoreId", store); 48 | message.ApplicationProperties.Add("Price", item.GetPrice().ToString()); 49 | message.ApplicationProperties.Add("Color", item.GetColor()); 50 | message.ApplicationProperties.Add("Category", item.GetItemCategory()); 51 | await tc.SendMessageAsync(message); 52 | Console.WriteLine( 53 | $"Sent item to Store {store}. Price={item.GetPrice()}, Color={item.GetColor()}, Category={item.GetItemCategory()}"); 54 | ; 55 | } 56 | } 57 | 58 | public async Task Receive() 59 | { 60 | var taskList = new List(); 61 | for (var i = 0; i < Subscriptions.Length; i++) taskList.Add(ReceiveMessages(i.ToString())); 62 | await Task.WhenAll(taskList); 63 | } 64 | 65 | private async Task ReceiveMessages(string subscription) 66 | { 67 | await using var client = new ServiceBusClient(ServiceBusConnectionString); 68 | var receiver = client.CreateReceiver(TopicName, subscription); 69 | 70 | // In reality you would not break out of the loop like in this example but would keep looping. The receiver keeps the connection open 71 | // to the broker for the specified amount of seconds and the broker returns messages as soon as they arrive. The client then initiates 72 | // a new connection. So in reality you would not want to break out of the loop. 73 | // Also note that the code shows how to batch receive, which you would do for performance reasons. For convenience you can also always 74 | // use the regular receive pump which we show in our Quick Start and in other github samples. 75 | while (true) 76 | try 77 | { 78 | //IList messages = await receiver.ReceiveAsync(10, TimeSpan.FromSeconds(2)); 79 | // Note the extension class which is serializing an deserializing messages and testing messages is null or 0. 80 | // If you think you did not receive all messages, just press M and receive again via the menu. 81 | var messages = await receiver.ReceiveMessagesAsync(100); 82 | 83 | if (messages.Any()) 84 | foreach (var message in messages) 85 | { 86 | lock (Console.Out) 87 | { 88 | var item = message.As(); 89 | var myApplicationProperties = message.ApplicationProperties; 90 | Console.WriteLine($"StoreId={myApplicationProperties["StoreId"]}"); 91 | if (message.Subject != null) Console.WriteLine($"Subject={message.Subject}"); 92 | Console.WriteLine( 93 | $"Item data: Price={item.GetPrice()}, Color={item.GetColor()}, Category={item.GetItemCategory()}"); 94 | } 95 | 96 | await receiver.CompleteMessageAsync(message); 97 | } 98 | else 99 | break; 100 | } 101 | catch (Exception ex) 102 | { 103 | Console.WriteLine(ex.ToString()); 104 | } 105 | } 106 | } 107 | } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /BasicSendReceiveTutorialWithFilters/Program.cs: -------------------------------------------------------------------------------- 1 | //using Microsoft.Azure.ServiceBus; 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Threading.Tasks; 6 | using Azure.Messaging.ServiceBus.Administration; 7 | 8 | namespace BasicSendReceiveTutorialWithFilters 9 | { 10 | internal class Program 11 | { 12 | private static readonly string[] Subscriptions = {"S1", "S2", "S3"}; 13 | 14 | private static readonly IDictionary SubscriptionFilters = new Dictionary 15 | { 16 | {"S1", new[] {"StoreId IN('Store1', 'Store2', 'Store3')", "StoreId = 'Store4'"}}, 17 | {"S2", new[] {"sys.To IN ('Store5','Store6','Store7') OR StoreId = 'Store8'"}}, 18 | { 19 | "S3", 20 | new[] 21 | { 22 | "sys.To NOT IN ('Store1','Store2','Store3','Store4','Store5','Store6','Store7','Store8') OR StoreId NOT IN ('Store1','Store2','Store3','Store4','Store5','Store6','Store7','Store8')" 23 | } 24 | } 25 | }; 26 | 27 | // You can have only have one action per rule and this sample code supports only one action for the first filter which is used to create the first rule. 28 | private static readonly IDictionary SubscriptionAction = new Dictionary 29 | { 30 | {"S1", ""}, 31 | {"S2", ""}, 32 | {"S3", "SET sys.Label = 'SalesEvent'"} 33 | }; 34 | 35 | private static readonly string[] Store = 36 | {"Store1", "Store2", "Store3", "Store4", "Store5", "Store6", "Store7", "Store8", "Store9", "Store10"}; 37 | 38 | //static string SysField = "sys.To"; 39 | //static string CustomField = "StoreId"; 40 | private static readonly int NrOfMessagesPerStore = 1; // Send at least 1. 41 | private string ServiceBusConnectionString; 42 | private string TopicName; 43 | 44 | private static Program StartProgram(string ServiceBusConnectionString, string TopicName) 45 | { 46 | var program = new Program 47 | { 48 | ServiceBusConnectionString = ServiceBusConnectionString, 49 | TopicName = TopicName 50 | }; 51 | 52 | return program; 53 | } 54 | 55 | private static void Main(string[] args) 56 | { 57 | var ServiceBusConnectionString = ""; 58 | var TopicName = ""; 59 | 60 | for (var i = 0; i < args.Length; i++) 61 | if (args[i] == "-ConnectionString") 62 | { 63 | Console.WriteLine($"ConnectionString: {args[i + 1]}"); 64 | ServiceBusConnectionString = args[i + 1]; // Alternatively enter your connection string here. 65 | } 66 | else if (args[i] == "-TopicName") 67 | { 68 | Console.WriteLine($"TopicName: {args[i + 1]}"); 69 | TopicName = args[i + 1]; // Alternatively enter your queue name here. 70 | } 71 | 72 | if (ServiceBusConnectionString != "" && TopicName != "") 73 | { 74 | var P = StartProgram(ServiceBusConnectionString, TopicName); 75 | P.PresentMenu().GetAwaiter().GetResult(); 76 | } 77 | else 78 | { 79 | Console.WriteLine("Specify -Connectionstring and -TopicName to execute the example."); 80 | Console.ReadKey(); 81 | } 82 | } 83 | 84 | public async Task PresentMenu() 85 | { 86 | Console.WriteLine("Choose an action:"); 87 | Console.WriteLine("[1] Remove the default filters which accept all messages. DO THIS ALWAYS FIRST."); 88 | Console.WriteLine("[2] Create your own filters. DO THIS SECOND."); 89 | Console.WriteLine("[3] Remove your own filters. OPTIONAL"); 90 | Console.WriteLine("[4] Send messages."); 91 | Console.WriteLine("[5] Receive messages.\n"); 92 | 93 | var key = Console.ReadKey(true).KeyChar; 94 | var keyPressed = key.ToString().ToUpper(); 95 | 96 | switch (keyPressed) 97 | { 98 | case "1": 99 | // This will remove the default filters, which you need to do always first 100 | await RemoveDefaultFilters(); 101 | break; 102 | case "2": 103 | // This will create the customer filters 104 | await CreateCustomFilters(); 105 | break; 106 | case "3": 107 | // Optionally with this you can remove the custom filters. 108 | await CleanUpCustomFilters(); 109 | break; 110 | case "4": 111 | // Use this to Send messages. 112 | await SendMessages(); 113 | break; 114 | case "5": 115 | // Use this to Receive messages. 116 | await Receive(); 117 | break; 118 | default: 119 | Console.WriteLine("Unknown command, press enter to exit"); 120 | Console.ReadLine(); 121 | break; 122 | } 123 | } 124 | 125 | private async Task SendMessages() 126 | { 127 | var sr = new SendReceive 128 | { 129 | ServiceBusConnectionString = ServiceBusConnectionString, 130 | TopicName = TopicName, 131 | Subscriptions = Subscriptions, 132 | Store = Store, 133 | NrOfMessagesPerStore = NrOfMessagesPerStore 134 | }; 135 | 136 | await sr.SendMessages(); 137 | 138 | await PresentMenu(); 139 | } 140 | 141 | private async Task Receive() 142 | { 143 | var sr = new SendReceive 144 | { 145 | ServiceBusConnectionString = ServiceBusConnectionString, 146 | TopicName = TopicName, 147 | Subscriptions = Subscriptions, 148 | Store = Store, 149 | NrOfMessagesPerStore = NrOfMessagesPerStore 150 | }; 151 | 152 | Console.WriteLine( 153 | "\nReceiveing messages. Press any key to exit once all messages have been received. Alternatively press \"M\" to get to the menu\n"); 154 | 155 | await sr.Receive(); 156 | 157 | var key = Console.ReadKey(true).KeyChar; 158 | var keyPressed = key.ToString().ToUpper(); 159 | 160 | switch (keyPressed) 161 | { 162 | case "M": 163 | await PresentMenu(); 164 | break; 165 | } 166 | } 167 | 168 | private async Task RemoveDefaultFilters() 169 | { 170 | Console.WriteLine("Starting to remove default filters."); 171 | 172 | try 173 | { 174 | var client = new ServiceBusAdministrationClient(ServiceBusConnectionString); 175 | foreach (var subscription in Subscriptions) 176 | { 177 | await client.DeleteRuleAsync(TopicName, subscription, CreateRuleOptions.DefaultRuleName); 178 | Console.WriteLine($"Default filter for {subscription} has been removed."); 179 | } 180 | 181 | Console.WriteLine("All default Rules have been removed.\n"); 182 | } 183 | catch (Exception ex) 184 | { 185 | Console.WriteLine(ex.ToString()); 186 | } 187 | 188 | await PresentMenu(); 189 | } 190 | 191 | private async Task CreateCustomFilters() 192 | { 193 | try 194 | { 195 | for (var i = 0; i < Subscriptions.Length; i++) 196 | { 197 | var client = new ServiceBusAdministrationClient(ServiceBusConnectionString); 198 | var filters = SubscriptionFilters[Subscriptions[i]]; 199 | if (filters[0] != "") 200 | { 201 | var count = 0; 202 | foreach (var myFilter in filters) 203 | { 204 | count++; 205 | 206 | var action = SubscriptionAction[Subscriptions[i]]; 207 | if (action != "") 208 | await client.CreateRuleAsync(TopicName, Subscriptions[i], new CreateRuleOptions 209 | { 210 | Filter = new SqlRuleFilter(myFilter), 211 | Action = new SqlRuleAction(action), 212 | Name = $"MyRule{count}" 213 | }); 214 | else 215 | await client.CreateRuleAsync(TopicName, Subscriptions[i], new CreateRuleOptions 216 | { 217 | Filter = new SqlRuleFilter(myFilter), 218 | Name = $"MyRule{count}" 219 | }); 220 | } 221 | } 222 | 223 | Console.WriteLine($"Filters and actions for {Subscriptions[i]} have been created."); 224 | } 225 | 226 | Console.WriteLine("All filters and actions have been created.\n"); 227 | } 228 | catch (Exception ex) 229 | { 230 | Console.WriteLine(ex.ToString()); 231 | } 232 | 233 | await PresentMenu(); 234 | } 235 | 236 | private async Task CleanUpCustomFilters() 237 | { 238 | foreach (var subscription in Subscriptions) 239 | try 240 | { 241 | var client = new ServiceBusAdministrationClient(ServiceBusConnectionString); 242 | var rules = client.GetRulesAsync(TopicName, subscription).GetAsyncEnumerator(); 243 | while (await rules.MoveNextAsync()) 244 | { 245 | await client.DeleteRuleAsync(TopicName, subscription, rules.Current.Name); 246 | Console.WriteLine($"Rule {rules.Current.Name} has been removed."); 247 | } 248 | } 249 | catch (Exception ex) 250 | { 251 | Console.WriteLine(ex.ToString()); 252 | } 253 | 254 | Console.WriteLine("All default filters have been removed.\n"); 255 | 256 | await PresentMenu(); 257 | } 258 | } 259 | } --------------------------------------------------------------------------------