public void LookupCouponInvoice() { var discounts = new Dictionary<string, int> { { "USD", 1000 } }; var coupon = new Coupon(GetMockCouponCode(), GetMockCouponName(), discounts); coupon.Create(); var plan = new Plan(GetMockPlanCode(), GetMockPlanCode()) { Description = "Test Lookup Coupon Invoice" }; plan.UnitAmountInCents.Add("USD", 1500); plan.Create(); PlansToDeactivateOnDispose.Add(plan); var account = CreateNewAccountWithBillingInfo(); var redemption = account.RedeemCoupon(coupon.CouponCode, "USD"); var sub = new Subscription(account, plan, "USD", coupon.CouponCode); sub.Create(); // TODO complete this test var invoices = account.GetInvoices(); invoices.Should().NotBeEmpty(); var invoice = Invoices.Get(invoices.First().InvoiceNumber); var fromInvoice = invoice.GetRedemption(); redemption.Should().Be(fromInvoice); }
private void ConnectionAgent() { while (!_connectionEnd.WaitOne(0) && !Connected) try { URL url = new URL(_OpcSection.Server.Name); _Server = new Opc.Da.Server(new OpcCom.Factory(), null); _Server.Connect(url, new ConnectData(new NetworkCredential())); _groupRead = (Subscription)_Server.CreateSubscription(_GroupReadState); _groupWrite = (Subscription)_Server.CreateSubscription(_GroupWriteState); for (int i = 0; i < _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags.Count; i++) { _Items[i] = new Opc.Da.Item(); //_Items[i].ItemName = String.Format("{0}{1}", _OpcSection.Server.Channel, _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name); _Items[i].ItemName = _OpcSection.Server.Channel + "." + _OpcSection.Server.Device + "." + _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name; //string itmNam = String.Format("{0}]{1}", _OpcSection.Server.Channel, _OpcSection.Server.TagGroup.GetElement(_TagGroup).Tags[i].Name); _logger.LogInfo(/*Mtd*/ ": recognized element " + _Items[i].ItemName); } _Items = _groupRead.AddItems(_Items); _groupRead.DataChanged += new DataChangedEventHandler(Group_DataChanged); } catch (Exception ex) { _logger.LogError(ex); } }
public void should_not_match_invalid_joined_routing_key_with_splitted_token_subscription() { var subscription = new Subscription(MessageUtil.TypeId<FakeRoutableCommand>(), new BindingKey("Abc", "Service", "0")); var routingKey = BindingKey.Joined("Abc.Service.1"); subscription.Matches(routingKey).ShouldBeFalse(); }
public void Init() { var en = CultureInfo.CreateSpecificCulture("en"); Thread.CurrentThread.CurrentCulture = en; Thread.CurrentThread.CurrentUICulture = en; helper = new FormHelper(); subscription = new Subscription(); mock = new MockClass(); months = new[] {new Month(1, "January"), new Month(1, "February")}; product = new Product("memory card", 10, (decimal) 12.30); user = new SimpleUser(); users = new[] { new SimpleUser(1, false), new SimpleUser(2, true), new SimpleUser(3, false), new SimpleUser(4, true) }; mock.Values = new[] { 2, 3 }; var controller = new HomeController(); var context = new ControllerContext(); context.PropertyBag.Add("product", product); context.PropertyBag.Add("user", user); context.PropertyBag.Add("users", users); context.PropertyBag.Add("roles", new[] { new Role(1, "a"), new Role(2, "b"), new Role(3, "c") }); context.PropertyBag.Add("sendemail", true); context.PropertyBag.Add("confirmation", "abc"); context.PropertyBag.Add("fileaccess", FileAccess.Read); context.PropertyBag.Add("subscription", subscription); context.PropertyBag.Add("months", months); context.PropertyBag.Add("mock", mock); helper.SetController(controller, context); }
public void CreateWithPlanAndInvalidCardCvv() { var plan = CreateTestPlan (); plan.Save (); Assert.AreNotEqual (plan.Id, 0); var subscription = new Subscription { CardCvv = "651", CardExpirationDate = "0921", CardHolderName = "Jose da Silva", CardNumber = "4242424242424242", Customer = new Customer { Email = "*****@*****.**" }, Plan = plan }; try { subscription.Save (); } catch (PagarMeException ex) { Assert.IsNotNull (ex.Error.Errors.Where (e => e.Type == "action_forbidden").FirstOrDefault ()); } }
public override void TearDown () { MessageBus.Unsubscribe (subscriptionDataChange); subscriptionDataChange = null; base.TearDown (); }
public void Should_call_Nack_on_nested_subscriptions_with_all_delivery_tag() { // Arrange var channel = Substitute.For<IModel>(); channel.IsOpen.Returns(true); var subs = new CompositeSubscription(); var subscription = new Subscription { ConsumerTag = "ConsumerTag", QueueName = "QueueName", SubscriptionName = "SubscriptionName" }; subscription.SetChannel(channel); subs.AddSubscription(subscription); // Action subs.Nack("ConsumerTag", new[] { (ulong)1, (ulong)2, (ulong)3, (ulong)4, (ulong)5 }, false); // Assert channel.Received().BasicNack(1, false, false); channel.Received().BasicNack(2, false, false); channel.Received().BasicNack(3, false, false); channel.Received().BasicNack(4, false, false); channel.Received().BasicNack(5, false, false); }
public override void OnCreate () { base.OnCreate (); var bus = ServiceContainer.Resolve<MessageBus> (); subscriptionSyncFinishedMessage = bus.Subscribe<SyncWidgetMessage> (OnSyncFinishedMessage); }
/// <summary> /// Prompts the user to specify the browse options. /// </summary> public async Task<bool> ShowDialog(Subscription subscription) { if (subscription == null) throw new ArgumentNullException("subscription"); DisplayNameTB.Text = subscription.DisplayName; PublishingIntervalNC.Value = (double)Convert.ToDecimal(subscription.PublishingInterval); KeepAliveCountNC.Value = subscription.KeepAliveCount; LifetimeCountCTRL.Value = subscription.LifetimeCount; MaxNotificationsCTRL.Value = subscription.MaxNotificationsPerPublish; PriorityNC.Value = subscription.Priority; PublishingEnabledCK.IsChecked = subscription.PublishingEnabled; TaskCompletionSource<bool> tcs = new TaskCompletionSource<bool>(); Popup dialog = new Popup(); dialog.Child = this; dialog.IsOpen = true; dialog.Closed += (o, e) => { tcs.SetResult(dialogResult); }; bool result = await tcs.Task; subscription.DisplayName = DisplayNameTB.Text; subscription.PublishingInterval = (int)PublishingIntervalNC.Value; subscription.KeepAliveCount = (uint)KeepAliveCountNC.Value; subscription.LifetimeCount = (uint)LifetimeCountCTRL.Value; subscription.MaxNotificationsPerPublish = (uint)MaxNotificationsCTRL.Value; subscription.Priority = (byte)PriorityNC.Value; subscription.PublishingEnabled = (bool)PublishingEnabledCK.IsChecked; return result; }
public SubscriptionDataExtended(Subscription subscription, SubscriptionData subscriptionData, string description, Operation operation) { OperationDescription = description; OperationStatus = operation.Status; OperationId = operation.OperationTrackingId; SubscriptionName = subscriptionData.SubscriptionName; SubscriptionId = subscriptionData.SubscriptionId; Certificate = subscriptionData.Certificate; CurrentStorageAccount = subscriptionData.CurrentStorageAccount; ServiceEndpoint = subscriptionData.ServiceEndpoint; SqlAzureServiceEndpoint = subscriptionData.SqlAzureServiceEndpoint; IsDefault = subscriptionData.IsDefault; AccountAdminLiveEmailId = subscription.AccountAdminLiveEmailId; CurrentCoreCount = subscription.CurrentCoreCount; CurrentHostedServices = subscription.CurrentHostedServices; CurrentStorageAccounts = subscription.CurrentStorageAccounts; CurrentDnsServers = subscription.CurrentDnsServers; CurrentLocalNetworkSites = subscription.CurrentLocalNetworkSites; CurrentVirtualNetworkSites = subscription.CurrentVirtualNetworkSites; MaxCoreCount = subscription.MaxCoreCount; MaxHostedServices = subscription.MaxHostedServices; MaxStorageAccounts = subscription.MaxStorageAccounts; MaxDnsServers = subscription.MaxDnsServers; MaxLocalNetworkSites = subscription.MaxLocalNetworkSites; MaxVirtualNetworkSites = subscription.MaxVirtualNetworkSites; ServiceAdminLiveEmailId = subscription.ServiceAdminLiveEmailId; SubscriptionRealName = subscription.SubscriptionName; SubscriptionStatus = subscription.SubscriptionStatus; }
public override void OnResume () { base.OnResume (); var bus = ServiceContainer.Resolve<MessageBus> (); subscriptionUserTimeEntryStateChange = bus.Subscribe<UserTimeEntryStateChangeMessage> (OnUserTimeEntryStateChange); }
private void UpdateCore(Peer peer, Subscription subscription, bool isAddOrUpdate) { if (subscription.IsMatchingAllMessages) { var list = _peersHandlingAllMessages .Where(i => i.Id != peer.Id) .ToList(); if (isAddOrUpdate) list.Add(peer); _peersHandlingAllMessages = list; } else { var list = _dynamicPeerSubscriptions .Where(item => item.Peer.Id != peer.Id || !Equals(item.Subscription, subscription)) .ToList(); if (isAddOrUpdate) list.Add(new PeerSubscription(peer, subscription)); Interlocked.Exchange(ref _dynamicPeerSubscriptions, list); } }
internal StorageAccount(XElement xml, Subscription subscription) : this() { var azureNamespace = XmlNamespaces.WindowsAzure; xml.HydrateObject(azureNamespace, this); Subscription = subscription; var storageServicePropertiesElement = xml.Element(azureNamespace + "StorageServiceProperties"); storageServicePropertiesElement.HydrateObject(azureNamespace, this); if (!string.IsNullOrEmpty(Label)) Label = Label.FromBase64String(); var extendedProperties = xml.Element(azureNamespace + "ExtendedProperties"); if (extendedProperties != null) { ExtendedProperties = extendedProperties.Elements() .ToDictionary( x => (string) x.Element(azureNamespace + "Name"), x => (string) x.Element(azureNamespace + "Value")); } Endpoints = GetEndpoints(storageServicePropertiesElement, azureNamespace, "Endpoints"); SecondaryEndpoints = GetEndpoints(storageServicePropertiesElement, azureNamespace, "SecondaryEndpoints"); }
public void CreateSubscription() { var plan = new Plan(GetMockPlanCode(), GetMockPlanName()) { Description = "Create Subscription Test" }; plan.UnitAmountInCents.Add("USD", 100); plan.Create(); PlansToDeactivateOnDispose.Add(plan); var account = CreateNewAccountWithBillingInfo(); var coup = CreateNewCoupon(3); var sub = new Subscription(account, plan, "USD"); sub.TotalBillingCycles = 5; sub.Coupon = coup; Assert.Null(sub.TaxInCents); Assert.Null(sub.TaxType); Assert.Null(sub.TaxRate); sub.Create(); sub.ActivatedAt.Should().HaveValue().And.NotBe(default(DateTime)); sub.State.Should().Be(Subscription.SubscriptionState.Active); Assert.Equal(5, sub.TotalBillingCycles); Assert.Equal(coup.CouponCode, sub.Coupon.CouponCode); Assert.Equal(9, sub.TaxInCents.Value); Assert.Equal("usst", sub.TaxType); Assert.Equal(0.0875M, sub.TaxRate.Value); var sub1 = Subscriptions.Get(sub.Uuid); Assert.Equal(5, sub1.TotalBillingCycles); }
public void NewToOld() { var oldSub = new Subscription("the message", new Uri("http://bob/phil")); IList<Subscription> oldSubs = new List<Subscription>(); oldSubs.Add(oldSub); using (var newStream = new MemoryStream()) { NewWriter.Serialize(newStream, oldSubs); newStream.Position = 0; using (var oldStream = new MemoryStream()) { using (var str = File.OpenRead(_pathToFile)) { var buff = new byte[str.Length]; str.Read(buff, 0, buff.Length); oldStream.Write(buff, 0, buff.Length); } if (File.Exists(".\\my_msg_2.txt")) File.Delete(".\\my_msg_2.txt"); using (var fs = File.OpenWrite(".\\my_msg_2.txt")) { fs.Write(newStream.ToArray(), 0, newStream.ToArray().Length); } StreamAssert.AreEqual(oldStream, newStream); } } }
private void Unsubscribe(Subscription subscription) { lock (_subscriptions) { _subscriptions.Remove(subscription); } }
public virtual void SetUp() { RcvBuffer = new UnsafeBuffer(new byte[ALIGNED_FRAME_LENGTH]); DataHeader = new DataHeaderFlyweight(); MockFragmentHandler = A.Fake<FragmentHandler>(); MockControlledFragmentHandler = A.Fake<IControlledFragmentHandler>(); Position = A.Fake<IPosition>(options => options.Wrapping(new AtomicLongPosition())); LogBuffers = A.Fake<LogBuffers>(); ErrorHandler = A.Fake<ErrorHandler>(); Subscription = A.Fake<Subscription>(); AtomicBuffers = new UnsafeBuffer[(LogBufferDescriptor.PARTITION_COUNT * 2) + 1]; TermBuffers = new UnsafeBuffer[LogBufferDescriptor.PARTITION_COUNT]; DataHeader.Wrap(RcvBuffer); for (var i = 0; i < LogBufferDescriptor.PARTITION_COUNT; i++) { AtomicBuffers[i] = new UnsafeBuffer(new byte[TERM_BUFFER_LENGTH]); TermBuffers[i] = AtomicBuffers[i]; AtomicBuffers[i + LogBufferDescriptor.PARTITION_COUNT] = new UnsafeBuffer(new byte[LogBufferDescriptor.TERM_META_DATA_LENGTH]); } AtomicBuffers[LogBufferDescriptor.LOG_META_DATA_SECTION_INDEX] = new UnsafeBuffer(new byte[LogBufferDescriptor.LOG_META_DATA_LENGTH]); A.CallTo(() => LogBuffers.AtomicBuffers()).Returns(AtomicBuffers); A.CallTo(() => LogBuffers.TermLength()).Returns(TERM_BUFFER_LENGTH); }
private void addSubscription(Subscription s) { AddBodyRow(row => { row.Cell(s.Receiver.ToString()); row.Cell(s.MessageType); }); }
public void can_replace_the_subscriptions() { var cache = new SubscriptionCache(new ChannelGraph(), new ITransport[]{new InMemoryTransport(), }); var subscriptions1 = new Subscription[] { ObjectMother.ExistingSubscription(), ObjectMother.ExistingSubscription(), ObjectMother.ExistingSubscription(), ObjectMother.ExistingSubscription(), ObjectMother.ExistingSubscription(), ObjectMother.ExistingSubscription(), ObjectMother.ExistingSubscription() }; var subscriptions2 = new Subscription[] { ObjectMother.ExistingSubscription(), ObjectMother.ExistingSubscription(), ObjectMother.ExistingSubscription(), ObjectMother.ExistingSubscription() }; cache.LoadSubscriptions(subscriptions1); cache.ActiveSubscriptions.ShouldHaveTheSameElementsAs(subscriptions1); cache.LoadSubscriptions(subscriptions2); cache.ActiveSubscriptions.ShouldHaveTheSameElementsAs(subscriptions2); }
/// <summary> /// Creates a new subscription. /// </summary> public Subscription New(Session session) { if (session == null) throw new ArgumentNullException("session"); Subscription subscription = new Subscription(session.DefaultSubscription); if (!new SubscriptionEditDlg().ShowDialog(subscription)) { return null; } session.AddSubscription(subscription); subscription.Create(); Subscription duplicateSubscription = session.Subscriptions.FirstOrDefault(s => s.Id != 0 && s.Id.Equals(subscription.Id) && s != subscription); if (duplicateSubscription != null) { Utils.Trace("Duplicate subscription was created with the id: {0}", duplicateSubscription.Id); DialogResult result = MessageBox.Show("Duplicate subscription was created with the id: " + duplicateSubscription.Id + ". Do you want to keep it?", "Warning", MessageBoxButtons.YesNo); if (result == System.Windows.Forms.DialogResult.No) { duplicateSubscription.Delete(false); session.RemoveSubscription(subscription); return null; } } Show(subscription); return subscription; }
/// <summary> /// Prompts the user to specify the browse options. /// </summary> public bool ShowDialog(Subscription subscription) { if (subscription == null) throw new ArgumentNullException("subscription"); DisplayNameTB.Text = subscription.DisplayName; PublishingIntervalNC.Value = subscription.Created ? (decimal)subscription.CurrentPublishingInterval : (decimal)subscription.PublishingInterval; KeepAliveCountNC.Value = subscription.Created ? subscription.CurrentKeepAliveCount : subscription.KeepAliveCount; LifetimeCountCTRL.Value = subscription.Created ? subscription.CurrentLifetimeCount: subscription.LifetimeCount; MaxNotificationsCTRL.Value = subscription.MaxNotificationsPerPublish; PriorityNC.Value = subscription.Created ? subscription.CurrentPriority : subscription.Priority; PublishingEnabledCK.Checked = subscription.Created ? subscription.CurrentPublishingEnabled : subscription.PublishingEnabled; if (ShowDialog() != DialogResult.OK) { return false; } subscription.DisplayName = DisplayNameTB.Text; subscription.PublishingInterval = (int)PublishingIntervalNC.Value; subscription.KeepAliveCount = (uint)KeepAliveCountNC.Value; subscription.LifetimeCount = (uint)LifetimeCountCTRL.Value; subscription.MaxNotificationsPerPublish = (uint)MaxNotificationsCTRL.Value; subscription.Priority = (byte)PriorityNC.Value; if (subscription.Created) { subscription.SetPublishingMode(PublishingEnabledCK.Checked); } else { subscription.PublishingEnabled = PublishingEnabledCK.Checked; } return true; }
internal TrafficManagerProfile(XElement xml, Subscription subscription) : this() { var ns = XmlNamespaces.WindowsAzure; xml.HydrateObject(ns, this); Enabled = (string) xml.Element(ns + "Status") != "Disabled"; Subscription = subscription; }
/// <summary> /// Initializes a new instance of the <see cref="AuditEventForm"/> class. /// </summary> /// <param name="session">The session.</param> /// <param name="subscription">The subscription.</param> public AuditEventForm(Session session, Subscription subscription) { InitializeComponent(); m_session = session; m_subscription = subscription; // a table used to track event types. m_eventTypeMappings = new Dictionary<NodeId, NodeId>(); // the filter to use. m_filter = new FilterDefinition(); m_filter.AreaId = ObjectIds.Server; m_filter.Severity = EventSeverity.Min; m_filter.IgnoreSuppressedOrShelved = true; m_filter.EventTypes = new NodeId[] { ObjectTypeIds.AuditUpdateMethodEventType }; // find the fields of interest. m_filter.SelectClauses = m_filter.ConstructSelectClauses(m_session, ObjectTypeIds.AuditUpdateMethodEventType); // declate callback. m_MonitoredItem_Notification = new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); // create a monitored item based on the current filter settings. m_monitoredItem = m_filter.CreateMonitoredItem(m_session); // set up callback for notifications. m_monitoredItem.Notification += m_MonitoredItem_Notification; m_subscription.AddItem(m_monitoredItem); m_subscription.ApplyChanges(); }
/// <summary> /// Displays the dialog. /// </summary> public void Show(Subscription subscription, bool useTypeModel) { if (subscription == null) throw new ArgumentNullException("subscription"); Show(); BringToFront(); // remove previous subscription. if (m_subscription != null) { m_subscription.StateChanged -= m_SubscriptionStateChanged; } // start receiving notifications from the new subscription. m_subscription = subscription; if (subscription != null) { m_subscription.StateChanged += m_SubscriptionStateChanged; } m_subscription = subscription; BrowseCTRL.AllowPick = true; BrowseCTRL.SetView(subscription.Session, (useTypeModel)?BrowseViewType.ObjectTypes:BrowseViewType.Objects, null); MonitoredItemsCTRL.Initialize(subscription); }
public TimeCorrectionManager () { var bus = ServiceContainer.Resolve<MessageBus> (); subscriptionHttpResponseMessage = bus.Subscribe<TogglHttpResponseMessage> (OnHttpResponse); LoadMeasurements (); }
public override void OnViewCreated (View view, Bundle savedInstanceState) { base.OnViewCreated (view, savedInstanceState); var bus = ServiceContainer.Resolve<MessageBus> (); subscriptionSettingChanged = bus.Subscribe<SettingChangedMessage> (OnSettingChanged); }
public MainViewModel() { XDocument doc = XDocument.Load("Subscriptions.config"); List<Subscription> subscriptions = new List<Subscription>(); foreach (XElement elem in doc.Root.Elements("Subscription")) { Subscription subscription = new Subscription() { Title = elem.Attribute("title").Value, AccountName = elem.Attribute("accountName").Value, AccountKey = elem.Attribute("accountKey").Value, Roles = elem.Element("Roles").Elements("Role").Select(r => new Role() { Name = r.Attribute("name").Value, PerformanceCounters = r.Element("PerformanceCounters").Elements("PerformanceCounterConfiguration").Select(o => o.Attribute("counterSpecifier").Value).ToArray() }).ToArray() }; subscriptions.Add(subscription); } this.Subscriptions = new ObservableCollection<Subscription>(subscriptions); RaisePropertyChanged("Subscriptions"); this.LogEntries = new ObservableCollection<WadLogEntity>(); RaisePropertyChanged("LogEntries"); }
//public XmlRpcValue stickaroundyouwench = null; public PendingConnection(XmlRpcClient client, Subscription s, string uri, XmlRpcValue chk) { this.client = client; this.chk = chk; parent = s; RemoteUri = uri; }
public async Task DeleteAsync() { Contract.Requires(Subscription != null); await GetRestClient("/" + Name).DeleteAsync(); Subscription = null; }
public void ListExpiredSubscriptions() { var plan = new Plan(GetMockPlanCode(), GetMockPlanName()) { Description = "Subscription Test", PlanIntervalLength = 1, PlanIntervalUnit = Plan.IntervalUnit.Months }; plan.UnitAmountInCents.Add("USD", 400); plan.Create(); PlansToDeactivateOnDispose.Add(plan); for (var x = 0; x < 2; x++) { var account = CreateNewAccountWithBillingInfo(); var sub = new Subscription(account, plan, "USD") { StartsAt = DateTime.Now.AddMonths(-5) }; sub.Create(); } var subs = Subscriptions.List(Subscription.SubscriptionState.Expired); subs.Should().NotBeEmpty(); }
public StatusbarViewModel() { _onDirectoryChanged = EventAggregator.Subscribe <DirectoryChangedEventArgs>(DirectoryChanged); _configService = GetService <ConfigurationService>(); }
public Subscriber(AtomicBoolean running, Subscription subscription) { Running = running; Subscription = subscription; }
public static void AlexaPropertyChanged(dynamic @params) { Subscription sub = (Subscription)@params; using (deDupeLock.Lock()) { // Premise can send multiple notifications for a single object, one for each // subscribed property that changes. The state report function here will capture // states of all properties, so the DeDupeDictionary prevents multiple state reports // from being sent for essentially the same event. if (DeDupeDictionary.ContainsKey(sub.sysObjectId)) { return; } DeDupeDictionary.Add(sub.sysObjectId, sub); } Task.Run(() => { // get the endpoint and endpoint capabilities Guid premiseId = new Guid(sub.sysObjectId); IPremiseObject endpoint = HomeObject.GetObjectAsync(premiseId.ToString("B")).GetAwaiter().GetResult(); if (!endpoint.IsValidObject()) { return; } DiscoveryEndpoint discoveryEndpoint = GetDiscoveryEndpointAsync(endpoint).GetAwaiter().GetResult(); if (discoveryEndpoint == null) { return; } // get the authorization code for the notification string authCode; using (asyncObjectsLock.Lock()) { authCode = (string)HomeObject.GetValueAsync("AlexaAsyncAuthorizationCode").GetAwaiter().GetResult(); } // build the change report AlexaChangeReport changeReport = new AlexaChangeReport(); [email protected] = Guid.NewGuid().ToString("D"); [email protected].@namespace = "Alexa"; [email protected] = "3"; [email protected] = "BearerToken"; [email protected] = authCode; [email protected] = premiseId.ToString("D").ToUpper(); [email protected] = discoveryEndpoint.cookie; [email protected] = "PHYSICAL_INTERACTION"; // get the device type and controller (e.g. AlexaAV, AlexaHVAC) IAlexaDeviceType deviceType = null; IAlexaController controller = null; List <AlexaProperty> relatedPropertyStates = null; bool hasScene = false; foreach (IAlexaController controllerToTest in Controllers.Values) { if (!controllerToTest.HasPremiseProperty(sub.propertyName)) { continue; } controller = controllerToTest; Type type = Type.GetType(controller.GetAssemblyTypeName()); if (type == null) { continue; } // found a controller, get an instance of the assembly deviceType = (IAlexaDeviceType)Activator.CreateInstance(type); // Determine if this deviceType supports the desired capability // note: This handles situation where the same property name is used by different // controllers. e.g. "brightness" is used in both ColorController and BrightnessController relatedPropertyStates = deviceType.FindRelatedProperties(endpoint, ""); foreach (AlexaProperty property in relatedPropertyStates) { // if so, this is the correct type if (property.@namespace == controller.GetNameSpace()) { break; } } } // ReSharper disable once ConditionIsAlwaysTrueOrFalse if ((deviceType == null) || (controller == null || relatedPropertyStates == null)) { return; } foreach (AlexaProperty prop in relatedPropertyStates) { if (prop.@namespace == "Alexa.SceneController") { hasScene = true; continue; } if (([email protected] == 0) && (prop.name == controller.MapPremisePropertyToAlexaProperty(sub.propertyName))) { [email protected](prop); } else { string propKey = prop.@namespace + "." + prop.name; changeReport.context.propertiesInternal.Add(propKey, prop); } } [email protected] = "ChangeReport"; // scenes are special case if (hasScene) { AlexaSetSceneController sceneController = new AlexaSetSceneController(endpoint); changeReport = sceneController.AlterChangeReport(changeReport); } StateChangeReportWrapper item = new StateChangeReportWrapper { ChangeReport = changeReport }; stateReportQueue.Enqueue(item); using (deDupeLock.Lock()) { DeDupeDictionary.Remove(sub.sysObjectId); } }); }
/// <summary> /// Подключение к OPC-серверу по его адресу. Выполняется асинхронно. /// </summary> /// <param name="ep">Адрес OPC-сервера</param> /// <returns></returns> public async Task Connect(string endpointUrl) { _config = new ApplicationConfiguration() { ApplicationName = "Console OPC-Client", ApplicationType = ApplicationType.Client, ApplicationUri = "urn:localhost:OPCFoundation:SampleClient", SecurityConfiguration = new SecurityConfiguration { ApplicationCertificate = new CertificateIdentifier { StoreType = "Directory", StorePath = "./OPC Foundation/CertificateStores/MachineDefault", SubjectName = Utils.Format("CN={0}, DC={1}", "Console OPC-Client", Utils.GetHostName()) }, TrustedPeerCertificates = new CertificateTrustList { StoreType = "Directory", StorePath = "./OPC Foundation/CertificateStores/UA Applications", }, TrustedIssuerCertificates = new CertificateTrustList { StoreType = "Directory", StorePath = "./OPC Foundation/CertificateStores/UA Certificate Authorities", }, RejectedCertificateStore = new CertificateTrustList { StoreType = "Directory", StorePath = "./OPC Foundation/CertificateStores/RejectedCertificates", }, NonceLength = 32, AutoAcceptUntrustedCertificates = true }, TransportConfigurations = new TransportConfigurationCollection(), TransportQuotas = new TransportQuotas { OperationTimeout = 15000 }, ClientConfiguration = new ClientConfiguration { DefaultSessionTimeout = 60000 } }; await _config.Validate(ApplicationType.Client); _haveAppCertificate = _config.SecurityConfiguration.ApplicationCertificate.Certificate != null; if (_haveAppCertificate && _config.SecurityConfiguration.AutoAcceptUntrustedCertificates) { _config.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); } Uri endpointURI = new Uri(endpointUrl); var endpointCollection = DiscoverEndpoints(_config, endpointURI, 10); var selectedEndpoint = SelectUaTcpEndpoint(endpointCollection, _haveAppCertificate); var endpointConfiguration = EndpointConfiguration.Create(_config); var endpoint = new ConfiguredEndpoint(selectedEndpoint.Server, endpointConfiguration); endpoint.Update(selectedEndpoint); _session = await Session.Create(_config, endpoint, true, "Console OPC Client", 60000, null, null); _subscription = new Subscription(_session.DefaultSubscription) { PublishingInterval = 1000 }; }
public ActionResult <RetrieveUpcomingInvoiceResponse> RetrieveUpcomingInvoice([FromBody] RetrieveUpcomingInvoiceRequest req) { if (!ModelState.IsValid) { return(this.FailWithMessage("invalid params")); } var newPrice = Environment.GetEnvironmentVariable(req.NewPrice.ToUpper()); if (newPrice is null || newPrice == "") { return(this.FailWithMessage($"No price with the new price ID ({req.NewPrice}) found in .env")); } List <InvoiceSubscriptionItemOptions> items; Subscription subscription = null; if (req.Subscription != "" && req.Subscription != null) { var subscriptionService = new SubscriptionService(); subscription = subscriptionService.Get(req.Subscription); var currentPrice = subscription.Items.Data[0].Price.Id; if (currentPrice == newPrice) { items = new List <InvoiceSubscriptionItemOptions> { new InvoiceSubscriptionItemOptions { Id = subscription.Items.Data[0].Id, Quantity = req.Quantity, } }; } else { items = new List <InvoiceSubscriptionItemOptions> { new InvoiceSubscriptionItemOptions { Id = subscription.Items.Data[0].Id, Deleted = true, }, new InvoiceSubscriptionItemOptions { Price = newPrice, Quantity = req.Quantity, }, }; } } else { items = new List <InvoiceSubscriptionItemOptions> { new InvoiceSubscriptionItemOptions { Price = newPrice, Quantity = req.Quantity, }, }; } var invoiceService = new InvoiceService(); var options = new UpcomingInvoiceOptions { Customer = req.Customer, Subscription = req.Subscription, SubscriptionItems = items, }; Invoice upcomingInvoice = invoiceService.Upcoming(options); if (req.Subscription == "" || req.Subscription is null) { return(new RetrieveUpcomingInvoiceResponse { Invoice = upcomingInvoice, }); } else { var currentPeriodEnd = subscription.CurrentPeriodEnd; long immediateTotal = 0; long nextInvoiceSum = 0; foreach (var lineItem in upcomingInvoice.Lines.Data) { if (lineItem.Period.End == currentPeriodEnd) { immediateTotal += lineItem.Amount; } else { nextInvoiceSum += lineItem.Amount; } } return(new RetrieveUpcomingInvoiceResponse { ImmediateTotal = immediateTotal, NextInvoiceSum = nextInvoiceSum, Invoice = upcomingInvoice, }); } }
/// <summary> /// Creates the client to read data from the usage REST API. /// </summary> /// <param name="azureIdentity">the service credentials</param> /// <param name="environment">the azure environment</param> /// <param name="subscription">the subscription details</param> public UsageClient(AzureIdentity azureIdentity, AzureEnvironment environment, Subscription subscription) : base(azureIdentity, environment, subscription) { }
/// <summary> /// Подписать клиента на определенный тип сообщений или обновить подписку. /// </summary> /// <param name="clientId">Идентификатор клиента, подписку которого нужно обновить или создать.</param> /// <param name="messageTypeId">Тип сообщений подписки.</param><param name="isCallback">Является ли подписка callback.</param> /// <param name="transportType">Способ передачи сообщений, если подписка callback, иначе можно передать null.</param> /// <param name="expiryDate">Дата прекращения подписки. Если не указана, вычисляется как сумма текущей даты и параметра конфигурации UpdateForATime.</param> /// <param name="subscriptionId">Идентификатор подписки, которую нужно обновить или создать.</param> public void SubscribeOrUpdate(string clientId, string messageTypeId, bool isCallback, TransportType?transportType, DateTime?expiryDate = null, string subscriptionId = null) { Subscription[] subscriptions = GetSubscriptions(clientId, false).Where(x => x.MessageType.ID == messageTypeId || CompareGuid2Str(((KeyGuid)x.MessageType.__PrimaryKey).Guid, messageTypeId)).ToArray(); Subscription subscription = subscriptionId == null?subscriptions.FirstOrDefault() : subscriptions.FirstOrDefault(s => CompareGuid2Str(((KeyGuid)s.__PrimaryKey).Guid, subscriptionId)); Stopwatch stopwatch; long time; if (subscription == null) { var langDef = ExternalLangDef.LanguageDef; LoadingCustomizationStruct clientLcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(Client), Client.Views.EditView); clientLcs.LimitFunction = langDef.GetFunction(langDef.funcEQ, new VariableDef(langDef.StringType, Information.ExtractPropertyPath <Client>(x => x.ID)), clientId); stopwatch = new Stopwatch(); stopwatch.Start(); var client = _dataService.LoadObjects(clientLcs).Cast <Client>().FirstOrDefault(); stopwatch.Stop(); time = stopwatch.ElapsedMilliseconds; _statisticsService.NotifyAvgTimeSql(null, (int)time, "CachedSubscriptionsManager.SubscribeOrUpdate() load Client."); if (client == null) { throw new ArgumentException("clientId"); } LoadingCustomizationStruct messageTypeLcs = LoadingCustomizationStruct.GetSimpleStruct(typeof(MessageType), MessageType.Views.EditView); messageTypeLcs.LimitFunction = langDef.GetFunction(langDef.funcEQ, new VariableDef(langDef.StringType, Information.ExtractPropertyPath <MessageType>(x => x.ID)), messageTypeId); stopwatch = new Stopwatch(); stopwatch.Start(); var messageType = _dataService.LoadObjects(messageTypeLcs).Cast <MessageType>().FirstOrDefault(); stopwatch.Stop(); time = stopwatch.ElapsedMilliseconds; _statisticsService.NotifyAvgTimeSql(null, (int)time, "CachedSubscriptionsManager.SubscribeOrUpdate() load TypeMessage."); if (messageType == null) { throw new ArgumentException("messageTypeId"); } subscription = new Subscription() { Client = client, MessageType = messageType }; if (subscriptionId != null) { subscription.__PrimaryKey = Guid.Parse(subscriptionId); } } subscription.IsCallback = isCallback; if (transportType != null) { subscription.TransportType = transportType.Value; } else if (isCallback) { throw new ArgumentNullException(nameof(transportType)); } if (expiryDate != null) { subscription.ExpiryDate = expiryDate.Value; } else { ServiceHelper.UpdateStoppingDate(subscription); } if (subscription.GetStatus() == ObjectStatus.Created) { lock (SubscriptionsLockObject) { Subscriptions.Add(subscription); } } stopwatch = new Stopwatch(); stopwatch.Start(); _dataService.UpdateObject(subscription); stopwatch.Stop(); time = stopwatch.ElapsedMilliseconds; _statisticsService.NotifyAvgTimeSql(subscription, (int)time, "CachedSubscriptionsManager.SubscribeOrUpdate() load Client."); }
public void Persist(Subscription subscription) { _transaction.Execute <IDocumentSession>(x => x.Store(subscription)); }
private void OnEnable() { gameEventSubscription = PublisherSubscriber.Subscribe <GameEventType>(GameEventHandler); }
public void CreateSubscriptionWithSplitRules() { var plan = CreateTestPlan(); plan.Save(); var subscription = new Subscription { PaymentMethod = PaymentMethod.CreditCard, CardHash = GetCardHash(), Customer = new Customer() { Name = "Customer de teste", Email = "*****@*****.**", DocumentNumber = "17583142903", Address = new Address() { Street = "Avenida Brigadeiro Faria Lima", StreetNumber = "123", Neighborhood = "Jardim Paulistano", Zipcode = "04250000" }, Phone = new Phone() { Ddi = "55", Ddd = "11", Number = "23456789" } }, Plan = plan }; Recipient recipient1 = CreateRecipient(); recipient1.Save(); Recipient recipient2 = CreateRecipient(); recipient2.Save(); subscription.SplitRules = new[] { new SplitRule { Recipient = recipient1, Amount = 660, ChargeProcessingFee = true, Liable = true }, new SplitRule { Recipient = recipient2, Amount = 439, ChargeProcessingFee = false, Liable = false } }; subscription.Save(); Assert.AreEqual(subscription.Status, SubscriptionStatus.Paid); List <Payable> subscriptionPayables = subscription.CurrentTransaction.Payables.FindAll(new Payable()).ToList(); List <Payable> firstRecipientPayable = subscriptionPayables.Where(x => x.RecipientId == recipient1.Id).ToList(); List <Payable> secondRecipientPayable = subscriptionPayables.Where(x => x.RecipientId == recipient2.Id).ToList(); Assert.AreEqual(firstRecipientPayable.Count, 1); Assert.AreEqual(firstRecipientPayable.ElementAt(0).RecipientId, recipient1.Id); Assert.AreEqual(firstRecipientPayable.ElementAt(0).Amount, 660); Assert.AreEqual(secondRecipientPayable.Count, 1); Assert.AreEqual(secondRecipientPayable.ElementAt(0).RecipientId, recipient2.Id); Assert.AreEqual(secondRecipientPayable.ElementAt(0).Amount, 439); }
public static Pageable <ProductFamily> GetProductFamilies(this Subscription subscription, ProductFamiliesRequest productFamiliesRequest, string expand = null, string skipToken = null, CancellationToken cancellationToken = default) { Argument.AssertNotNull(productFamiliesRequest, nameof(productFamiliesRequest)); return(GetExtensionClient(subscription).GetProductFamilies(productFamiliesRequest, expand, skipToken, cancellationToken)); }
public static async Task MaintainSubscription(IServiceProvider serviceProvider, Subscription subscription) { var contextAccessor = serviceProvider.GetRequiredService <IHttpContextAccessor>(); var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>(); var webApiConfiguration = serviceProvider.GetRequiredService <IOptions <WebApiConfiguration> >()?.Value; var logger = loggerFactory.CreateLogger(string.Join('.', typeof(JibberwockEventProcessing).FullName, nameof(MaintainSubscription))); var sqlDataSource = serviceProvider.GetRequiredService <SqlServerDataSource>(); Jibberwock.DataModels.Products.SubscriptionStatus?desiredSubscriptionStatus = null; var subscriptions = new List <Jibberwock.DataModels.Products.Subscription>(); switch (subscription?.Status?.ToLower()) { case SubscriptionStatuses.Trialing: desiredSubscriptionStatus = DataModels.Products.SubscriptionStatus.Trial; break; case SubscriptionStatuses.Active: desiredSubscriptionStatus = DataModels.Products.SubscriptionStatus.Active; break; case SubscriptionStatuses.PastDue: desiredSubscriptionStatus = DataModels.Products.SubscriptionStatus.Expired; break; case SubscriptionStatuses.Canceled: case SubscriptionStatuses.Unpaid: case SubscriptionStatuses.IncompleteExpired: desiredSubscriptionStatus = DataModels.Products.SubscriptionStatus.Unpaid; break; case SubscriptionStatuses.Incomplete: desiredSubscriptionStatus = DataModels.Products.SubscriptionStatus.PaymentPending; break; } // Map the jibberwock_ids parameter to a list of Jibberwock subscription IDs, if it's present if (subscription.Metadata.TryGetValue("jibberwock_ids", out var rawSubscriptionIds)) { var idList = rawSubscriptionIds.Split(';', StringSplitOptions.RemoveEmptyEntries); foreach (var id in idList) { if (long.TryParse(id, out var parsedId)) { subscriptions.Add(new Jibberwock.DataModels.Products.Subscription() { Id = parsedId }); } } } var syncSubscriptionCommand = new Jibberwock.Persistence.DataAccess.Commands.Products.SyncSubscriptionsFromBillingProvider(logger, null, contextAccessor.HttpContext.TraceIdentifier, webApiConfiguration.Authorization.DefaultServiceId, null, subscriptions, desiredSubscriptionStatus, subscription.Id, subscription.LatestInvoiceId); await syncSubscriptionCommand.Execute(sqlDataSource); }
public static Pageable <OrderItemResource> GetOrderItemResources(this Subscription subscription, string filter = null, string expand = null, string skipToken = null, CancellationToken cancellationToken = default) { return(GetExtensionClient(subscription).GetOrderItemResources(filter, expand, skipToken, cancellationToken)); }
private void WriteMI_Click(object sender, EventArgs e) { try { // get the current session. Session session = Get <Session>(NodesTV.SelectedNode); if (session == null || !session.Connected) { return; } // build list of nodes to read. WriteValueCollection values = new WriteValueCollection(); MonitoredItem monitoredItem = Get <MonitoredItem>(NodesTV.SelectedNode); if (monitoredItem != null) { WriteValue value = new WriteValue(); value.NodeId = monitoredItem.ResolvedNodeId; value.AttributeId = monitoredItem.AttributeId; value.IndexRange = monitoredItem.IndexRange; MonitoredItemNotification datachange = monitoredItem.LastValue as MonitoredItemNotification; if (datachange != null) { value.Value = (DataValue)Utils.Clone(datachange.Value); } values.Add(value); } else { Subscription subscription = Get <Subscription>(NodesTV.SelectedNode); if (subscription != null) { foreach (MonitoredItem item in subscription.MonitoredItems) { WriteValue value = new WriteValue(); value.NodeId = item.ResolvedNodeId; value.AttributeId = item.AttributeId; value.IndexRange = item.IndexRange; MonitoredItemNotification datachange = item.LastValue as MonitoredItemNotification; if (datachange != null) { value.Value = (DataValue)Utils.Clone(datachange.Value); } values.Add(value); } } } // show form. new WriteDlg().Show(session, values); } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }
public static Pageable <ProductFamiliesMetadataDetails> GetProductFamiliesMetadata(this Subscription subscription, string skipToken = null, CancellationToken cancellationToken = default) { return(GetExtensionClient(subscription).GetProductFamiliesMetadata(skipToken, cancellationToken)); }
public static Pageable <AddressResource> GetAddressResources(this Subscription subscription, string filter = null, string skipToken = null, CancellationToken cancellationToken = default) { return(GetExtensionClient(subscription).GetAddressResources(filter, skipToken, cancellationToken)); }
public AddSubscriptionWorkflowStepResult(bool success, string workDescription, string errorMessage, Subscription subscription) : base(success, workDescription, errorMessage) { this.Subscription = subscription; }
public static Pageable <OrderResource> GetOrderResources(this Subscription subscription, string skipToken = null, CancellationToken cancellationToken = default) { return(GetExtensionClient(subscription).GetOrderResources(skipToken, cancellationToken)); }
public async Task CreateCommonClient() { Client = GetArmClient(); DefaultSubscription = await Client.GetDefaultSubscriptionAsync(); }
public static Pageable <ProductConfiguration> GetConfigurations(this Subscription subscription, ConfigurationsRequest configurationsRequest, string skipToken = null, CancellationToken cancellationToken = default) { Argument.AssertNotNull(configurationsRequest, nameof(configurationsRequest)); return(GetExtensionClient(subscription).GetConfigurations(configurationsRequest, skipToken, cancellationToken)); }
private void OnLocalPlayerReady(Subscription subscription) { int playerId = subscription.Read <int> (0); photonView.RPC("SetPlayerReady", PhotonTargets.Others); }
public ICommandResult Handle(CreateBoletoSubscriptionCommand command) { //Fail Fast Validations command.Validate(); if (command.Invalid) { AddNotifications(command); return(new CommandResult(false, "Não foi possível realizar sua ssinatura")); } // Verificar se documento está cadastrado if (_repository.DocumentExists(command.PayerDocument)) { AddNotifications(new Contract()); return(new CommandResult(false, "Esse CPF já está em uso")); } //Verificar se E-mail já está cadastrado if (_repository.EmailExists(command.PayerEmail)) { AddNotifications(new Contract()); return(new CommandResult(false, "Esse E-mail já está em uso")); } //Gerar os VOs var name = new Name(command.FirstName, command.LastName); var doc = new Document(command.PayerDocument, EDocumentType.CPF); var email = new Email(command.PayerEmail); var address = new Address(command.Street, command.Number, command.Neighborhood, command.City, command.State, command.Country, command.ZipCode); //Gerar as Entidades var student = new Student(name, doc, email); var subscription = new Subscription(DateTime.Now.AddMonths(1)); var payment = new BoletoPayment( command.BarCode, command.BoletoNumber, command.PaidDate, command.ExpireDate, command.Total, command.TotalPaid, command.Payer, new Document(command.PayerDocument, command.PayerDocumentType), address, email); //Relacionamentos subscription.AddPayment(payment); student.AddSubscription(subscription); //Agrupar as Validações AddNotifications(name, doc, email, address, student, subscription, payment); //Checar as notificações if (Invalid) { return(new CommandResult(false, "Assinatura realizada com sucesso")); } //Salvar as Informações _repository.CreateSubscription(student); //Enviar E-mail de boas vindas _emailService.Send(student.Name.FirstName, student.Email.Address, "Bem vindo", "Sua assinatura foi criada"); //Retornar informações return(new CommandResult(true, "Assinatura realizada com sucesso")); }
private void OnWorldReady(Subscription subscription) { photonView.RPC("SetWorldReady", PhotonTargets.Others); }
public async Task <ActionResult <Subscription> > PostSubscriptions([FromBody] Subscription subscription) { using (var client = new HttpClient()) { // Add an Accept header for JSON format. client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Add("Authorization", this.Request.Headers["Authorization"].ToString()); client.BaseAddress = new Uri("http://localhost:62793/"); try { //Update Availability var response = client.PutAsync($"/Books/{subscription.BookId}", new StringContent(subscription.BookId, Encoding.UTF8, "application/json")).Result; if (response.StatusCode == HttpStatusCode.OK) { _context.SubscriptionList.Add(subscription); await _context.SaveChangesAsync(); string jsonMessage = response.Content.ReadAsStringAsync().Result; // De-serialize var bookDetail = (Books) JsonConvert.DeserializeObject(jsonMessage, typeof(Books)); if (bookDetail?.copiesAvailable <= 0 && subscription.Notify) { // Get the Customer details and email address //client.DefaultRequestHeaders.Clear(); response = client.GetAsync($"/Customer/{subscription.SubscriberName}").Result; if (response.StatusCode == HttpStatusCode.OK) { jsonMessage = response.Content.ReadAsStringAsync().Result; // De-serialize var customer = (Customer) JsonConvert.DeserializeObject(jsonMessage, typeof(Customer)); //Add the alert for the cuscriber as user opted for Notification of availability //client.DefaultRequestHeaders.Clear(); string registerUserJson = RegisterUserJson(subscription.BookId, subscription.Id, customer.Email); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, client.BaseAddress.ToString()) { Content = new StringContent(registerUserJson, Encoding.UTF8, "application/json") }; request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); response = client.PostAsync($"/AlertSubscription", request.Content).Result; } } //Send alert to all user as books are available if (bookDetail?.copiesAvailable > 0) { //client.DefaultRequestHeaders.Clear(); response = client.GetAsync($"/AlertSubscription/{subscription.BookId}").Result; } } } catch (Exception exception) { throw exception; } } return(CreatedAtAction(nameof(GetSubscriptionLists), new { id = subscription.BookId }, subscription)); }
private void OnSpawnPointSet(Subscription subscription) { PlayerInfo player = subscription.Read <PlayerInfo>(0); photonView.RPC("SetPlayerSpawnPoint", PhotonTargets.Others, player.ID, player.Position); }
private void OnMatchStart(Subscription subscription) { photonView.RPC("StartMatch", PhotonTargets.All); }
public Subscription AddOrUpdateSubscription(Subscription subscription) { return(AddOrUpdateSubscriptionAsync(subscription).GetAwaiter().GetResult()); }
private void OnItemSpawn(Subscription subscription) { PickupItem item = subscription.Read <PickupItem> (0); photonView.RPC("SpawnItem", PhotonTargets.Others, item.ID, item.gameObject.name, item.gameObject.transform.position, item.Owner, item.ObjectiveForPlayer, item.ObjectiveIndex); }
private void OnEnable() { inputEventSubscription = PublisherSubscriber.Subscribe <InputEventArgs>(Move); }
private bool ConstraintUnique(Subscription subscription) { return(eventSubscriptions[subscription.EventType] .Where(s => s != subscription) .All(s => s.ConstraintId != subscription.ConstraintId)); }