Best Xunit code snippet using TestUtility.Callback
PackagesControllerFacts.cs
Source:PackagesControllerFacts.cs
...393 It.IsAny<PackageRegistration>(),394 It.IsAny<string>(),395 It.IsAny<string>(),396 false))397 .Callback<MailAddress, PackageRegistration, string, string, bool>((_, __, msg, ___, ____) => sentMessage = msg);398 var package = new PackageRegistration { Id = "factory" };399 var packageService = new Mock<IPackageService>();400 packageService.Setup(p => p.FindPackageRegistrationById("factory")).Returns(package);401 var userService = new Mock<IUserService>();402 var controller = CreateController(403 packageService: packageService,404 messageService: messageService);405 controller.SetCurrentUser(new User { EmailAddress = "montgomery@burns.example.com", Username = "Montgomery" });406 var model = new ContactOwnersViewModel407 {408 Message = "I like the cut of your jib. It's <b>bold</b>.",409 };410 var result = controller.ContactOwners("factory", model) as RedirectToRouteResult;411 Assert.Equal("I like the cut of your jib. It's <b>bold</b>.", sentMessage);412 }413 [Fact]414 public void CallsSendContactOwnersMessageWithUserInfo()415 {416 var messageService = new Mock<IMessageService>();417 messageService.Setup(418 s => s.SendContactOwnersMessage(419 It.IsAny<MailAddress>(),420 It.IsAny<PackageRegistration>(),421 "I like the cut of your jib",422 It.IsAny<string>(), false));423 var package = new PackageRegistration { Id = "factory" };424 var packageService = new Mock<IPackageService>();425 packageService.Setup(p => p.FindPackageRegistrationById("factory")).Returns(package);426 var userService = new Mock<IUserService>();427 var controller = CreateController(428 packageService: packageService,429 messageService: messageService);430 controller.SetCurrentUser(new User { EmailAddress = "montgomery@burns.example.com", Username = "Montgomery" });431 var model = new ContactOwnersViewModel432 {433 Message = "I like the cut of your jib",434 };435 var result = controller.ContactOwners("factory", model) as RedirectToRouteResult;436 Assert.NotNull(result);437 }438 }439 public class TheEditMethod440 {441 [Fact]442 public void UpdatesUnlistedIfSelected()443 {444 // Arrange445 var package = new Package446 {447 PackageRegistration = new PackageRegistration { Id = "Foo" },448 Version = "1.0",449 Listed = true450 };451 package.PackageRegistration.Owners.Add(new User("Frodo"));452 var packageService = new Mock<IPackageService>(MockBehavior.Strict);453 packageService.Setup(svc => svc.MarkPackageListed(It.IsAny<Package>(), It.IsAny<bool>())).Throws(new Exception("Shouldn't be called"));454 packageService.Setup(svc => svc.MarkPackageUnlisted(It.IsAny<Package>(), It.IsAny<bool>())).Verifiable();455 packageService.Setup(svc => svc.FindPackageByIdAndVersion("Foo", "1.0", true)).Returns(package).Verifiable();456 var indexingService = new Mock<IIndexingService>();457 var controller = CreateController(packageService: packageService, indexingService: indexingService);458 controller.SetCurrentUser("Frodo");459 controller.Url = new UrlHelper(new RequestContext(), new RouteCollection());460 // Act461 var result = controller.Edit("Foo", "1.0", listed: false, urlFactory: p => @"~\Bar.cshtml");462 // Assert463 packageService.Verify();464 indexingService.Verify(i => i.UpdatePackage(package));465 Assert.IsType<RedirectResult>(result);466 Assert.Equal(@"~\Bar.cshtml", ((RedirectResult)result).Url);467 }468 [Fact]469 public void UpdatesUnlistedIfNotSelected()470 {471 // Arrange472 var package = new Package473 {474 PackageRegistration = new PackageRegistration { Id = "Foo" },475 Version = "1.0",476 Listed = true477 };478 package.PackageRegistration.Owners.Add(new User("Frodo"));479 var packageService = new Mock<IPackageService>(MockBehavior.Strict);480 packageService.Setup(svc => svc.MarkPackageListed(It.IsAny<Package>(), It.IsAny<bool>())).Verifiable();481 packageService.Setup(svc => svc.MarkPackageUnlisted(It.IsAny<Package>(), It.IsAny<bool>())).Throws(new Exception("Shouldn't be called"));482 packageService.Setup(svc => svc.FindPackageByIdAndVersion("Foo", "1.0", true)).Returns(package).Verifiable();483 var indexingService = new Mock<IIndexingService>();484 var controller = CreateController(packageService: packageService, indexingService: indexingService);485 controller.SetCurrentUser("Frodo");486 controller.Url = new UrlHelper(new RequestContext(), new RouteCollection());487 // Act488 var result = controller.Edit("Foo", "1.0", listed: true, urlFactory: p => @"~\Bar.cshtml");489 // Assert490 packageService.Verify();491 indexingService.Verify(i => i.UpdatePackage(package));492 Assert.IsType<RedirectResult>(result);493 Assert.Equal(@"~\Bar.cshtml", ((RedirectResult)result).Url);494 }495 }496 public class TheListPackagesMethod497 {498 [Fact]499 public async Task TrimsSearchTerm()500 {501 var searchService = new Mock<ISearchService>();502 searchService.Setup(s => s.Search(It.IsAny<SearchFilter>())).Returns(503 Task.FromResult(new SearchResults(0, DateTime.UtcNow)));504 var controller = CreateController(searchService: searchService);505 controller.SetCurrentUser(TestUtility.FakeUser);506 var result = (await controller.ListPackages(" test ")) as ViewResult;507 var model = result.Model as PackageListViewModel;508 Assert.Equal("test", model.SearchTerm);509 }510 }511 public class TheReportAbuseMethod512 {513 [Fact]514 public void SendsMessageToGalleryOwnerWithEmailOnlyWhenUnauthenticated()515 {516 var messageService = new Mock<IMessageService>();517 messageService.Setup(518 s => s.ReportAbuse(It.Is<ReportPackageRequest>(r => r.Message == "Mordor took my finger")));519 var package = new Package520 {521 PackageRegistration = new PackageRegistration { Id = "mordor" },522 Version = "2.0.1"523 };524 var packageService = new Mock<IPackageService>();525 packageService.Setup(p => p.FindPackageByIdAndVersion("mordor", "2.0.1", true)).Returns(package);526 var httpContext = new Mock<HttpContextBase>();527 var controller = CreateController(528 packageService: packageService,529 messageService: messageService,530 httpContext: httpContext);531 var model = new ReportAbuseViewModel532 {533 Email = "frodo@hobbiton.example.com",534 Message = "Mordor took my finger.",535 Reason = ReportPackageReason.IsFraudulent,536 AlreadyContactedOwner = true,537 };538 TestUtility.SetupUrlHelper(controller, httpContext);539 var result = controller.ReportAbuse("mordor", "2.0.1", model) as RedirectResult;540 Assert.NotNull(result);541 messageService.Verify(542 s => s.ReportAbuse(543 It.Is<ReportPackageRequest>(544 r => r.FromAddress.Address == "frodo@hobbiton.example.com"545 && r.Package == package546 && r.Reason == EnumHelper.GetDescription(ReportPackageReason.IsFraudulent)547 && r.Message == "Mordor took my finger."548 && r.AlreadyContactedOwners)));549 }550 [Fact]551 public void SendsMessageToGalleryOwnerWithUserInfoWhenAuthenticated()552 {553 var messageService = new Mock<IMessageService>();554 messageService.Setup(555 s => s.ReportAbuse(It.Is<ReportPackageRequest>(r => r.Message == "Mordor took my finger")));556 var user = new User { EmailAddress = "frodo@hobbiton.example.com", Username = "Frodo", Key = 1 };557 var package = new Package558 {559 PackageRegistration = new PackageRegistration { Id = "mordor" },560 Version = "2.0.1"561 };562 var packageService = new Mock<IPackageService>();563 packageService.Setup(p => p.FindPackageByIdAndVersion("mordor", It.IsAny<string>(), true)).Returns(package);564 var httpContext = new Mock<HttpContextBase>();565 var controller = CreateController(566 packageService: packageService,567 messageService: messageService,568 httpContext: httpContext);569 controller.SetCurrentUser(user);570 var model = new ReportAbuseViewModel571 {572 Message = "Mordor took my finger",573 Reason = ReportPackageReason.IsFraudulent574 };575 TestUtility.SetupUrlHelper(controller, httpContext);576 ActionResult result = controller.ReportAbuse("mordor", "2.0.1", model) as RedirectResult;577 Assert.NotNull(result);578 messageService.Verify(579 s => s.ReportAbuse(580 It.Is<ReportPackageRequest>(581 r => r.Message == "Mordor took my finger"582 && r.FromAddress.Address == "frodo@hobbiton.example.com"583 && r.FromAddress.DisplayName == "Frodo"584 && r.Reason == EnumHelper.GetDescription(ReportPackageReason.IsFraudulent))));585 }586 [Fact]587 public void FormRedirectsPackageOwnerToReportMyPackage()588 {589 var user = new User { EmailAddress = "darklord@mordor.com", Username = "Sauron" };590 var package = new Package591 {592 PackageRegistration = new PackageRegistration { Id = "Mordor", Owners = { user } },593 Version = "2.0.1"594 };595 var packageService = new Mock<IPackageService>();596 packageService.Setup(p => p.FindPackageByIdAndVersion("Mordor", It.IsAny<string>(), true)).Returns(package);597 var httpContext = new Mock<HttpContextBase>();598 var controller = CreateController(599 packageService: packageService,600 httpContext: httpContext);601 controller.SetCurrentUser(user);602 TestUtility.SetupUrlHelper(controller, httpContext);603 ActionResult result = controller.ReportAbuse("Mordor", "2.0.1");604 Assert.IsType<RedirectToRouteResult>(result);605 Assert.Equal("ReportMyPackage", ((RedirectToRouteResult)result).RouteValues["Action"]);606 }607 [Fact]608 public void HtmlEncodesMessageContent()609 {610 var messageService = new Mock<IMessageService>();611 messageService.Setup(612 s => s.ReportAbuse(It.Is<ReportPackageRequest>(r => r.Message == "Mordor took my finger")));613 var package = new Package614 {615 PackageRegistration = new PackageRegistration { Id = "mordor" },616 Version = "2.0.1"617 };618 var packageService = new Mock<IPackageService>();619 packageService.Setup(p => p.FindPackageByIdAndVersion("mordor", "2.0.1", true)).Returns(package);620 var httpContext = new Mock<HttpContextBase>();621 httpContext.Setup(h => h.Request.IsAuthenticated).Returns(false);622 var controller = CreateController(623 packageService: packageService,624 messageService: messageService,625 httpContext: httpContext);626 var model = new ReportAbuseViewModel627 {628 Email = "frodo@hobbiton.example.com",629 Message = "I like the cut of your jib. It's <b>bold</b>.",630 Reason = ReportPackageReason.IsFraudulent,631 AlreadyContactedOwner = true,632 };633 TestUtility.SetupUrlHelper(controller, httpContext);634 controller.ReportAbuse("mordor", "2.0.1", model);635 messageService.Verify(636 s => s.ReportAbuse(637 It.Is<ReportPackageRequest>(638 r => r.FromAddress.Address == "frodo@hobbiton.example.com"639 && r.Package == package640 && r.Reason == EnumHelper.GetDescription(ReportPackageReason.IsFraudulent)641 && r.Message == "I like the cut of your jib. It's <b>bold</b>."642 && r.AlreadyContactedOwners)));643 }644 }645 public class TheReportMyPackageMethod646 {647 [Fact]648 public void FormRedirectsNonOwnersToReportAbuse()649 {650 var package = new Package651 {652 PackageRegistration = new PackageRegistration { Id = "Mordor", Owners = { new User { Username = "Sauron", Key = 1 } } },653 Version = "2.0.1"654 };655 var user = new User { EmailAddress = "frodo@hobbiton.example.com", Username = "Frodo", Key = 2 };656 var packageService = new Mock<IPackageService>();657 packageService.Setup(p => p.FindPackageByIdAndVersion("Mordor", It.IsAny<string>(), true)).Returns(package);658 var httpContext = new Mock<HttpContextBase>();659 var controller = CreateController(660 packageService: packageService,661 httpContext: httpContext);662 controller.SetCurrentUser(user);663 TestUtility.SetupUrlHelper(controller, httpContext);664 ActionResult result = controller.ReportMyPackage("Mordor", "2.0.1");665 Assert.IsType<RedirectToRouteResult>(result);666 Assert.Equal("ReportAbuse", ((RedirectToRouteResult)result).RouteValues["Action"]);667 }668 [Fact]669 public void HtmlEncodesMessageContent()670 {671 var user = new User { Username = "Sauron", Key = 1, EmailAddress = "sauron@mordor.example.com" };672 var package = new Package673 {674 PackageRegistration = new PackageRegistration { Id = "mordor", Owners = { user } },675 Version = "2.0.1"676 };677 var packageService = new Mock<IPackageService>();678 packageService.Setup(p => p.FindPackageByIdAndVersion("mordor", "2.0.1", true)).Returns(package);679 ReportPackageRequest reportRequest = null;680 var messageService = new Mock<IMessageService>();681 messageService682 .Setup(s => s.ReportMyPackage(It.IsAny<ReportPackageRequest>()))683 .Callback<ReportPackageRequest>(r => reportRequest = r);684 var httpContext = new Mock<HttpContextBase>();685 var controller = CreateController(686 packageService: packageService,687 messageService: messageService,688 httpContext: httpContext);689 controller.SetCurrentUser(user);690 var model = new ReportAbuseViewModel691 {692 Email = "frodo@hobbiton.example.com",693 Message = "I like the cut of your jib. It's <b>bold</b>.",694 Reason = ReportPackageReason.IsFraudulent,695 AlreadyContactedOwner = true,696 };697 TestUtility.SetupUrlHelper(controller, httpContext);...
CodePackageActivationContextStubs.cs
Source:CodePackageActivationContextStubs.cs
1// ------------------------------------------------------------2// Copyright (c) Microsoft Corporation. All rights reserved.3// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.4// ------------------------------------------------------------5namespace System.Fabric.Test.Stubs6{7 using System;8 using System.Collections.Generic;9 using System.Fabric.Interop;10 using System.Linq;11 using System.Runtime.InteropServices;12 using Microsoft.VisualStudio.TestTools.UnitTesting;13 using System.Fabric.Description;14 #region Native Stubs/Wrappers/Helpers15 /// <summary>16 /// Wrapper for the native ICodePackageActivationContext object17 /// </summary>18 class CodePackageActivationContextStub : NativeRuntime.IFabricCodePackageActivationContext619 {20 private readonly RegistrationTracker<NativeRuntime.IFabricCodePackageChangeHandler> codePackageRegistrations = new RegistrationTracker<NativeRuntime.IFabricCodePackageChangeHandler>();21 private readonly RegistrationTracker<NativeRuntime.IFabricConfigurationPackageChangeHandler> configPackageRegistrations = new RegistrationTracker<NativeRuntime.IFabricConfigurationPackageChangeHandler>();22 private readonly RegistrationTracker<NativeRuntime.IFabricDataPackageChangeHandler> dataPackageRegistrations = new RegistrationTracker<NativeRuntime.IFabricDataPackageChangeHandler>();23 public CodePackageActivationContextStub()24 {25 this.ServiceManifestInfo_Internal = new ServiceManifestInfo();26 }27 public string ListenAddress_Internal { get; set; }28 public string PublishAddress_Internal { get; set; }29 public string ApplicationTypeName_Internal { get; set; }30 public string ApplicationName_Internal { get; set; }31 public string CodePackageName_Internal { get; set; }32 public string CodePackageVersion_Internal { get; set; }33 public string ContextId_Internal { get; set; }34 public string LogDirectory_Internal { get; set; }35 public string WorkDirectory_Internal { get; set; }36 public string TempDirectory_Internal { get; set; }37 public ServiceManifestInfo ServiceManifestInfo_Internal { get; set; }38 public IList<NativeRuntime.IFabricCodePackageChangeHandler> CodePackageRegistrations39 {40 get41 {42 return this.codePackageRegistrations.Registrations;43 }44 }45 public IList<NativeRuntime.IFabricDataPackageChangeHandler> DataPackageRegistrations46 {47 get48 {49 return this.dataPackageRegistrations.Registrations;50 }51 }52 public IList<NativeRuntime.IFabricConfigurationPackageChangeHandler> ConfigPackageRegistrations53 {54 get55 {56 return this.configPackageRegistrations.Registrations;57 }58 }59 public IntPtr get_CodePackageName()60 {61 return Marshal.StringToCoTaskMemUni(this.CodePackageName_Internal);62 }63 public IntPtr get_CodePackageVersion()64 {65 return Marshal.StringToCoTaskMemUni(this.CodePackageVersion_Internal);66 }67 public IntPtr get_ContextId()68 {69 return Marshal.StringToCoTaskMemUni(this.ContextId_Internal);70 }71 public NativeCommon.IFabricStringListResult GetCodePackageNames()72 {73 List<string> strings = new List<string>();74 foreach (CodePackageInfo info in this.ServiceManifestInfo_Internal.CodePackages)75 {76 strings.Add(info.Name);77 }78 return new StringListResult(strings);79 }80 public NativeCommon.IFabricStringListResult GetConfigurationPackageNames()81 {82 List<string> strings = new List<string>();83 foreach (ConfigurationPackageInfo info in this.ServiceManifestInfo_Internal.ConfigurationPackages)84 {85 strings.Add(info.Name);86 }87 return new StringListResult(strings);88 }89 public NativeCommon.IFabricStringListResult GetDataPackageNames()90 {91 List<string> strings = new List<string>();92 foreach (DataPackageInfo info in this.ServiceManifestInfo_Internal.DataPackages)93 {94 strings.Add(info.Name);95 }96 return new StringListResult(strings);97 }98 public NativeRuntime.IFabricCodePackage GetCodePackage(IntPtr codePackageName)99 {100 var elem = this.ServiceManifestInfo_Internal.CodePackages.FirstOrDefault(cp => cp.Name == Marshal.PtrToStringUni(codePackageName));101 Assert.IsNotNull(elem, "This implies something in the test is broken");102 return elem;103 }104 public NativeRuntime.IFabricConfigurationPackage GetConfigurationPackage(IntPtr configurationPackageName)105 {106 var elem = this.ServiceManifestInfo_Internal.ConfigurationPackages.FirstOrDefault(cp => cp.Name == Marshal.PtrToStringUni(configurationPackageName));107 Assert.IsNotNull(elem, "This implies something in the test is broken");108 return elem;109 }110 public NativeRuntime.IFabricDataPackage GetDataPackage(IntPtr dataPackageName)111 {112 var elem = this.ServiceManifestInfo_Internal.DataPackages.FirstOrDefault(cp => cp.Name == Marshal.PtrToStringUni(dataPackageName));113 Assert.IsNotNull(elem, "This implies something in the test is broken");114 return elem;115 }116 public IntPtr get_ServiceTypes()117 {118 if (this.ServiceManifestInfo_Internal == null || this.ServiceManifestInfo_Internal.ServiceTypes == null)119 {120 return IntPtr.Zero;121 }122 return TestUtility.StructureToIntPtr(this.ServiceManifestInfo_Internal.ServiceTypes.ToNative());123 }124 public IntPtr get_ServiceGroupTypes()125 {126 if (this.ServiceManifestInfo_Internal == null || this.ServiceManifestInfo_Internal.ServiceGroupTypes == null)127 {128 return IntPtr.Zero;129 }130 return TestUtility.StructureToIntPtr(this.ServiceManifestInfo_Internal.ServiceGroupTypes.ToNative());131 }132 public IntPtr get_ApplicationPrincipals()133 {134 Assert.Fail("CodePackageActivationContextStub.get_ApplicationPrincipals not implemented");135 return IntPtr.Zero;136 }137 public IntPtr get_ServiceEndpointResources()138 {139 if (this.ServiceManifestInfo_Internal == null || this.ServiceManifestInfo_Internal.Endpoints == null)140 {141 return IntPtr.Zero;142 }143 return TestUtility.StructureToIntPtr(this.ServiceManifestInfo_Internal.Endpoints.ToNative());144 }145 public IntPtr GetServiceEndpointResource(IntPtr endpointName)146 {147 Assert.Fail("CodePackageActivationContextStub.GetServiceEndpointResource not implemented");148 return IntPtr.Zero;149 }150 public IntPtr get_LogDirectory()151 {152 return Marshal.StringToCoTaskMemUni(this.LogDirectory_Internal);153 }154 public IntPtr GetServiceManifestDescription()155 {156 if (this.ServiceManifestInfo_Internal == null)157 {158 return IntPtr.Zero;159 }160 return this.ServiceManifestInfo_Internal.ToNative();161 }162 public IntPtr get_WorkDirectory()163 {164 return Marshal.StringToCoTaskMemUni(this.WorkDirectory_Internal);165 }166 public IntPtr get_TempDirectory()167 {168 return Marshal.StringToCoTaskMemUni(this.TempDirectory_Internal);169 }170 public long RegisterCodePackageChangeHandler(NativeRuntime.IFabricCodePackageChangeHandler callback)171 {172 return this.codePackageRegistrations.Add(callback);173 }174 public long RegisterConfigurationPackageChangeHandler(NativeRuntime.IFabricConfigurationPackageChangeHandler callback)175 {176 return this.configPackageRegistrations.Add(callback);177 }178 public long RegisterDataPackageChangeHandler(NativeRuntime.IFabricDataPackageChangeHandler callback)179 {180 return this.dataPackageRegistrations.Add(callback);181 }182 public void UnregisterCodePackageChangeHandler(long callbackHandle)183 {184 this.codePackageRegistrations.Remove(callbackHandle);185 }186 public void UnregisterConfigurationPackageChangeHandler(long callbackHandle)187 {188 this.configPackageRegistrations.Remove(callbackHandle);189 }190 public void UnregisterDataPackageChangeHandler(long callbackHandle)191 {192 this.dataPackageRegistrations.Remove(callbackHandle);193 }194 public IntPtr get_ApplicationName()195 {196 return Marshal.StringToCoTaskMemUni(this.ApplicationName_Internal);197 }198 public IntPtr get_ApplicationTypeName()199 {200 return Marshal.StringToCoTaskMemUni(this.ApplicationTypeName_Internal);201 }202 public NativeCommon.IFabricStringResult GetServiceManifestName()203 {204 return new StringResult(this.ServiceManifestInfo_Internal.Name);205 }206 public NativeCommon.IFabricStringResult GetServiceManifestVersion()207 {208 return new StringResult(this.ServiceManifestInfo_Internal.Version);209 }210 public void ReportApplicationHealth(IntPtr healthInfo)211 {212 Assert.Fail("CodePackageActivationContextStub.ReportApplicationHealth not implemented");213 }214 public void ReportApplicationHealth2(IntPtr healthInfo, IntPtr sendOptions)215 {216 Assert.Fail("CodePackageActivationContextStub.ReportApplicationHealth2 not implemented");217 }218 219 public void ReportDeployedApplicationHealth(IntPtr healthInfo)220 {221 Assert.Fail("CodePackageActivationContextStub.ReportDeployedApplicationHealth not implemented");222 }223 public void ReportDeployedApplicationHealth2(IntPtr healthInfo, IntPtr sendOptions)224 {225 Assert.Fail("CodePackageActivationContextStub.ReportDeployedApplicationHealth2 not implemented");226 }227 public void ReportDeployedServicePackageHealth(IntPtr healthInfo)228 {229 Assert.Fail("CodePackageActivationContextStub.ReportDeployedServicePackageHealth not implemented");230 }231 public void ReportDeployedServicePackageHealth2(IntPtr healthInfo, IntPtr sendOptions)232 {233 Assert.Fail("CodePackageActivationContextStub.ReportDeployedServicePackageHealth2 not implemented");234 }235 public NativeCommon.IFabricStringResult GetDirectory(IntPtr logicalDirectoryName)236 {237 return new StringResult(this.WorkDirectory_Internal);238 }239 public IntPtr get_ServiceListenAddress()240 {241 return Marshal.StringToCoTaskMemUni(this.ListenAddress_Internal);242 }243 public IntPtr get_ServicePublishAddress()244 {245 return Marshal.StringToCoTaskMemUni(this.PublishAddress_Internal);246 }247 private class RegistrationTracker<T>248 {249 private readonly Dictionary<long, T> registrations = new Dictionary<long, T>();250 private long index = 0;251 public IList<T> Registrations252 {253 get254 {255 return new List<T>(this.registrations.Values);256 }257 }258 public long Add(T obj)259 {260 long handle = this.index++;261 this.registrations[handle] = obj;262 return handle;263 }264 public void Remove(long index)265 {266 this.registrations.Remove(index);267 }268 }269 }270 #region Wrappers for handling the native structs271 /// <summary>272 /// An interface that defines serializability for all the native objects273 /// </summary>274 interface INativeWrapper275 {276 int Size { get; }277 object ToNative();278 }279 /// <summary>280 /// Helper class implementation281 /// </summary>282 abstract class NativeWrapperBase<T> : INativeWrapper283 {284 public int Size285 {286 get { return Marshal.SizeOf(typeof(T)); }287 }288 public object ToNative()289 {290 return (object)this.ToNativeRaw();291 }292 public abstract T ToNativeRaw();293 }294 interface INativeCollectionWrapper : INativeWrapper295 {296 bool ReturnNullIfEmpty { get; set; }297 void Clear();298 }299 /// <summary>300 /// Helper class that wraps the *_LIST structures301 /// It assumes that the children are of TElement (INativeWrapper) and contains a collection of them302 /// The ToNative method then returns the _LIST structure allocating all the items as per the native code303 /// </summary>304 class NativeContainer<TContainer, TElement> : INativeCollectionWrapper, ICollection<TElement>305 where TContainer : new()306 where TElement : INativeWrapper307 {308 private Func<uint, IntPtr, TContainer> containerFactory;309 private IList<TElement> children;310 public NativeContainer(Func<uint, IntPtr, TContainer> containerFactory)311 {312 this.containerFactory = containerFactory;313 this.children = new List<TElement>();314 }315 public bool ReturnNullIfEmpty { get; set; }316 public int Size317 {318 get { return Marshal.SizeOf(typeof(TContainer)); }319 }320 public unsafe object ToNative()321 {322 if (this.children.Count == 0 && this.ReturnNullIfEmpty)323 {324 return null;325 }326 uint count = (uint)this.children.Count;327 IntPtr childrenBuffer = IntPtr.Zero;328 if (this.children.Count != 0)329 {330 int elementSize = this.children[0].Size;331 childrenBuffer = Marshal.AllocHGlobal(elementSize * this.children.Count);332 for (int i = 0; i < this.children.Count; i++)333 {334 IntPtr ptr = childrenBuffer + elementSize * i;335 Marshal.StructureToPtr(this.children[i].ToNative(), ptr, false);336 }337 }338 return this.containerFactory(count, childrenBuffer);339 }340 public IEnumerator<TElement> GetEnumerator()341 {342 return this.children.GetEnumerator();343 }344 Collections.IEnumerator Collections.IEnumerable.GetEnumerator()345 {346 return this.children.GetEnumerator();347 }348 public void Add(TElement item)349 {350 this.children.Add(item);351 }352 public void Clear()353 {354 this.children.Clear();355 }356 public bool Contains(TElement item)357 {358 return this.children.Contains(item);359 }360 public void CopyTo(TElement[] array, int arrayIndex)361 {362 throw new NotImplementedException();363 }364 public int Count365 {366 get { return this.children.Count; }367 }368 public bool IsReadOnly369 {370 get { throw new NotImplementedException(); }371 }372 public bool Remove(TElement item)373 {374 throw new NotImplementedException();375 }376 }377 #endregion378 class StringResult : NativeCommon.IFabricStringResult379 {380 string Value { get; set; }381 IntPtr valuePtr;382 unsafe public StringResult(string value)383 {384 this.Value = value;385 this.valuePtr = Marshal.StringToCoTaskMemUni(this.Value);386 }387 unsafe public IntPtr get_String()388 {389 return this.valuePtr;390 }391 }392 class StringListResult : NativeCommon.IFabricStringListResult393 {394 private List<string> strings { get; set; }395 IntPtr[] stringsPtr;396 unsafe public StringListResult(List<string> strings)397 {398 this.strings = strings;399 this.stringsPtr = new IntPtr[this.strings.Count];400 for (int i = 0; i < this.strings.Count; i++)401 {402 stringsPtr[i] = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(IntPtr)));403 Marshal.WriteIntPtr(stringsPtr[i], Marshal.StringToCoTaskMemUni(this.strings[i]));404 }405 }406 unsafe public IntPtr GetStrings(out UInt32 itemCount)407 {408 itemCount = (UInt32)strings.Count;409 if (itemCount > 0)410 {411 return stringsPtr[0];412 }413 else414 {415 return IntPtr.Zero;416 }417 }418 }419 /// <summary>420 /// Wrapper for FABRIC_ENDPOINT_RESOURCE_DESCRIPTION421 /// </summary>422 class EndPointInfo : NativeWrapperBase<NativeTypes.FABRIC_ENDPOINT_RESOURCE_DESCRIPTION>423 {424 public string Name { get; set; }425 public string Protocol { get; set; }426 public string Type { get; set; }427 public UInt32 Port { get; set; }428 public string CertificateName { get; set; }429 public string UriScheme { get; set; }430 public string PathSuffix { get; set; }431 private NativeTypes.FABRIC_ENDPOINT_RESOURCE_DESCRIPTION_EX1 _additions;432 public override NativeTypes.FABRIC_ENDPOINT_RESOURCE_DESCRIPTION ToNativeRaw()433 {434 IntPtr reserved = IntPtr.Zero;435 if (!String.IsNullOrEmpty(UriScheme) ||436 !String.IsNullOrEmpty(PathSuffix))437 {438 _additions.PathSuffix = Marshal.StringToCoTaskMemUni(PathSuffix);439 _additions.UriScheme = Marshal.StringToCoTaskMemUni(UriScheme);440 }441 return new NativeTypes.FABRIC_ENDPOINT_RESOURCE_DESCRIPTION442 {443 CertificateName = Marshal.StringToCoTaskMemUni(this.CertificateName),444 Name = Marshal.StringToCoTaskMemUni(this.Name),445 Port = this.Port,446 Protocol = Marshal.StringToCoTaskMemUni(this.Protocol),447 Type = Marshal.StringToCoTaskMemUni(this.Type),448 Reserved = TestUtility.StructureToIntPtr(_additions)449 };450 }451 }452 #region Packages453 class DllHostItemInfo : NativeWrapperBase<NativeTypes.FABRIC_DLLHOST_HOSTED_DLL_DESCRIPTION>454 {455 public NativeTypes.FABRIC_DLLHOST_HOSTED_DLL_KIND Type { get; set; }456 public string Item { get; set; }457 public override NativeTypes.FABRIC_DLLHOST_HOSTED_DLL_DESCRIPTION ToNativeRaw()458 {459 object value = null;460 if (this.Type == NativeTypes.FABRIC_DLLHOST_HOSTED_DLL_KIND.FABRIC_DLLHOST_HOSTED_DLL_KIND_MANAGED)461 {462 value = new NativeTypes.FABRIC_DLLHOST_HOSTED_MANAGED_DLL_DESCRIPTION463 {464 AssemblyName = Marshal.StringToCoTaskMemUni(this.Item)465 };466 }467 else468 {469 value = new NativeTypes.FABRIC_DLLHOST_HOSTED_UNMANAGED_DLL_DESCRIPTION470 {471 DllName = Marshal.StringToCoTaskMemUni(this.Item)472 };473 }474 return new NativeTypes.FABRIC_DLLHOST_HOSTED_DLL_DESCRIPTION475 {476 Kind = this.Type,477 Value = value == null ? IntPtr.Zero : TestUtility.StructureToIntPtr(value)478 };479 }480 }481 class DllHostEntryPointInfo : NativeWrapperBase<NativeTypes.FABRIC_DLLHOST_ENTRY_POINT_DESCRIPTION>482 {483 public NativeTypes.FABRIC_DLLHOST_ISOLATION_POLICY IsolationPolicyType { get; set; }484 public NativeContainer<NativeTypes.FABRIC_DLLHOST_HOSTED_DLL_DESCRIPTION_LIST, DllHostItemInfo> HostedDlls { get; private set; }485 public DllHostEntryPointInfo()486 {487 this.IsolationPolicyType = NativeTypes.FABRIC_DLLHOST_ISOLATION_POLICY.FABRIC_DLLHOST_ISOLATION_POLICY_DEDICATED_PROCESS;488 this.HostedDlls = new NativeContainer<NativeTypes.FABRIC_DLLHOST_HOSTED_DLL_DESCRIPTION_LIST,DllHostItemInfo>(489 (count, buffer) => new NativeTypes.FABRIC_DLLHOST_HOSTED_DLL_DESCRIPTION_LIST { Count = count, Items = buffer });490 }491 public override NativeTypes.FABRIC_DLLHOST_ENTRY_POINT_DESCRIPTION ToNativeRaw()492 {493 return new NativeTypes.FABRIC_DLLHOST_ENTRY_POINT_DESCRIPTION494 {495 IsolationPolicyType = this.IsolationPolicyType,496 HostedDlls = TestUtility.StructureToIntPtr(this.HostedDlls.ToNative())497 };498 }499 }500 class ExecutableEntryPointInfo : NativeWrapperBase<NativeTypes.FABRIC_EXEHOST_ENTRY_POINT_DESCRIPTION>501 {502 public string Program { get; set; }503 public string Arguments { get; set; }504 public NativeTypes.FABRIC_EXEHOST_WORKING_FOLDER WorkingFolder { get; set; }505 public UInt32 PeriodicIntervalInSeconds { get; set; }506 public override NativeTypes.FABRIC_EXEHOST_ENTRY_POINT_DESCRIPTION ToNativeRaw()507 {508 return new NativeTypes.FABRIC_EXEHOST_ENTRY_POINT_DESCRIPTION509 {510 Program = Marshal.StringToCoTaskMemUni(this.Program),511 Arguments = Marshal.StringToCoTaskMemUni(this.Arguments),512 WorkingFolder = this.WorkingFolder,513 Reserved = TestUtility.StructureToIntPtr(new NativeTypes.FABRIC_EXEHOST_ENTRY_POINT_DESCRIPTION_EX1 { PeriodicIntervalInSeconds = this.PeriodicIntervalInSeconds })514 };515 }516 }517 class EntryPointInfo : NativeWrapperBase<NativeTypes.FABRIC_CODE_PACKAGE_ENTRY_POINT_DESCRIPTION>518 {519 public object Description { get; set; } 520 public T GetDescription<T>() where T : class521 {522 return Description as T;523 }524 public IntPtr GetNativeDescription()525 {526 var exe = this.GetDescription<ExecutableEntryPointInfo>();527 var fabricHost = this.GetDescription<DllHostEntryPointInfo>();528 if (exe != null)529 {530 return TestUtility.StructureToIntPtr(exe.ToNative());531 }532 if (fabricHost != null)533 {534 return TestUtility.StructureToIntPtr(fabricHost.ToNative());535 }536 return IntPtr.Zero;537 }538 public NativeTypes.FABRIC_CODE_PACKAGE_ENTRY_POINT_KIND Type539 {540 get541 {542 if (this.Description == null)543 {544 return NativeTypes.FABRIC_CODE_PACKAGE_ENTRY_POINT_KIND.FABRIC_CODE_PACKAGE_ENTRY_POINT_KIND_NONE;545 }546 if (this.GetDescription<ExecutableEntryPointInfo>() != null)547 {548 return NativeTypes.FABRIC_CODE_PACKAGE_ENTRY_POINT_KIND.FABRIC_CODE_PACKAGE_ENTRY_POINT_KIND_EXEHOST;549 }550 if (this.GetDescription<DllHostEntryPointInfo>() != null)551 {552 return NativeTypes.FABRIC_CODE_PACKAGE_ENTRY_POINT_KIND.FABRIC_CODE_PACKAGE_ENTRY_POINT_KIND_DLLHOST;553 }554 return NativeTypes.FABRIC_CODE_PACKAGE_ENTRY_POINT_KIND.FABRIC_CODE_PACKAGE_ENTRY_POINT_KIND_INVALID;555 }556 }557 public override NativeTypes.FABRIC_CODE_PACKAGE_ENTRY_POINT_DESCRIPTION ToNativeRaw()558 {559 return new NativeTypes.FABRIC_CODE_PACKAGE_ENTRY_POINT_DESCRIPTION560 {561 Kind = this.Type,562 Value = this.GetNativeDescription()563 };564 }565 }566 /// <summary>567 /// Base interface for dealing with packages in test code568 /// </summary>569 interface IPackageInfo570 {571 string Name { get; }572 string PathProperty { get; }573 string Version { get; set; }574 }575 /// <summary>576 /// FABRIC_CODE_PACKAGE_DESCRIPTION and NativeRuntime.IFabricCodePackage577 /// </summary>578 class CodePackageInfo : NativeWrapperBase<NativeTypes.FABRIC_CODE_PACKAGE_DESCRIPTION>, 579 NativeRuntime.IFabricCodePackage2,580 IPackageInfo581 {582 public ExecutableEntryPointInfo SetupEntryPoint { get; set; }583 public EntryPointInfo EntryPoint { get; set; }584 public string PathProperty { get; set; }585 public string Name { get; set; }586 public string Version { get; set; }587 public string ServiceManifestName { get; set; }588 public string ServiceManifestVersion { get; set; }589 public bool IsShared { get; set; }590 591 public IntPtr get_Description()592 {593 return TestUtility.StructureToIntPtr(this.ToNativeRaw());594 }595 public IntPtr get_Path()596 {597 return Marshal.StringToCoTaskMemUni(this.PathProperty);598 }599 public IntPtr get_EntryPointRunAsPolicy()600 {601 return IntPtr.Zero;602 }603 public IntPtr get_SetupEntryPointRunAsPolicy()604 {605 return IntPtr.Zero;606 }607 public override NativeTypes.FABRIC_CODE_PACKAGE_DESCRIPTION ToNativeRaw()608 {609 return new NativeTypes.FABRIC_CODE_PACKAGE_DESCRIPTION610 {611 SetupEntryPoint = this.SetupEntryPoint == null? IntPtr.Zero : TestUtility.StructureToIntPtr(this.SetupEntryPoint.ToNative()),612 EntryPoint = this.EntryPoint == null ? IntPtr.Zero : TestUtility.StructureToIntPtr(this.EntryPoint.ToNative()),613 IsShared = NativeTypes.ToBOOLEAN(this.IsShared),614 Name = Marshal.StringToCoTaskMemUni(this.Name),615 Version = Marshal.StringToCoTaskMemUni(this.Version),616 ServiceManifestName = Marshal.StringToCoTaskMemUni(this.ServiceManifestName),617 ServiceManifestVersion = Marshal.StringToCoTaskMemUni(this.ServiceManifestVersion),618 }; 619 }620 }621 /// <summary>622 /// FABRIC_DATA_PACKAGE_DESCRIPTION and NativeRuntime.IFabricDataPackage623 /// </summary>624 class DataPackageInfo : NativeWrapperBase<NativeTypes.FABRIC_DATA_PACKAGE_DESCRIPTION>, NativeRuntime.IFabricDataPackage, IPackageInfo625 {626 public string Name { get; set; }627 public string PathProperty { get; set; }628 public string Version { get; set; }629 public string ServiceManifestName { get; set; }630 public string ServiceManifestVersion { get; set; }631 public IntPtr get_Description()632 {633 return TestUtility.StructureToIntPtr(this.ToNative());634 }635 public IntPtr get_Path()636 {637 return Marshal.StringToCoTaskMemUni(this.PathProperty);638 }639 public override NativeTypes.FABRIC_DATA_PACKAGE_DESCRIPTION ToNativeRaw()640 {641 return new NativeTypes.FABRIC_DATA_PACKAGE_DESCRIPTION642 {643 Name = Marshal.StringToCoTaskMemUni(this.Name),644 Version = Marshal.StringToCoTaskMemUni(this.Version),645 ServiceManifestName = Marshal.StringToCoTaskMemUni(this.ServiceManifestName),646 ServiceManifestVersion = Marshal.StringToCoTaskMemUni(this.ServiceManifestVersion),647 };648 }649 }650 class ConfigurationParameterInfo : NativeWrapperBase<NativeTypes.FABRIC_CONFIGURATION_PARAMETER>651 {652 public string Name { get; set; }653 public string Value { get; set; }654 public override NativeTypes.FABRIC_CONFIGURATION_PARAMETER ToNativeRaw()655 {656 return new NativeTypes.FABRIC_CONFIGURATION_PARAMETER657 {658 Name = Marshal.StringToCoTaskMemUni(this.Name),659 Value = Marshal.StringToCoTaskMemUni(this.Value),660 };661 }662 }663 class ConfigurationSectionInfo : NativeWrapperBase<NativeTypes.FABRIC_CONFIGURATION_SECTION>664 {665 public string SectionName { get; set; }666 public NativeContainer<NativeTypes.FABRIC_CONFIGURATION_PARAMETER_LIST, ConfigurationParameterInfo> Parameters { get; private set; }667 public ConfigurationSectionInfo()668 {669 this.Parameters = new NativeContainer<NativeTypes.FABRIC_CONFIGURATION_PARAMETER_LIST, ConfigurationParameterInfo>(670 (count, buffer) => new NativeTypes.FABRIC_CONFIGURATION_PARAMETER_LIST { Count = count, Items = buffer });671 }672 public override NativeTypes.FABRIC_CONFIGURATION_SECTION ToNativeRaw()673 {674 return new NativeTypes.FABRIC_CONFIGURATION_SECTION675 {676 Name = Marshal.StringToCoTaskMemUni(this.SectionName),677 Parameters = TestUtility.StructureToIntPtr(this.Parameters.ToNative()),678 };679 }680 }681 class ConfigurationSettingsInfo : NativeWrapperBase<NativeTypes.FABRIC_CONFIGURATION_SETTINGS>682 {683 public NativeContainer<NativeTypes.FABRIC_CONFIGURATION_SECTION_LIST, ConfigurationSectionInfo> Sections { get; private set; }684 public ConfigurationSettingsInfo()685 {686 this.Sections = new NativeContainer<NativeTypes.FABRIC_CONFIGURATION_SECTION_LIST, ConfigurationSectionInfo>(687 (count, buffer) => new NativeTypes.FABRIC_CONFIGURATION_SECTION_LIST { Count = count, Items = buffer });688 }689 public override NativeTypes.FABRIC_CONFIGURATION_SETTINGS ToNativeRaw()690 {691 return new NativeTypes.FABRIC_CONFIGURATION_SETTINGS692 {693 Sections = TestUtility.StructureToIntPtr(this.Sections.ToNative()),694 };695 }696 }697 class ConfigurationPackageInfo : NativeWrapperBase<NativeTypes.FABRIC_CONFIGURATION_PACKAGE_DESCRIPTION>, NativeRuntime.IFabricConfigurationPackage, IPackageInfo698 {699 public string Name { get; set; }700 public string PathProperty { get; set; }701 public string Version { get; set; }702 public string ServiceManifestName { get; set; }703 public string ServiceManifestVersion { get; set; }704 public ConfigurationSettingsInfo SettingsProperty { get; set; }705 public ConfigurationPackageInfo()706 {707 this.SettingsProperty = new ConfigurationSettingsInfo();708 }709 public IntPtr get_Description()710 {711 return TestUtility.StructureToIntPtr(this.ToNative());712 }713 public IntPtr get_Path()714 {715 return Marshal.StringToCoTaskMemUni(this.PathProperty);716 }717 public IntPtr get_Settings()718 {719 return TestUtility.StructureToIntPtr(this.SettingsProperty.ToNative());720 }721 public IntPtr GetSection(IntPtr sectionName)722 {723 return TestUtility.StructureToIntPtr(this.SettingsProperty.Sections.First(s => s.SectionName == NativeTypes.FromNativeString(sectionName)).ToNative());724 }725 public IntPtr GetValue(IntPtr sectionName, IntPtr parameterName)726 {727 return Marshal.StringToCoTaskMemUni(this.SettingsProperty.Sections.First(s => s.SectionName == NativeTypes.FromNativeString(sectionName)).Parameters.First(p => p.Name == NativeTypes.FromNativeString(parameterName)).Value);728 }729 public override NativeTypes.FABRIC_CONFIGURATION_PACKAGE_DESCRIPTION ToNativeRaw()730 {731 return new NativeTypes.FABRIC_CONFIGURATION_PACKAGE_DESCRIPTION732 {733 Name = Marshal.StringToCoTaskMemUni(this.Name),734 Version = Marshal.StringToCoTaskMemUni(this.Version),735 ServiceManifestName = Marshal.StringToCoTaskMemUni(this.ServiceManifestName),736 ServiceManifestVersion = Marshal.StringToCoTaskMemUni(this.ServiceManifestVersion),737 };738 }739 }740 #endregion741 #region ServiceTypes742 class DescriptionExtensionInfo : NativeWrapperBase<NativeTypes.FABRIC_SERVICE_TYPE_DESCRIPTION_EXTENSION>743 {744 public string Name { get; set; }745 public string Value { get; set; }746 public override NativeTypes.FABRIC_SERVICE_TYPE_DESCRIPTION_EXTENSION ToNativeRaw()747 {748 return new NativeTypes.FABRIC_SERVICE_TYPE_DESCRIPTION_EXTENSION749 {750 Name = Marshal.StringToCoTaskMemUni(this.Name),751 Value = Marshal.StringToCoTaskMemAuto(this.Value),752 };753 }754 }755 class ServiceLoadMetricInfo : NativeWrapperBase<NativeTypes.FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION>756 {757 public string Name { get; set; }758 public NativeTypes.FABRIC_SERVICE_LOAD_METRIC_WEIGHT Weight { get; set; }759 public uint PrimaryDefaultLoad { get; set; }760 public uint SecondaryDefaultLoad { get; set; }761 public override NativeTypes.FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION ToNativeRaw()762 {763 return new NativeTypes.FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION764 {765 PrimaryDefaultLoad = this.PrimaryDefaultLoad,766 SecondaryDefaultLoad = this.SecondaryDefaultLoad,767 Name = Marshal.StringToCoTaskMemUni(this.Name),768 Weight = this.Weight769 };770 }771 }772 class ServiceTypeInfo : NativeWrapperBase<NativeTypes.FABRIC_SERVICE_TYPE_DESCRIPTION>773 {774 public string ServiceTypeName { get; set; }775 public string PlacementConstraints { get; set; }776 public NativeContainer<NativeTypes.FABRIC_SERVICE_TYPE_DESCRIPTION_EXTENSION_LIST, DescriptionExtensionInfo> Extensions { get; private set; }777 public NativeContainer<NativeTypes.FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION_LIST, ServiceLoadMetricInfo> LoadMetrics { get; private set; }778 public ServiceTypeInfo()779 {780 this.Extensions = new NativeContainer<NativeTypes.FABRIC_SERVICE_TYPE_DESCRIPTION_EXTENSION_LIST, DescriptionExtensionInfo>(781 (count, buffer) => new NativeTypes.FABRIC_SERVICE_TYPE_DESCRIPTION_EXTENSION_LIST { Count = count, Items = buffer });782 this.LoadMetrics = new NativeContainer<NativeTypes.FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION_LIST, ServiceLoadMetricInfo>(783 (count, buffer) => new NativeTypes.FABRIC_SERVICE_LOAD_METRIC_DESCRIPTION_LIST { Count = count, Items = buffer });784 }785 protected virtual object ToNativeDerived(IntPtr serviceTypeName, IntPtr placementConstraints, IntPtr extensions, IntPtr loadMetrics)786 {787 return null;788 }789 public virtual NativeTypes.FABRIC_SERVICE_KIND Kind790 {791 get792 {793 return NativeTypes.FABRIC_SERVICE_KIND.FABRIC_SERVICE_KIND_INVALID;794 }795 }796 public override NativeTypes.FABRIC_SERVICE_TYPE_DESCRIPTION ToNativeRaw()797 {798 if (this.Kind == NativeTypes.FABRIC_SERVICE_KIND.FABRIC_SERVICE_KIND_INVALID)799 {800 return new NativeTypes.FABRIC_SERVICE_TYPE_DESCRIPTION801 {802 Kind = this.Kind,803 Value = IntPtr.Zero,804 };805 }806 else807 {808 return new NativeTypes.FABRIC_SERVICE_TYPE_DESCRIPTION809 {810 Kind = this.Kind,811 Value = TestUtility.StructureToIntPtr(this.ToNativeDerived()),812 };813 }814 }815 public object ToNativeDerived()816 {817 return this.ToNativeDerived(818 Marshal.StringToCoTaskMemUni(this.ServiceTypeName),819 Marshal.StringToCoTaskMemUni(this.PlacementConstraints),820 TestUtility.StructureToIntPtr(this.Extensions.ToNative()),821 TestUtility.StructureToIntPtr(this.LoadMetrics.ToNative()));822 }823 }824 class StatelessServiceTypeInfo : ServiceTypeInfo825 {826 public override NativeTypes.FABRIC_SERVICE_KIND Kind827 {828 get829 {830 return NativeTypes.FABRIC_SERVICE_KIND.FABRIC_SERVICE_KIND_STATELESS;831 }832 }833 protected override object ToNativeDerived(IntPtr serviceTypeName, IntPtr placementConstraints, IntPtr extensions, IntPtr loadMetrics)834 {835 return new NativeTypes.FABRIC_STATELESS_SERVICE_TYPE_DESCRIPTION836 {837 ServiceTypeName = serviceTypeName,838 PlacementConstraints = placementConstraints,839 Extensions = extensions,840 LoadMetrics = loadMetrics,841 };842 }843 }844 class StatefulServiceTypeInfo : ServiceTypeInfo845 {846 public bool HasPersistedState { get; set; }847 public override NativeTypes.FABRIC_SERVICE_KIND Kind848 {849 get850 {851 return NativeTypes.FABRIC_SERVICE_KIND.FABRIC_SERVICE_KIND_STATEFUL;852 }853 }854 protected override object ToNativeDerived(IntPtr serviceTypeName, IntPtr placementConstraints, IntPtr extensions, IntPtr loadMetrics)855 {856 return new NativeTypes.FABRIC_STATEFUL_SERVICE_TYPE_DESCRIPTION857 {858 ServiceTypeName = serviceTypeName,859 PlacementConstraints = placementConstraints,860 Extensions = extensions,861 HasPersistedState = NativeTypes.ToBOOLEAN(this.HasPersistedState),862 LoadMetrics = loadMetrics,863 };864 }865 }866 class ServiceGroupTypeMemberInfo : NativeWrapperBase<NativeTypes.FABRIC_SERVICE_GROUP_TYPE_MEMBER_DESCRIPTION>867 {868 public string ServiceTypeName { get; set; }869 public override NativeTypes.FABRIC_SERVICE_GROUP_TYPE_MEMBER_DESCRIPTION ToNativeRaw()870 {871 return new NativeTypes.FABRIC_SERVICE_GROUP_TYPE_MEMBER_DESCRIPTION872 {873 ServiceTypeName = Marshal.StringToCoTaskMemUni(this.ServiceTypeName)874 };875 }876 }877 class ServiceGroupTypeInfo : NativeWrapperBase<NativeTypes.FABRIC_SERVICE_GROUP_TYPE_DESCRIPTION>878 {879 public ServiceTypeInfo Description { get; set; }880 public string PlacementConstraints { get; set; }881 public bool UseImplicitFactory { get; set; }882 public NativeContainer<NativeTypes.FABRIC_SERVICE_GROUP_TYPE_MEMBER_DESCRIPTION_LIST, ServiceGroupTypeMemberInfo> Members { get; private set; }883 public ServiceGroupTypeInfo()884 {885 this.Members = new NativeContainer<NativeTypes.FABRIC_SERVICE_GROUP_TYPE_MEMBER_DESCRIPTION_LIST, ServiceGroupTypeMemberInfo>(886 (count, buffer) => new NativeTypes.FABRIC_SERVICE_GROUP_TYPE_MEMBER_DESCRIPTION_LIST { Count = count, Items = buffer });887 }888 public override NativeTypes.FABRIC_SERVICE_GROUP_TYPE_DESCRIPTION ToNativeRaw()889 {890 return new NativeTypes.FABRIC_SERVICE_GROUP_TYPE_DESCRIPTION891 {892 Description = TestUtility.StructureToIntPtr(this.Description.ToNativeRaw()),893 Members = TestUtility.StructureToIntPtr(this.Members.ToNative()),894 UseImplicitFactory = this.UseImplicitFactory ? (sbyte)1 : (sbyte)0895 };896 }897 }898 #endregion899 /// <summary>900 /// The service manifest901 /// </summary>902 class ServiceManifestInfo : NativeRuntime.IFabricServiceManifestDescriptionResult903 {904 public IntPtr get_Description()905 {906 return this.ToNative();907 }908 public NativeContainer<NativeTypes.FABRIC_ENDPOINT_RESOURCE_DESCRIPTION_LIST, EndPointInfo> Endpoints { get; private set; }909 public NativeContainer<NativeTypes.FABRIC_CODE_PACKAGE_DESCRIPTION_LIST, CodePackageInfo> CodePackages { get; private set; }910 public NativeContainer<NativeTypes.FABRIC_DATA_PACKAGE_DESCRIPTION_LIST, DataPackageInfo> DataPackages { get; private set; }911 public NativeContainer<NativeTypes.FABRIC_CONFIGURATION_PACKAGE_DESCRIPTION_LIST, ConfigurationPackageInfo> ConfigurationPackages { get; private set; }912 public NativeContainer<NativeTypes.FABRIC_SERVICE_TYPE_DESCRIPTION_LIST, ServiceTypeInfo> ServiceTypes { get; private set; }913 public NativeContainer<NativeTypes.FABRIC_SERVICE_GROUP_TYPE_DESCRIPTION_LIST, ServiceGroupTypeInfo> ServiceGroupTypes { get; private set; }914 public string Name { get; set; }915 public string Version { get; set; }916 public ServiceManifestInfo()917 {918 this.Endpoints = new NativeContainer<NativeTypes.FABRIC_ENDPOINT_RESOURCE_DESCRIPTION_LIST, EndPointInfo>(919 (count, buffer) => new NativeTypes.FABRIC_ENDPOINT_RESOURCE_DESCRIPTION_LIST { Count = count, Items = buffer });920 this.CodePackages = new NativeContainer<NativeTypes.FABRIC_CODE_PACKAGE_DESCRIPTION_LIST, CodePackageInfo>(921 (count, buffer) => new NativeTypes.FABRIC_CODE_PACKAGE_DESCRIPTION_LIST { Count = count, Items = buffer });922 this.DataPackages = new NativeContainer<NativeTypes.FABRIC_DATA_PACKAGE_DESCRIPTION_LIST, DataPackageInfo>(923 (count, buffer) => new NativeTypes.FABRIC_DATA_PACKAGE_DESCRIPTION_LIST { Count = count, Items = buffer });924 this.ConfigurationPackages = new NativeContainer<NativeTypes.FABRIC_CONFIGURATION_PACKAGE_DESCRIPTION_LIST, ConfigurationPackageInfo>(925 (count, buffer) => new NativeTypes.FABRIC_CONFIGURATION_PACKAGE_DESCRIPTION_LIST { Count = count, Items = buffer });926 this.ServiceTypes = new NativeContainer<NativeTypes.FABRIC_SERVICE_TYPE_DESCRIPTION_LIST, ServiceTypeInfo>(927 (count, buffer) => new NativeTypes.FABRIC_SERVICE_TYPE_DESCRIPTION_LIST { Count = count, Items = buffer });928 this.ServiceGroupTypes = new NativeContainer<NativeTypes.FABRIC_SERVICE_GROUP_TYPE_DESCRIPTION_LIST, ServiceGroupTypeInfo>(929 (count, buffer) => new NativeTypes.FABRIC_SERVICE_GROUP_TYPE_DESCRIPTION_LIST { Count = count, Items = buffer });930 }931 public unsafe IntPtr ToNative()932 {933 NativeTypes.FABRIC_SERVICE_MANIFEST_DESCRIPTION serviceManifestDescription = new NativeTypes.FABRIC_SERVICE_MANIFEST_DESCRIPTION();934 serviceManifestDescription.Endpoints = TestUtility.StructureToIntPtr(this.Endpoints.ToNative());935 serviceManifestDescription.CodePackages = TestUtility.StructureToIntPtr(this.CodePackages.ToNative());936 serviceManifestDescription.DataPackages = TestUtility.StructureToIntPtr(this.DataPackages.ToNative());937 serviceManifestDescription.ConfigurationPackages = TestUtility.StructureToIntPtr(this.ConfigurationPackages.ToNative());938 serviceManifestDescription.ServiceTypes = TestUtility.StructureToIntPtr(this.ServiceTypes.ToNative());939 serviceManifestDescription.ServiceGroupTypes = TestUtility.StructureToIntPtr(this.ServiceGroupTypes.ToNative());940 serviceManifestDescription.Name = Marshal.StringToCoTaskMemUni(this.Name);941 serviceManifestDescription.Version = Marshal.StringToCoTaskMemUni(this.Version);942 return TestUtility.StructureToIntPtr(serviceManifestDescription);943 }944 }945 #endregion946}...
WebSocketClientHelper.cs
Source:WebSocketClientHelper.cs
...179 }180 public void InitiateWithAlwaysReading()181 {182 Initiate();183 Connection.Stream.BeginRead(Connection.InputData, 0, Connection.InputData.Length, ReadDataCallback, Connection);184 IsAlwaysReading = true;185 }186 public void SendWebSocketRequest(int websocketVersion)187 {188 HandShakeRequest = Frames.GetHandShakeFrame(Address.AbsoluteUri, websocketVersion);189 190 byte[] outputData = null;191 int offset = 0;192 while (offset < HandShakeRequest.Length)193 {194 outputData = HandShakeRequest[offset++];195 var result = Connection.Stream.BeginWrite(outputData, 0, outputData.Length, WriteCallback, Connection);196 197 //jhkim debug198 //result.AsyncWaitHandle.WaitOne();199 TestUtility.LogInformation("Client {0:D3}: Write {1} bytes: {2} ", Connection.Id, outputData.Length,200 Encoding.UTF8.GetString(outputData, 0, outputData.Length));201 //result.AsyncWaitHandle.Close();202 }203 }204 public void SendWebSocketRequest(int websocketVersion, string AffinityCookie)205 {206 HandShakeRequest = Frames.GetHandShakeFrameWithAffinityCookie(Address.AbsoluteUri, websocketVersion, AffinityCookie);207 byte[] outputData = null;208 int offset = 0;209 while (offset < HandShakeRequest.Length)210 {211 outputData = HandShakeRequest[offset++];212 Connection.Stream.BeginWrite(outputData, 0, outputData.Length, WriteCallback, Connection);213 TestUtility.LogInformation("Client {0:D3}: Write {1} bytes: {2} ", Connection.Id, outputData.Length,214 Encoding.UTF8.GetString(outputData, 0, outputData.Length));215 }216 }217 public void ReadDataCallback(IAsyncResult result)218 {219 WebSocketConnect client = (WebSocketConnect)result.AsyncState;220 try221 {222 if (!client.TcpClient.Connected)223 {224 TestUtility.LogInformation("Failed to ReadDataCallback() because connection is gone");225 return;226 }227 if (client.IsDisposed)228 {229 return;230 }231 // wait until the buffer is filled232 int bytesRead = client.Stream.EndRead(result); 233 234 int bytesReadIntotal = bytesRead;235 ArrayList InputDataArray = new ArrayList();236 byte[] tempBuffer = null;237 if (bytesRead > 0)238 {239 tempBuffer = WebSocketClientUtility.SubArray(Connection.InputData, 0, bytesRead);240 Frame temp = new Frame(tempBuffer);241 // start looping if there is still remaining data242 if (tempBuffer.Length < temp.DataLength)243 {244 if (client.TcpClient.GetStream().DataAvailable)245 {246 // add the first buffer to the arrayList247 InputDataArray.Add(tempBuffer);248 // start looping appending to the arrayList249 while (client.TcpClient.GetStream().DataAvailable)250 {251 bytesRead = client.TcpClient.GetStream().Read(Connection.InputData, 0, Connection.InputData.Length);252 tempBuffer = WebSocketClientUtility.SubArray(Connection.InputData, 0, bytesRead);253 InputDataArray.Add(tempBuffer);254 bytesReadIntotal += bytesRead;255 TestUtility.LogInformation("ReadDataCallback: Looping: Client {0:D3}: bytesReadHere {1} ", Connection.Id, bytesRead);256 }257 // create a single byte array with the arrayList258 tempBuffer = new byte[bytesReadIntotal];259 int arrayIndex = 0;260 foreach (byte[] item in InputDataArray.ToArray())261 {262 for (int i = 0; i < item.Length; i++)263 {264 tempBuffer[arrayIndex] = item[i];265 arrayIndex++;266 }267 }268 }269 }270 // Create frame with the tempBuffer271 Frame frame = new Frame(tempBuffer);272 ProcessReceivedData(frame);273 int nextFrameIndex = frame.IndexOfNextFrame;274 while (nextFrameIndex != -1)275 {276 tempBuffer = tempBuffer.SubArray(frame.IndexOfNextFrame, tempBuffer.Length - frame.IndexOfNextFrame);277 frame = new Frame(tempBuffer);278 ProcessReceivedData(frame);279 nextFrameIndex = frame.IndexOfNextFrame;280 }281 if (this.WebSocketState == WebSocketState.ConnectionClosed)282 {283 client.Dispose();284 }285 if (client.IsDisposed)286 {287 return;288 }289 if (client.TcpClient.IsDead || client.TcpClient.Connected == false)290 {291 throw new Exception("Connection closed unexpectedly");292 }293 // Start the Async Read to handle the next frame comming from server294 client.Stream.BeginRead(client.InputData, 0, client.InputData.Length, ReadDataCallback, client);295 }296 else297 {298 client.Dispose();299 }300 }301 catch (Exception ex)302 {303 if (this.WebSocketState != WebSocketState.ConnectionClosed)304 {305 TestUtility.LogInformation("ReadDataCallback: Error on EndRead()" + ex.Message);306 this.WebSocketState = WebSocketState.ConnectionClosed;307 }308 else309 {310 TestUtility.LogInformation("ReadDataCallback() failed: WebSocketState is in closed state.");311 }312 client.Dispose();313 }314 }315 public Frame ReadData()316 {317 Frame frame = new Frame(new byte[] { });318 319 IAsyncResult result = Connection.Stream.BeginRead(Connection.InputData, 0, Connection.InputData.Length, null, Connection);320 321 if (result != null)322 {323 int bytesRead = Connection.Stream.EndRead(result);324 if (bytesRead > 0)325 {326 frame = new Frame(WebSocketClientUtility.SubArray(Connection.InputData, 0, bytesRead));327 ProcessReceivedData(frame);328 TestUtility.LogInformation("Client {0:D3}: Read Type {1} : {2} ", Connection.Id, frame.FrameType, frame.Content.Length);329 }330 }331 return frame;332 }333 public void SendTextData(string data)334 {335 Send(WebSocketClientUtility.GetFramedTextDataInBytes(data));336 }337 public void SendTextData(string data, byte opCode)338 {339 Send(WebSocketClientUtility.GetFramedTextDataInBytes(data, opCode));340 }341 public void SendHello()342 {343 Send(Frames.HELLO);344 }345 public void SendPing()346 {347 Send(Frames.PING);348 }349 public void SendPong()350 {351 Send(Frames.PONG);352 }353 public void SendClose()354 {355 Send(Frames.CLOSE_FRAME);356 }357 public void SendPong(Frame receivedPing)358 {359 var pong = new byte[receivedPing.Data.Length+4];360 for (int i = 1; i < receivedPing.Data.Length; i++)361 { 362 if(i<2)363 pong[i] = receivedPing.Data[i];364 else365 pong[i+4] = receivedPing.Data[i];366 }367 pong[0] = 0x8A;368 pong[1] = (byte)((int)pong[1] | 128);369 Send(pong);370 }371 public void CloseConnection()372 {373 this.WebSocketState = WebSocketState.ClosingFromClientStarted;374 Send(Frames.CLOSE_FRAME);375 if (!WaitForWebSocketState(WebSocketState.ConnectionClosed))376 {377 throw new Exception("Failed to close a connection");378 }379 }380 public static void WriteCallback(IAsyncResult result)381 {382 var client = result.AsyncState as WebSocketConnect;383 if (client.IsDisposed)384 return;385 client.Stream.EndWrite(result);386 }387 override public string ToString()388 {389 return Connection.Id + ": " + WebSocketState.ToString();390 }391 #region Private Methods392 public Frame Send(byte[] outputData)393 {394 var frame = new Frame(outputData);395 ProcessSentData(frame);396 if (Connection.TcpClient.Connected)397 {398 try399 {400 var result = Connection.Stream.BeginWrite(outputData, 0, outputData.Length, WriteCallback, Connection);401 TestUtility.LogInformation("Client {0:D3}: Write Type {1} : {2} ", Connection.Id, frame.FrameType, frame.Content.Length);402 }403 catch (Exception ex)404 {405 if (this.WebSocketState != WebSocketState.ConnectionClosed)406 {407 TestUtility.LogInformation("Send(): Exception error: " + ex.Message);408 this.WebSocketState = WebSocketState.ConnectionClosed;409 }410 else411 {412 TestUtility.LogInformation("Send() failed: WebSocketState is in closed state.");413 }414 }415 }416 else417 {418 TestUtility.LogInformation("Failed to Send() because connection is gone");419 }420 return frame;421 }422 private void ProcessSentData(Frame frame)423 {424 ProcessData(frame, true);425 }426 private void ProcessReceivedData(Frame frame)427 {428 TestUtility.LogInformation("ReadDataCallback: Client {0:D3}: Read Type {1} : {2} ", Connection.Id, frame.FrameType, frame.DataLength);429 if (frame.FrameType == FrameType.NonControlFrame)430 {431 string content = frame.Content.ToLower();432 if (content.Contains("connection: upgrade")433 && content.Contains("upgrade: websocket")434 && content.Contains("http/1.1 101 switching protocols"))435 {436 TestUtility.LogInformation("Connection opened...");437 TestUtility.LogInformation(frame.Content);438 WebSocketState = WebSocketState.ConnectionOpen;439 }440 }441 else442 {...
EtlInMemoryProducerTests.cs
Source:EtlInMemoryProducerTests.cs
...306 .Returns(consumerProcessTraceEventActionForFastWriter);307 dcaInMemoryConsumer.Setup(c => c.MaxIndexAlreadyProcessed)308 .Returns(maxIndexAlreadyProcessedForFastWriter);309 dcaInMemoryConsumer.Setup(c => c.OnProcessingPeriodStart(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<string>()))310 .Callback((string traceFileName, bool isActiveEtl, string traceFileSubFolder) => onProcessingPeriodStartActionForFastWriter(traceFileName, isActiveEtl, traceFileSubFolder));311 dcaInMemoryConsumer.Setup(c => c.OnProcessingPeriodStop(It.IsAny<string>(), It.IsAny<bool>(), It.IsAny<string>()))312 .Callback((string traceFileName, bool isActiveEtl, string traceFileSubFolder) => onProcessingPeriodStopActionForFastWriter(traceFileName, isActiveEtl, traceFileSubFolder));313 return dcaInMemoryConsumer.Object;314 }315 }316}...
ZipDirectoryReaderTest.cs
Source:ZipDirectoryReaderTest.cs
...265 MinimumPosition = Math.Min(MinimumPosition ?? long.MaxValue, Position);266 MaximumPosition = Math.Min(MaximumPosition ?? long.MinValue, Position);267 }268 public override bool CanWrite => throw new NotSupportedException();269 public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => throw new NotSupportedException();270 public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) => throw new NotSupportedException();271 public override int EndRead(IAsyncResult asyncResult) => throw new NotSupportedException();272 public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();273 public override int ReadByte() => throw new NotSupportedException();274 public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) => throw new NotSupportedException();275 public override Task FlushAsync(CancellationToken cancellationToken) => throw new NotSupportedException();276 public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => throw new NotSupportedException();277 public override void EndWrite(IAsyncResult asyncResult) => throw new NotSupportedException();278 public override void Flush() => throw new NotSupportedException();279 public override void SetLength(long value) => throw new NotSupportedException();280 public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();281 public override void WriteByte(byte value) => throw new NotSupportedException();282 }283 }284 }...
HttpClientHelper.cs
Source:HttpClientHelper.cs
...40 TestUtility.LogInformation(String.Format("HttpClient::sendRequest() {0} with no hostname", uri));41 else42 TestUtility.LogInformation(String.Format("HttpClient::sendRequest() {0} with hostname {1}", uri, hostName));43 }44 ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);45 if (useLegacy)46 {47 TestUtility.LogInformation(String.Format("Using SSL3"));48 ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;49 }50 HttpWebRequest myRequest;51 myRequest = (HttpWebRequest)WebRequest.Create(uri);52 myRequest.Proxy = null;53 myRequest.KeepAlive = false;54 if (hostName != null)55 myRequest.Host = hostName;56 ServicePoint point = myRequest.ServicePoint;57 point.ConnectionLeaseTimeout = 0;58 try...
TokenProviderTests.cs
Source:TokenProviderTests.cs
...106 {107 var appAuthority = "";108 var aadAppId = "";109 var aadAppSecret = "";110 AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback =111 async (audience, authority, state) =>112 {113 var authContext = new AuthenticationContext(authority);114 var cc = new ClientCredential(aadAppId, aadAppSecret);115 var authResult = await authContext.AcquireTokenAsync(audience, cc);116 return authResult.AccessToken;117 };118 var tokenProvider = TokenProvider.CreateAzureActiveDirectoryTokenProvider(authCallback, appAuthority);119 // Create new client with updated connection string.120 await using (var scope = await EventHubScope.CreateAsync(1))121 {122 var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);123 var csb = new EventHubsConnectionStringBuilder(connectionString);124 var ehClient = EventHubClient.CreateWithTokenProvider(csb.Endpoint, csb.EntityPath, tokenProvider);125 // Send one event126 TestUtility.Log($"Sending one message.");127 var ehSender = ehClient.CreatePartitionSender("0");128 var eventData = new EventData(Encoding.UTF8.GetBytes("Hello EventHub!"));129 await ehSender.SendAsync(eventData);130 // Receive event.131 PartitionReceiver ehReceiver = null;132 try133 {134 TestUtility.Log($"Receiving one message.");135 ehReceiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, "0", EventPosition.FromStart());136 var msg = await ehReceiver.ReceiveAsync(1);137 Assert.True(msg != null, "Failed to receive message.");138 }139 finally140 {141 await ehReceiver?.CloseAsync();142 }143 }144 }145 /// <summary>146 /// This test is for manual only purpose. Fill in the tenant-id, app-id and app-secret before running.147 /// </summary>148 /// <returns></returns>149 [Fact(Skip = "Manual run only")]150 [LiveTest]151 [DisplayTestMethodName]152 public async Task UseCreateApiWithAad()153 {154 var appAuthority = "";155 var aadAppId = "";156 var aadAppSecret = "";157 AzureActiveDirectoryTokenProvider.AuthenticationCallback authCallback =158 async (audience, authority, state) =>159 {160 var authContext = new AuthenticationContext(authority);161 var cc = new ClientCredential(aadAppId, aadAppSecret);162 var authResult = await authContext.AcquireTokenAsync(audience, cc);163 return authResult.AccessToken;164 };165 // Create new client with updated connection string.166 await using (var scope = await EventHubScope.CreateAsync(1))167 {168 var connectionString = TestUtility.BuildEventHubsConnectionString(scope.EventHubName);169 var csb = new EventHubsConnectionStringBuilder(connectionString);170 var ehClient = EventHubClient.CreateWithAzureActiveDirectory(csb.Endpoint, csb.EntityPath, authCallback, appAuthority);171 // Send one event172 TestUtility.Log($"Sending one message.");173 var ehSender = ehClient.CreatePartitionSender("0");174 var eventData = new EventData(Encoding.UTF8.GetBytes("Hello EventHub!"));175 await ehSender.SendAsync(eventData);176 // Receive event.177 PartitionReceiver ehReceiver = null;178 try179 {180 TestUtility.Log($"Receiving one message.");181 ehReceiver = ehClient.CreateReceiver(PartitionReceiver.DefaultConsumerGroupName, "0", EventPosition.FromStart());182 var msg = await ehReceiver.ReceiveAsync(1);183 Assert.True(msg != null, "Failed to receive message.");184 }...
OscInputTests.cs
Source:OscInputTests.cs
...56 public async Task TestSend(OscButtonInput buttonInput)57 {58 OscMessageValues values = null;59 string address = null;60 void Callback(BlobString a, OscMessageValues v)61 => (address, values) = (a.ToString(), v);62 _server.AddMonitorCallback(Callback);63 buttonInput.Send();64 await TestUtility.LoopWhile(() => values == null, TestUtility.LatencyTimeout);65 Assert.AreEqual(1, values.ReadIntElementUnchecked(0));66 Assert.AreEqual(buttonInput.CreateAddress(), address);67 values = null;68 buttonInput.Send(true);69 await TestUtility.LoopWhile(() => values == null, TestUtility.LatencyTimeout);70 Assert.AreEqual(1, values.ReadIntElementUnchecked(0));71 Assert.AreEqual(buttonInput.CreateAddress(), address);72 values = null;73 buttonInput.Send(false);74 await TestUtility.LoopWhile(() => values == null, TestUtility.LatencyTimeout);75 Assert.AreEqual(0, values.ReadIntElementUnchecked(0));76 Assert.AreEqual(buttonInput.CreateAddress(), address);77 values = null;78 _server.RemoveMonitorCallback(Callback);79 }80 [TestCaseSource(nameof(OscAxisInputTestCases))]81 public async Task<float> TestSendA(OscAxisInput axisInput, float value)82 {83 OscMessageValues values = null;84 string address = null;85 void Callback(BlobString a, OscMessageValues v)86 => (address, values) = (a.ToString(), v);87 _server.AddMonitorCallback(Callback);88 axisInput.Send(value);89 await TestUtility.LoopWhile(() => values == null, TestUtility.LatencyTimeout);90 Assert.AreEqual(axisInput.CreateAddress(), address);91 Assert.IsTrue(_server.RemoveMonitorCallback(Callback));92 return values.ReadFloatElement(0);93 }94 [TestCaseSource(nameof(AllOscButtonInput))]95 public async Task TestPressRelease(OscButtonInput buttonInput)96 {97 OscMessageValues values = null;98 string address = null;99 void Callback(BlobString a, OscMessageValues v)100 => (address, values) = (a.ToString(), v);101 _server.AddMonitorCallback(Callback);102 buttonInput.Press();103 await TestUtility.LoopWhile(() => values == null, TestUtility.LatencyTimeout);104 Assert.AreEqual(buttonInput.CreateAddress(), address);105 Assert.AreEqual(1, values.ReadIntElementUnchecked(0));106 values = null;107 buttonInput.Release();108 await TestUtility.LoopWhile(() => values == null, TestUtility.LatencyTimeout);109 Assert.AreEqual(buttonInput.CreateAddress(), address);110 Assert.AreEqual(0, values.ReadIntElementUnchecked(0));111 values = null;112 _server.RemoveMonitorCallback(Callback);113 }114 [TestCaseSource(nameof(AllOscButtonInput))]115 public void TestCreateAddress(OscButtonInput buttonInput)116 {117 Assert.AreEqual("/input/" + buttonInput.ToString(), buttonInput.CreateAddress());118 Assert.AreEqual("/input/" + buttonInput.ToString(), buttonInput.CreateAddress());119 }120 [TestCaseSource(nameof(AllOscAxisInput))]121 public void TestCreateAddress(OscAxisInput axisInput)122 {123 Assert.AreEqual("/input/" + axisInput.ToString(), axisInput.CreateAddress());124 Assert.AreEqual("/input/" + axisInput.ToString(), axisInput.CreateAddress());125 }126}...
Callback
Using AI Code Generation
1using System;2using System.Collections.Generic;3using System.Linq;4using System.Text;5using System.Threading.Tasks;6using TestUtility;7{8 {9 static void Main(string[] args)10 {11 Callback c1 = new Callback();12 c1.Method1();13 c1.Method2();14 Console.Read();15 }16 }17}
Callback
Using AI Code Generation
1using System;2using TestUtility;3{4 {5 static void Main(string[] args)6 {7 Callback c = new Callback();8 c.CallBackMethod();9 Console.Read();10 }11 }12}
Callback
Using AI Code Generation
1using TestUtility;2{3 public static void Main()4 {5 var callback = new Callback();6 callback.OnCallback += Callback_OnCallback;7 callback.OnCallback += Callback_OnCallback1;8 callback.OnCallback += Callback_OnCallback2;9 callback.OnCallback += Callback_OnCallback3;10 callback.OnCallback += Callback_OnCallback4;11 callback.OnCallback += Callback_OnCallback5;12 callback.OnCallback += Callback_OnCallback6;13 callback.OnCallback += Callback_OnCallback7;14 callback.OnCallback += Callback_OnCallback8;15 callback.OnCallback += Callback_OnCallback9;16 callback.OnCallback += Callback_OnCallback10;17 callback.OnCallback += Callback_OnCallback11;18 callback.OnCallback += Callback_OnCallback12;19 callback.OnCallback += Callback_OnCallback13;20 callback.OnCallback += Callback_OnCallback14;21 callback.OnCallback += Callback_OnCallback15;22 callback.OnCallback += Callback_OnCallback16;23 callback.OnCallback += Callback_OnCallback17;24 callback.OnCallback += Callback_OnCallback18;25 callback.OnCallback += Callback_OnCallback19;26 callback.OnCallback += Callback_OnCallback20;27 callback.OnCallback += Callback_OnCallback21;28 callback.OnCallback += Callback_OnCallback22;29 callback.OnCallback += Callback_OnCallback23;30 callback.OnCallback += Callback_OnCallback24;31 callback.OnCallback += Callback_OnCallback25;32 callback.OnCallback += Callback_OnCallback26;33 callback.OnCallback += Callback_OnCallback27;34 callback.OnCallback += Callback_OnCallback28;35 callback.OnCallback += Callback_OnCallback29;36 callback.OnCallback += Callback_OnCallback30;37 callback.OnCallback += Callback_OnCallback31;38 callback.OnCallback += Callback_OnCallback32;39 callback.OnCallback += Callback_OnCallback33;40 callback.OnCallback += Callback_OnCallback34;41 callback.OnCallback += Callback_OnCallback35;42 callback.OnCallback += Callback_OnCallback36;43 callback.OnCallback += Callback_OnCallback37;44 callback.OnCallback += Callback_OnCallback38;45 callback.OnCallback += Callback_OnCallback39;46 callback.OnCallback += Callback_OnCallback40;47 callback.OnCallback += Callback_OnCallback41;48 callback.OnCallback += Callback_OnCallback42;49 callback.OnCallback += Callback_OnCallback43;50 callback.OnCallback += Callback_OnCallback44;51 callback.OnCallback += Callback_OnCallback45;52 callback.OnCallback += Callback_OnCallback46;
Callback
Using AI Code Generation
1using TestUtility;2using System;3{4 {5 static void Main(string[] args)6 {7 Callback cb = new Callback();8 cb.CallbackEvent += new CallbackHandler(cb_CallbackEvent);9 cb.DoSomething();10 Console.ReadLine();11 }12 static void cb_CallbackEvent(object sender, EventArgs e)13 {14 Console.WriteLine("Callback event raised");15 }16 }17}18using TestUtility;19using System;20{21 {22 static void Main(string[] args)23 {24 Callback cb = new Callback();25 cb.CallbackEvent += new CallbackHandler(cb_CallbackEvent);26 cb.DoSomething();27 Console.ReadLine();28 }29 static void cb_CallbackEvent(object sender, EventArgs e)30 {31 Console.WriteLine("Callback event raised");32 }33 }34}35using TestUtility;36using System;37{38 {39 static void Main(string[] args)40 {41 Callback cb = new Callback();42 cb.CallbackEvent += new CallbackHandler(cb_CallbackEvent);43 cb.DoSomething();44 Console.ReadLine();45 }46 static void cb_CallbackEvent(object sender, EventArgs e)47 {48 Console.WriteLine("Callback event raised");49 }50 }51}52using TestUtility;53using System;54{55 {56 static void Main(string[] args)57 {58 Callback cb = new Callback();59 cb.CallbackEvent += new CallbackHandler(cb_CallbackEvent);60 cb.DoSomething();61 Console.ReadLine();62 }63 static void cb_CallbackEvent(object sender, EventArgs e)64 {65 Console.WriteLine("Callback event raised");66 }67 }68}69using TestUtility;70using System;71{72 {73 static void Main(string[] args)74 {75 Callback cb = new Callback();76 cb.CallbackEvent += new CallbackHandler(cb_CallbackEvent);77 cb.DoSomething();78 Console.ReadLine();79 }80 static void cb_CallbackEvent(object sender, EventArgs e)81 {82 Console.WriteLine("
Callback
Using AI Code Generation
1using TestUtility;2{3 {4 public static void Main(string[] args)5 {6 Callback callback = new Callback();7 callback.DoSomething();8 }9 }10}112.cs(3,7): error CS0246: The type or namespace name 'TestUtility' could not be found (are you missing a using directive or an assembly reference?)
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!