public override TransactionInfo ProcessSubscription(ref SubscriptionInfo sub, GatewayInfo gateway, GatewayTypeInfo gatewayType, ICustomer customer, CreditCardInfo card, bool isTrial, bool testTransaction) { ProPayRequest request = null; ProPayResponse response = null; TransactionInfo transactionInfo = new TransactionInfo(); string requestUrl = testTransaction == true ? gatewayType.TestUrl : gatewayType.LiveUrl; string loginId = testTransaction == true ? gatewayType.TestLoginId : gateway.LoginId; string transactionKey = testTransaction == true ? gatewayType.TestTransactionKey : gateway.TransactionKey; decimal amount = isTrial == true ? sub.TrialAmount : sub.Amount; request = new ProPayRequest(requestUrl, loginId, transactionKey, customer, card, amount, testTransaction); response = request.Process(); sub.LastProcessedDate = DateTime.Now; transactionInfo.Id = Guid.NewGuid(); transactionInfo.SubscriptionId = sub.Id; transactionInfo.GatewayId = sub.GatewayId; transactionInfo.CreateDate = DateTime.Now; transactionInfo.IsTrial = isTrial; transactionInfo.Type = TransactionType.Standard; transactionInfo.Amount = amount; transactionInfo.GatewayAmount = gateway.TransactionFee; transactionInfo.OrderId = sub.RefId; if (response == null) { sub.LastProcessingStatus = TransactionStatus.Error; transactionInfo.ResponseText = ""; transactionInfo.Status = TransactionStatus.Error; } else if (response.Code == ProPayResponseCode.Success) { sub.LastProcessingStatus = TransactionStatus.Approved; if (isTrial) sub.TrialOccurrencesDone += 1; else sub.TotalOccurrencesDone += 1; transactionInfo.ResponseText = response.ResponseText; transactionInfo.Status = TransactionStatus.Approved; } else { sub.LastProcessingStatus = TransactionStatus.Error; transactionInfo.ResponseText = response.ResponseText; transactionInfo.Status = TransactionStatus.Error; } return transactionInfo; }
public string CreateSubscription(ConnectionInfo connectionInfo, string subscriptionQuery, SubscriberCallback callback) { if (!connectionInfo.CanCreateSubscription) throw new InvalidOperationException("This connection doesn't support subscriptions"); SubscriptionInfo subInfo; if (!proxies.TryGetValue(connectionInfo, out subInfo)) { var listener = CreateListener(connectionInfo); subInfo = new SubscriptionInfo() { Proxy = listener }; proxies[connectionInfo] = subInfo; connectionInfo.ConnectionClosing += ServerConnectionClosing; } var subscriptionId = Subscribe(connectionInfo, subscriptionQuery); subInfo.SubscriptionIDs.Add(subscriptionId); var key = GetSubscriptionKeyFromUri(subscriptionId); subscriptions.TryAdd(key, callback); return subscriptionId; }
public int AddSubscription(SubscriptionInfo objSubscription) { return dataProvider.AddSubscription(objSubscription.PortalId, objSubscription.ModuleId, objSubscription.ForumId, objSubscription.TopicId, objSubscription.SubscriptionType, objSubscription.UserId); }
public bool RemoveSubscription(SubscriptionInfo subscriptionInfo) { //use subscription IDentifier if (string.Compare(subscriptionInfo.ClientId, ClientID, true) != 0) { return(false); } SubscriptionIdentifier subscriptionIdentifier = new SubscriptionIdentifier(subscriptionInfo.SubscriptionId, subscriptionInfo.SubPolicyType); List <Message> removedMessages = new List <Message>(); bool result = false; lock (this) { _lastActivityTime = _updateTime = DateTime.Now; switch (subscriptionInfo.Type) { case Common.Enum.SubscriptionType.Subscriber: if (_messageSubscriptions.ContainsKey(subscriptionIdentifier)) { result = _messageSubscriptions.Remove(subscriptionIdentifier); _messageSubscriptionLoadbalancer.Remove(subscriptionIdentifier); } break; case Common.Enum.SubscriptionType.Publisher: if (_deliverySubscriptions.ContainsKey(subscriptionIdentifier)) { result = _deliverySubscriptions.Remove(subscriptionIdentifier); _deliverSubscriptionLoadbalancer.Remove(subscriptionIdentifier); } break; } foreach (Message message in _messages.Values) { if (message.MessageMetaData.DeliveryOption == Runtime.Caching.DeliveryOption.Any) { message.MessageMetaData.RemoveRecepient(subscriptionInfo.SubscriptionId); message.MessageMetaData.RemoveFromReciepientList(subscriptionIdentifier); } message.MessageMetaData.UnregisterSubscription(this); if (message.MessageMetaData.IsRemovable) { removedMessages.Add(message); } } foreach (Message message in _delivryNotificationMessages.Values) { message.MessageMetaData.UnregisterSubscription(this); message.MessageMetaData.RemoveRecepient(subscriptionInfo.SubscriptionId); message.MessageMetaData.RemoveFromReciepientList(subscriptionIdentifier); if (message.MessageMetaData.IsRemovable) { removedMessages.Add(message); } } } foreach (Message message in removedMessages) { if (message.MessageMetaData.SubscriptionType == Common.Enum.SubscriptionType.Publisher) { _delivryNotificationMessages.Remove(message.MessageId); } else { _messages.Remove(message.MessageId); } _topic.OnSubscriptonRemoved(message, subscriptionInfo); } _refreshSubscriptions.Remove(subscriptionIdentifier); return(result); }
private void DoAddSubscription(Type handlerType, string eventName, bool isDynamic) { if (!HasSubscriptionsForEvent(eventName)) { _handlers.Add(eventName, new List <SubscriptionInfo>()); } if (_handlers[eventName].Any(s => s.HandlerType == handlerType)) { throw new ArgumentException( $"Handler Type {handlerType.Name} already registered for '{eventName}'", nameof(handlerType)); } _handlers[eventName].Add(isDynamic ? SubscriptionInfo.Dynamic(handlerType) : SubscriptionInfo.Typed(handlerType)); }
private void RemoveSubscriptionFromRedis(SubscriptionInfo info) { var id = info.SubscriptionId; using (var redis = clientsManager.GetClient()) using (var trans = redis.CreateTransaction()) { trans.QueueCommand(r => r.Remove(RedisIndex.Subscription.Fmt(id))); trans.QueueCommand(r => r.RemoveItemFromSortedSet(RedisIndex.ActiveSubscriptionsSet, id)); trans.QueueCommand(r => r.RemoveItemFromSet(RedisIndex.UserIdSet.Fmt(info.UserId), id)); foreach (var channel in info.Channels) { trans.QueueCommand(r => r.RemoveItemFromSet(RedisIndex.ChannelSet.Fmt(channel), id)); } if (info.UserName != null) trans.QueueCommand(r => r.RemoveItemFromSet(RedisIndex.UserNameSet.Fmt(info.UserName), id)); if (info.SessionId != null) trans.QueueCommand(r => r.RemoveItemFromSet(RedisIndex.SessionSet.Fmt(info.SessionId), id)); trans.Commit(); } }
public void UpdateNotifyDate(SubscriptionInfo subscription) { _subscriptionRepository.UpdateNotifyDate(subscription); }
public async Task <ISubscriptionProcessor.SubResult> ProcessSubscription(SubscriptionInfo subscriptionInfo) { User user = subscriptionInfo.Subscriber; if (user.MonthsSubscribed > 0 && user.SubscriptionTier == null) { _logger.LogWarning("Subscriber {User} has no subscription tier recorded. Assuming Tier 1", user); user = await _userRepo.SetSubscriptionInfo( user, user.MonthsSubscribed, SubscriptionTier.Tier1, user.LoyaltyLeague, user.SubscriptionUpdatedAt); } if (user.MonthsSubscribed == subscriptionInfo.NumMonths && user.SubscriptionTier?.ToRank() >= subscriptionInfo.Tier.ToRank()) { // If twitch reports the new months as being the same as the old months, such as due to repeated message // or other error, ignore the sub but send a warning to the user in case of issues. return(new ISubscriptionProcessor.SubResult.SameMonth(subscriptionInfo.NumMonths)); } bool subCountCorrected = false; if (user.MonthsSubscribed > subscriptionInfo.NumMonths) { // Repair the user data and re-read it for further processing. // Set to current months - 1 to process as a 1-month subscription further down. user = await _userRepo.SetSubscriptionInfo( user, subscriptionInfo.NumMonths - 1, subscriptionInfo.Tier, user.LoyaltyLeague, user.SubscriptionUpdatedAt); subCountCorrected = true; } // If our internal months subscribed count is less than what Twitch says it is, // we update our count and give the subscriber "back pay" tokens. // This can occur when users (re)subscribe while the tpp bot is down. Debug.Assert(subscriptionInfo.NumMonths > user.MonthsSubscribed || (subscriptionInfo.NumMonths == user.MonthsSubscribed && subscriptionInfo.Tier.ToRank() > user.SubscriptionTier !.Value.ToRank())); // Difference between previous recorded subscribed months and new amount. int monthsDifference = subscriptionInfo.NumMonths - user.MonthsSubscribed; int loyaltyCompletions; if (monthsDifference > 0) { // Additional benefits for expensive plans are given only for the current months to prevent users from // tricking us into giving them extra "back pay", e.g. by purposefully not announcing lower grade // subscriptions from previous months. loyaltyCompletions = monthsDifference - 1 + subscriptionInfo.Tier.ToRank(); } else { Debug.Assert(user.SubscriptionTier.HasValue, "no months difference must mean it's a tier upgrade, so the user has subscribed before"); // Same month, but an upgrade in subscription tier. Pay the difference in monetary rank. loyaltyCompletions = subscriptionInfo.Tier.ToRank() - user.SubscriptionTier.Value.ToRank(); } const int maxLeague = 15; const int tokensPerLeague = 2; const int baseTokens = 10; int newLoyaltyLeague = Math.Min(user.LoyaltyLeague + loyaltyCompletions, maxLeague); int tokens = Enumerable .Range(user.LoyaltyLeague, loyaltyCompletions) .Select(league => baseTokens + Math.Min(league, maxLeague) * tokensPerLeague) .Sum(); int oldLoyaltyLeague = user.LoyaltyLeague; SubscriptionLog subscriptionLog = await _subscriptionLogRepo.LogSubscription( user.Id, subscriptionInfo.SubscriptionAt, subscriptionInfo.StreakMonths, user.MonthsSubscribed, subscriptionInfo.NumMonths, monthsDifference, oldLoyaltyLeague, newLoyaltyLeague, loyaltyCompletions, tokens, subscriptionInfo.Message, subscriptionInfo.Tier, subscriptionInfo.PlanName); TransactionLog transactionLog = await _tokenBank.PerformTransaction(new Transaction <User>( user, tokens, TransactionType.Subscription, new Dictionary <string, object?> { ["previous_months_subscribed"] = user.MonthsSubscribed, ["new_months_subscribed"] = subscriptionInfo.NumMonths, ["months_difference"] = monthsDifference, ["previous_loyalty_tier"] = oldLoyaltyLeague, ["new_loyalty_tier"] = newLoyaltyLeague, ["loyalty_completions"] = loyaltyCompletions })); user = await _userRepo.SetIsSubscribed(user, true); user = await _userRepo.SetSubscriptionInfo( user, subscriptionInfo.NumMonths, subscriptionInfo.Tier, newLoyaltyLeague, subscriptionInfo.SubscriptionAt); return(new ISubscriptionProcessor.SubResult.Ok( DeltaTokens: tokens, OldLoyaltyLeague: oldLoyaltyLeague, NewLoyaltyLeague: newLoyaltyLeague, CumulativeMonths: subscriptionInfo.NumMonths, SubCountCorrected: subCountCorrected)); }
public void Subscribe(SubscriptionInfo subscriber) { Facade.Subscribe(subscriber); }
public override void ExecuteCommand(ClientManager clientManager, Common.Protobuf.Command command) { System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); int overload = 1; bool subscribed = false; string exceptionMessage = null; try { NCache nCache = clientManager.CmdExecuter as NCache; var operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation); if (command.commandVersion < 1) { operationContext.Add(OperationContextFieldName.ClientLastViewId, forcedViewId); } else //NCache 4.1 SP1 or later { operationContext.Add(OperationContextFieldName.ClientLastViewId, command.clientLastViewId.ToString(CultureInfo.InvariantCulture)); } if (nCache != null) { _command = command.subscribeTopicCommand; SubscriptionInfo subscriptionInfo = new SubscriptionInfo() { SubscriptionId = _command.subscriptionName, ClientId = clientManager.ClientID, Type = (SubscriptionType)_command.pubSubType, SubPolicyType = (SubscriptionPolicyType)_command.subscriptionPolicy, CreationTime = _command.creationTime, Expiration = _command.expirationTime }; SubscriptionOperation subOperation = new SubscriptionOperation(_command.topicName, TopicOperationType.Subscribe, subscriptionInfo); subscribed = nCache.Cache.TopicOpertion(subOperation, operationContext); stopWatch.Stop(); //Common.Protobuf.Response response = new Common.Protobuf.Response(); Common.Protobuf.SubscribeTopicResponse subscribeTopicResponse = new Common.Protobuf.SubscribeTopicResponse(); subscribeTopicResponse.success = subscribed; if (clientManager.ClientVersion >= 5000) { Common.Util.ResponseHelper.SetResponse(subscribeTopicResponse, command.requestID, command.commandID); _serializedResponsePackets.Add(Common.Util.ResponseHelper.SerializeResponse(subscribeTopicResponse, Common.Protobuf.Response.Type.SUBSCRIBE_TOPIC)); } else { //PROTOBUF:RESPONSE Common.Protobuf.Response response = new Common.Protobuf.Response(); response.subscribeTopicResponse = subscribeTopicResponse; Common.Util.ResponseHelper.SetResponse(response, command.requestID, command.commandID, Common.Protobuf.Response.Type.SUBSCRIBE_TOPIC); _serializedResponsePackets.Add(Alachisoft.NCache.Common.Util.ResponseHelper.SerializeResponse(response)); } } } catch (Exception exc) { exceptionMessage = exc.ToString(); _serializedResponsePackets.Add(ResponseHelper.SerializeExceptionResponseWithType(exc, command.requestID, command.commandID, clientManager.ClientVersion)); } finally { TimeSpan executionTime = stopWatch.Elapsed; try { if (Alachisoft.NCache.Management.APILogging.APILogManager.APILogManger != null && Alachisoft.NCache.Management.APILogging.APILogManager.EnableLogging) { APILogItemBuilder log = new APILogItemBuilder(MethodsName.CreateTopicSubscriptoin); log.GenerateSubscribeToTopicAPILogItem(_command.topicName, (SubscriptionType)_command.pubSubType, executionTime, clientManager.ClientID, clientManager.ClientIP, overload, subscribed, exceptionMessage, APIClassNames.TOPIC); } } catch { } } }
private async Task RunAsync(SubscriptionInfo info) { if (IsDisposed) { return; } long oldLastProcessedCheckpoint; lock (syncRoot) { oldLastProcessedCheckpoint = lastProcessedCheckpoint; } if (memoryEventSource.IsFutureCheckpoint(oldLastProcessedCheckpoint)) { await subscriber.NoSuchCheckpoint(info).ConfigureAwait(false); } #pragma warning disable 4014 // Run continuations asynchronously. Task.Run(() => waitForCheckingWhetherItIsAheadCompletionSource.TrySetResult(false)); #pragma warning restore 4014 int nextTransactionIndex = memoryEventSource.GetNextTransactionIndex(oldLastProcessedCheckpoint); while (!IsDisposed) { Task waitForNewTransactions = memoryEventSource.WaitForNewTransactions(); Transaction[] transactions = memoryEventSource.GetTransactionsFromIndex(nextTransactionIndex); Transaction[] requestedTransactions = transactions .Where(transaction => transaction.Checkpoint > oldLastProcessedCheckpoint) .ToArray(); foreach (IList <Transaction> batch in requestedTransactions.InBatchesOf(batchSize)) { await subscriber.HandleTransactions(new ReadOnlyCollection <Transaction>(batch.ToList()), info) .ConfigureAwait(false); } if (requestedTransactions.Any()) { lock (syncRoot) { lastProcessedCheckpoint = requestedTransactions[requestedTransactions.Length - 1].Checkpoint; if (!isDisposed) { TaskCompletionSource <long> oldProgressCompletionSource = progressCompletionSource; progressCompletionSource = new TaskCompletionSource <long>(); #pragma warning disable 4014 // Run continuations asynchronously. Task.Run(() => oldProgressCompletionSource.SetResult(lastProcessedCheckpoint)); #pragma warning restore 4014 } } } nextTransactionIndex += transactions.Length; await waitForNewTransactions .WithWaitCancellation(cancellationTokenSource.Token) .ConfigureAwait(false); } }
private IEnumerable <MarketDataMessage> ProcessSubscriptionResult <T>(Dictionary <T, SubscriptionInfo <MarketDataMessage> > subscriptions, T key, SubscriptionInfo <MarketDataMessage> info, MarketDataMessage message) { //var info = subscriptions.TryGetValue(key); if (!subscriptions.ContainsKey(key)) { return(null); } //var isSubscribe = info.Message.IsSubscribe; //var removeInfo = !isSubscribe || !message.IsOk(); info.IsSubscribed = info.Message.IsSubscribe && message.IsOk(); var replies = new List <MarketDataMessage>(); // TODO только нужная подписка foreach (var requests in info.Requests) { var reply = (MarketDataMessage)requests.Clone(); reply.OriginalTransactionId = requests.TransactionId; //reply.TransactionId = message.TransactionId; reply.Error = message.Error; reply.IsNotSupported = message.IsNotSupported; replies.Add(reply); } if (!info.IsSubscribed) { subscriptions.Remove(key); _mdSubscribersById.RemoveWhere(p => p.Value == info); } return(replies); }
private void PollForEventMessage(string clientId) { SubscriptionInfo subscriptionInfo = new SubscriptionInfo() { SubscriptionId = SubscriptionInfo.EventsSubscriptionName, ClientId = clientId, Type = SubscriptionType.Subscriber, SubPolicyType = SubscriptionPolicyType.EventSubscription, Expiration = TimeSpan.MaxValue.Ticks }; result = context.CacheImpl.GetAssignedMessage(subscriptionInfo, operationContext); foreach (var pair in result.AssignedMessages) { IList <object> eventMessages = pair.Value; lock (eventMessages) { IEnumerator <object> enu = eventMessages.GetEnumerator(); while (enu.MoveNext()) { //Create Events here and fire var message = (EventMessage)enu.Current; EventContext eventContext = SetEventContext(message); switch (eventContext.EventID.EventType) { case Persistence.EventType.ITEM_UPDATED_CALLBACK: context.CacheImpl.RaiseOldCustomUpdateCalbackNotifier(message.Key, message.CallbackInfos, eventContext); break; case Persistence.EventType.ITEM_REMOVED_CALLBACK: CacheEntry entry = CacheEntry.CreateCacheEntry(context.FakeObjectPool); entry.Notifications = new Notifications(); entry.Notifications.ItemRemoveCallbackListener = new ArrayList(); entry.Notifications.ItemRemoveCallbackListener = message.CallbackInfos; entry.MarkInUse(NCModulesConstants.Global); context.CacheImpl.RaiseOldCustomRemoveCalbackNotifier(message.Key, entry, message.RemoveReason, operationContext, eventContext); break; } switch (message.MessageMetaData.TopicName) { case TopicConstant.ItemLevelEventsTopic: itemLevelEventsMessageIds.Add(message.MessageId); break; } } } } if (itemLevelEventsMessageIds.Count > 0) { topicWiseMessageIds.Add(TopicConstant.ItemLevelEventsTopic, itemLevelEventsMessageIds); itemLevelEventsMessageIds = new List <string>(); } if (topicWiseMessageIds.Count > 0) { context.CacheImpl.AcknowledgeMessageReceipt(clientId, topicWiseMessageIds, operationContext); topicWiseMessageIds = new Dictionary <string, IList <string> >(); } }
public override void ExecuteCommand(ClientManager clientManager, Common.Protobuf.Command command) { System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch(); stopWatch.Start(); int overload = 1; string exceptionMessage = null; try { NCache nCache = clientManager.CmdExecuter as NCache; if (nCache != null) { _command = command.getMessageCommand; var operationContext = new OperationContext(OperationContextFieldName.OperationType, OperationContextOperationType.CacheOperation); CommandsUtil.PopulateClientIdInContext(ref operationContext, clientManager.ClientAddress); if (command.commandVersion < 1) { operationContext.Add(OperationContextFieldName.ClientLastViewId, forcedViewId); } else //NCache 4.1 SP1 or later { operationContext.Add(OperationContextFieldName.ClientLastViewId, command.clientLastViewId.ToString(CultureInfo.InvariantCulture)); } _clientId = clientManager.ClientID; SubscriptionInfo subInfo = new SubscriptionInfo() { ClientId = clientManager.ClientID }; MessageResponse response = nCache.Cache.GetAssignedMessages(subInfo, operationContext); stopWatch.Stop(); //filter event messages for older clients that use pubsub if (clientManager.ClientVersion < 5000) { if (response.AssignedMessages.ContainsKey(TopicConstant.ItemLevelEventsTopic)) { response.AssignedMessages.Remove(TopicConstant.ItemLevelEventsTopic); } if (response.AssignedMessages.ContainsKey(TopicConstant.CollectionEventsTopic)) { response.AssignedMessages.Remove(TopicConstant.CollectionEventsTopic); } } GetMessageResponseBuilder.BuildResponse(response.AssignedMessages, command.commandVersion, _command.requestId.ToString(CultureInfo.InvariantCulture), _serializedResponsePackets, command.commandID, command.requestID, nCache, _clientId, clientManager); } } catch (System.Exception exc) { exceptionMessage = exc.ToString(); _serializedResponsePackets.Add(ResponseHelper.SerializeExceptionResponseWithType(exc, command.requestID, command.commandID, clientManager.ClientVersion)); } finally { TimeSpan executionTime = stopWatch.Elapsed; try { if (Alachisoft.NCache.Management.APILogging.APILogManager.APILogManger != null && Alachisoft.NCache.Management.APILogging.APILogManager.EnableLogging) { APILogItemBuilder log = new APILogItemBuilder(MethodsName.GetTopicMessages); log.GenerateGetTopicMessagesAPILogItem(executionTime, clientManager.ClientID, clientManager.ClientIP, overload, _messages, exceptionMessage); // Hashtable expirationHint = log.GetDependencyExpirationAndQueryInfo(cmdInfo.ExpirationHint, cmdInfo.queryInfo); } } catch { } } }
//Public Subs As List(Of SubscriptionInfo) public bool SendMail() { try { Hashtable objHost; if (SmtpServer == "") { objHost = Entities.Portals.PortalSettings.GetHostSettings(); SmtpServer = Host.SMTPServer; // Convert.ToString(objHost["SMTPServer"]); SmtpUserName = Host.SMTPUsername; // Convert.ToString(objHost["SMTPUsername"]); SmtpPassword = Host.SMTPPassword;// Convert.ToString(objHost["SMTPPassword"]); SmtpAuthentication = Host.SMTPAuthentication;// Convert.ToString(objHost["SMTPAuthentication"]); SmtpSSL = Host.EnableSMTPSSL.ToString();// Convert.ToString(objHost["SMTPEnableSSL"]); } //Dim Email As New System.Net.Mail.MailMessage //Email.From = New System.Net.Mail.MailAddress(SendFrom) //Email.To.Add(New System.Net.Mail.MailAddress(SendTo)) //Email.Subject = Subject //Email.IsBodyHtml = True //Email.Body = Body var subs = new List<SubscriptionInfo>(); var si = new SubscriptionInfo {Email = SendTo, DisplayName = string.Empty, LastName = string.Empty, FirstName = string.Empty}; subs.Add(si); var oEmail = new Email { UseQueue = false, Recipients = subs, Subject = Subject, From = SendFrom, BodyText = BodyText, BodyHTML = Body, SmtpServer = SmtpServer, SmtpUserName = SmtpUserName, SmtpPassword = SmtpPassword, SmtpAuthentication = SmtpAuthentication, SmtpSSL = SmtpSSL }; try { var objThread = new System.Threading.Thread(oEmail.Send); objThread.Start(); return true; } catch (Exception ex) { Services.Exceptions.Exceptions.LogException(ex); return false; } } catch (Exception ex) { Services.Exceptions.Exceptions.LogException(ex); return false; } }
private void ChangeState(SubscriptionInfo info, SubscriptionStates state) { info.State = info.State.ChangeSubscriptionState(state, info.Subscription.TransactionId, this, !_allSecIdChilds.Contains(info.Subscription.TransactionId)); }
/// <summary> /// Subscribes (or re-subscribes) to a data publisher for a set of data points. /// </summary> /// <param name="info">Configuration object that defines the subscription.</param> /// <returns><c>true</c> if subscribe transmission was successful; otherwise <c>false</c>.</returns> public bool Subscribe(SubscriptionInfo info) { if (info is SynchronizedSubscriptionInfo) return SynchronizedSubscribe((SynchronizedSubscriptionInfo)info); if (info is UnsynchronizedSubscriptionInfo) return UnsynchronizedSubscribe((UnsynchronizedSubscriptionInfo)info); throw new NotSupportedException("Type of subscription used is not supported"); }
private IEnumerable <SubscriptionInfo> ToDto(HttpEntityManager manager, MonitoringMessage.GetPersistentSubscriptionStatsCompleted message) { if (message == null) { yield break; } if (message.SubscriptionStats == null) { yield break; } foreach (var stat in message.SubscriptionStats) { string escapedStreamId = Uri.EscapeDataString(stat.EventStreamId); string escapedGroupName = Uri.EscapeDataString(stat.GroupName); var info = new SubscriptionInfo { Links = new List <RelLink>() { new RelLink( MakeUrl(manager, string.Format("/subscriptions/{0}/{1}/info", escapedStreamId, escapedGroupName)), "detail"), new RelLink( MakeUrl(manager, string.Format("/subscriptions/{0}/{1}/replayParked", escapedStreamId, escapedGroupName)), "replayParked") }, EventStreamId = stat.EventStreamId, GroupName = stat.GroupName, Status = stat.Status, AverageItemsPerSecond = stat.AveragePerSecond, TotalItemsProcessed = stat.TotalItems, CountSinceLastMeasurement = stat.CountSinceLastMeasurement, LastKnownEventNumber = stat.LastKnownMessage, LastProcessedEventNumber = stat.LastProcessedEventNumber, ReadBufferCount = stat.ReadBufferCount, LiveBufferCount = stat.LiveBufferCount, RetryBufferCount = stat.RetryBufferCount, TotalInFlightMessages = stat.TotalInFlightMessages, OutstandingMessagesCount = stat.OutstandingMessagesCount, ParkedMessageUri = MakeUrl(manager, string.Format(parkedMessageUriTemplate, escapedStreamId, escapedGroupName)), GetMessagesUri = MakeUrl(manager, string.Format("/subscriptions/{0}/{1}/{2}", escapedStreamId, escapedGroupName, DefaultNumberOfMessagesToGet)), Config = new SubscriptionConfigData { CheckPointAfterMilliseconds = stat.CheckPointAfterMilliseconds, BufferSize = stat.BufferSize, LiveBufferSize = stat.LiveBufferSize, MaxCheckPointCount = stat.MaxCheckPointCount, MaxRetryCount = stat.MaxRetryCount, MessageTimeoutMilliseconds = stat.MessageTimeoutMilliseconds, MinCheckPointCount = stat.MinCheckPointCount, NamedConsumerStrategy = stat.NamedConsumerStrategy, PreferRoundRobin = stat.NamedConsumerStrategy == SystemConsumerStrategies.RoundRobin, ReadBatchSize = stat.ReadBatchSize, ResolveLinktos = stat.ResolveLinktos, StartFrom = stat.StartFrom, ExtraStatistics = stat.ExtraStatistics, MaxSubscriberCount = stat.MaxSubscriberCount }, Connections = new List <ConnectionInfo>() }; if (stat.Connections != null) { foreach (var connection in stat.Connections) { info.Connections.Add(new ConnectionInfo { Username = connection.Username, From = connection.From, AverageItemsPerSecond = connection.AverageItemsPerSecond, CountSinceLastMeasurement = connection.CountSinceLastMeasurement, TotalItemsProcessed = connection.TotalItems, AvailableSlots = connection.AvailableSlots, InFlightMessages = connection.InFlightMessages, ExtraStatistics = connection.ObservedMeasurements ?? new List <Measurement>(), ConnectionName = connection.ConnectionName, }); } } yield return(info); } }
/// <summary> /// Standardizes the specified address. /// </summary> /// <remarks> /// The StrikeIron address verification will also attempt to geocode the address. If this /// geocode is succesful, the Geocode information of the address will be updated also. /// </remarks> /// <param name="location">The location.</param> /// <param name="result">The result.</param> /// <returns> /// True/False value of whether the address was standardized was succesfully /// </returns> public override bool Standardize(Rock.Model.Location location, out string result) { if (location != null) { var registeredUser = new RegisteredUser(); registeredUser.UserID = GetAttributeValue("UserID"); registeredUser.Password = GetAttributeValue("Password"); var licenseInfo = new LicenseInfo(); licenseInfo.RegisteredUser = registeredUser; var client = new USAddressVerificationSoapClient(); SIWsOutputOfUSAddress verifyResult; SubscriptionInfo info = client.VerifyAddressUSA( licenseInfo, location.Street1, location.Street2, string.Format("{0} {1} {2}", location.City, location.State, location.Zip), string.Empty, string.Empty, CasingEnum.PROPER, out verifyResult); if (verifyResult != null) { result = verifyResult.ServiceStatus.StatusNbr.ToString(); if (verifyResult.ServiceStatus.StatusNbr == 200) { USAddress usAddress = verifyResult.ServiceResult; if (usAddress != null && usAddress.GeoCode != null) { location.Street1 = usAddress.AddressLine1; location.Street2 = usAddress.AddressLine2; location.City = usAddress.City; location.State = usAddress.State; location.Zip = usAddress.ZIPPlus4; if (usAddress.GeoCode != null) { location.GeocodeAttemptedServiceType = "StrikeIron"; location.GeocodeAttemptedResult = "200"; location.GeocodedDateTime = DateTime.Now; location.SetLocationPointFromLatLong(usAddress.GeoCode.Latitude, usAddress.GeoCode.Longitude); } return(true); } } } else { result = "Null Result"; } } else { result = "Null Address"; } return(false); }
private void ChangeState(SubscriptionInfo info, SubscriptionStates state) { var subscription = info.Subscription; subscription.State = subscription.State.ChangeSubscriptionState(state, subscription.TransactionId, _connector, info.Parent == null); }
/// <inheritdoc /> public override void SendInMessage(Message message) { switch (message.Type) { case MessageTypes.Reset: { _subscriptions.Clear(); _subscriptionsById.Clear(); break; } case MessageTypes.MarketData: { var mdMsg = (MarketDataMessage)message; if (mdMsg.SecurityId.IsDefault()) { break; } var security = _securityProvider.LookupById(mdMsg.SecurityId); if (security == null || !security.IsBasket()) { break; } if (mdMsg.IsSubscribe) { var processor = _processorProvider.CreateProcessor(security); var info = new SubscriptionInfo(processor, mdMsg.TransactionId); var dict = _subscriptions.SafeAdd(mdMsg.DataType); _subscriptionsById.Add(mdMsg.TransactionId, info); var inners = new MarketDataMessage[processor.BasketLegs.Length]; for (var i = 0; i < inners.Length; i++) { var inner = (MarketDataMessage)mdMsg.Clone(); inner.TransactionId = TransactionIdGenerator.GetNextId(); inner.SecurityId = processor.BasketLegs[i]; inners[i] = inner; info.LegsSubscriptions.Add(inner.TransactionId); dict.Add(inner.TransactionId, info); } foreach (var inner in inners) { base.SendInMessage(inner); } } else { if (!_subscriptionsById.TryGetValue(mdMsg.OriginalTransactionId, out var info)) { break; } _subscriptionsById.Remove(mdMsg.OriginalTransactionId); foreach (var id in info.LegsSubscriptions) { base.SendInMessage(new MarketDataMessage { TransactionId = TransactionIdGenerator.GetNextId(), IsSubscribe = false, OriginalTransactionId = id }); } } RaiseNewOutMessage(new MarketDataMessage { OriginalTransactionId = mdMsg.TransactionId }); return; } } base.SendInMessage(message); }
public Subscription ProcessResponse(SubscriptionResponseMessage response, out ISubscriptionMessage originalMsg, out bool unexpectedCancelled) { originalMsg = null; SubscriptionInfo info = null; try { lock (_syncObject) { unexpectedCancelled = false; if (!_requests.TryGetValue(response.OriginalTransactionId, out var tuple)) { originalMsg = null; return(null); } // do not remove cause subscription can be interrupted after successful response //_requests.Remove(response.OriginalTransactionId); originalMsg = tuple.Item1; info = originalMsg.IsSubscribe ? TryGetInfo(originalMsg.TransactionId, false, false, null, false) : TryGetInfo(originalMsg.OriginalTransactionId, false, true, null, false); if (info == null) { originalMsg = null; return(null); } var subscription = info.Subscription; if (originalMsg.IsSubscribe) { if (response.IsOk()) { ChangeState(info, SubscriptionStates.Active); } else { ChangeState(info, SubscriptionStates.Error); Remove(subscription.TransactionId); unexpectedCancelled = subscription.State.IsActive(); _requests.Remove(response.OriginalTransactionId); } } else { ChangeState(info, SubscriptionStates.Stopped); Remove(subscription.TransactionId); // remove subscribe and unsubscribe requests _requests.Remove(subscription.TransactionId); _requests.Remove(response.OriginalTransactionId); } if (info.Parent != null) { originalMsg = null; return(null); } return(subscription); } } finally { if (info == null) { TryWriteLog(response.OriginalTransactionId); } } }
public void AddSubscriptions(SubscriptionInfo subscription) { _subscriptions.Add(subscription); }
public bool UnSubscribeSubscription(SubscriptionInfo subscriptionInfo, bool clientDisconnected = false, bool isDispose = false) { SubscriptionIdentifier subscriptionIdentifier = new SubscriptionIdentifier(subscriptionInfo.SubscriptionId, subscriptionInfo.SubPolicyType); return(RemoveSubscription(subscriptionIdentifier, subscriptionInfo, isDispose)); }
public SubscriptionInfo GetOrSubscribe(string topicArn) { SubscriptionInfo item; lock (_ConfirmedSubscriptions) { item = _ConfirmedSubscriptions.Where(s => string.Equals(s.TopicArn, topicArn, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault(); if (item is object) { return(item); } } lock (_LocalPendingSubscriptions) { item = _LocalPendingSubscriptions.Where(s => string.Equals(s.TopicArn, topicArn, StringComparison.InvariantCultureIgnoreCase)).SingleOrDefault(); if (item is object) { //orphaned - usually is takes only a few seconds until a subscription is confirmed! if (item.Initiated.AddSeconds(30) < DateTime.Now) { //just remoce thie item, becasue a new one will be created below... _LocalPendingSubscriptions.Remove(item); } return(item); } #if DEBUG if (SuppressSubscriptionDevmode) { item = new SubscriptionInfo(this, topicArn, "<dummy>", false); //simulate already confirmed subscription _LocalPendingSubscriptions.Add(item); return(item); } #endif try { using (var client = new AmazonSimpleNotificationServiceClient(this.AwsCredentials, this.AwsRegion)) { Task <SubscribeResponse> t; if (this.SubscriptionCallbackUrl.StartsWith("https:")) { t = client.SubscribeAsync(topicArn, "https", this.SubscriptionCallbackUrl); } else { t = client.SubscribeAsync(topicArn, "http", this.SubscriptionCallbackUrl); } t.Wait(); if (t.IsCompleted && t.Result is object) { item = new SubscriptionInfo(this, topicArn, t.Result.SubscriptionArn, true); _LocalPendingSubscriptions.Add(item); } else { if (t.Exception != null) { throw t.Exception; } else if (t.Result is object) { throw new Exception($"Subscribe-Task failed with Http-Status-Code: {t.Result.HttpStatusCode}!"); } else { throw new Exception($"Subscribe-Task failed!"); } } } } catch (AggregateException aex) { foreach (var subex in aex.InnerExceptions) { _ExceptionHandler.Invoke(subex); } } catch (Exception ex) { _ExceptionHandler.Invoke(ex); } } return(item); }
private bool AssignMessageToAllSubscriptions(SubscriptionInfo subscriptionInfo, Message message) { bool assigned = false; Subscriptions subscriptions; ClientSubscriptionManager clientManager; lock (_mutex) { if (subscriptionInfo.SubPolicyType != SubscriptionPolicyType.EventSubscription) { foreach (var subscription in _subscriptions) { HashSet <SubscriptionIdentifier> subscriptionIdentifierList; if (subscription.Value.IsActive() && subscription.Value.SubscriptionPolicyType == SubscriptionPolicyType.NonDurableExclusiveSubscription) { string clientId = subscription.Value.GetSubscriber(); if (!String.IsNullOrEmpty(clientId)) { if (_subscribers.TryGetValue(clientId, out clientManager)) { if (clientManager.HasMessageSubscriptons(SubscriptionType.Subscriber)) { assigned |= clientManager.AssignMessageToSubscription(message, subscriptionInfo); } } } } } } else { if (message.IsMulticast) { MultiCastMessage multicastMessage = (MultiCastMessage)message; if (multicastMessage.SpecificReciepients.Count > 0 || multicastMessage.SpecificReciepients != null) { List <SubscriptionInfo> subinfolist = multicastMessage.SpecificReciepients; foreach (var subInfo in subinfolist) { if (_subscribers.TryGetValue(subInfo.ClientId, out clientManager)) { assigned = clientManager.AssignMessageToSubscription(message, subscriptionInfo); } } } } else { SubscriptionIdentifier subscriptionIdentifier = new SubscriptionIdentifier(); subscriptionIdentifier.SubscriptionName = SubscriptionInfo.EventsSubscriptionName; subscriptionIdentifier.SubscriptionPolicy = SubscriptionPolicyType.EventSubscription; if (_subscriptions.TryGetValue(subscriptionIdentifier, out subscriptions)) { List <string> subscribedClients = subscriptions.GetSubscriberList(); if (subscriptions.IsActive() && (subscribedClients.Count > 0)) { foreach (var clientId in subscribedClients) { if (_subscribers.TryGetValue(clientId, out clientManager)) { if (clientManager.HasMessageSubscriptons(SubscriptionType.Subscriber)) { assigned |= clientManager.AssignMessageToSubscription(message, subscriptionInfo); } } } } } } } } return(assigned); }
public void UpdateSubscription(SubscriptionInfo objSubscription) { dataProvider.UpdateSubscription(objSubscription.SubscriptionId, objSubscription.PortalId, objSubscription.ModuleId, objSubscription.ForumId, objSubscription.TopicId, objSubscription.SubscriptionType, objSubscription.UserId); }
private bool ProcessInSubscriptionMessage(ISubscriptionMessage message) { if (message == null) { throw new ArgumentNullException(nameof(message)); } var transId = message.TransactionId; var isSubscribe = message.IsSubscribe; ISubscriptionMessage sendInMsg = null; Message[] sendOutMsgs = null; lock (_sync) { if (isSubscribe) { if (message.To == null) { var dataType = message.DataType; var secId = default(SecurityId); if (message is ISecurityIdMessage secIdMsg) { secId = secIdMsg.SecurityId; if (secId == default && IsSecurityRequired(dataType)) { this.AddWarningLog("Subscription {0} required security id.", dataType); } else if (secId != default && !IsSecurityRequired(dataType)) { this.AddWarningLog("Subscription {0} doesn't required security id.", dataType); } } var key = Tuple.Create(dataType, secId); if (!_subscriptionsByKey.TryGetValue(key, out var info)) { sendInMsg = message; info = new SubscriptionInfo(message.TypedClone()); _subscriptionsByKey.Add(key, info); } else { var resultMsg = message.CreateResult(); if (message.Type == MessageTypes.MarketData) { sendOutMsgs = new[] { message.CreateResponse(), resultMsg, }; } else { sendOutMsgs = new[] { resultMsg }; } } _subscriptionsById.Add(transId, info); info.Subscribers.Add(transId); } else { sendInMsg = message; } } else { ISubscriptionMessage MakeUnsubscribe(ISubscriptionMessage m, long subscriptionId) { m.IsSubscribe = false; m.TransactionId = transId; m.OriginalTransactionId = subscriptionId; return(m); } var originId = message.OriginalTransactionId; if (_subscriptionsById.TryGetValue(originId, out var info)) { if (!info.Subscribers.Remove(originId)) { sendOutMsgs = new[] { (Message)originId.CreateSubscriptionResponse(new InvalidOperationException(LocalizedStrings.SubscriptionNonExist.Put(originId))) }; } else { if (info.Subscribers.Count == 0) { _subscriptionsByKey.RemoveByValue(info); _subscriptionsById.Remove(originId); if (info.State.IsActive()) { // copy full subscription's details into unsubscribe request sendInMsg = MakeUnsubscribe(info.Subscription.TypedClone(), info.Subscription.TransactionId); } else { this.AddWarningLog(LocalizedStrings.SubscriptionInState, originId, info.State); } } else { sendOutMsgs = new[] { message.CreateResult() }; } } } else { sendOutMsgs = new[] { (Message)originId.CreateSubscriptionResponse(new InvalidOperationException(LocalizedStrings.SubscriptionNonExist.Put(originId))) }; } } } var retVal = true; if (sendInMsg != null) { this.AddInfoLog("In: {0}", sendInMsg); retVal = base.OnSendInMessage((Message)sendInMsg); } if (sendOutMsgs != null) { foreach (var sendOutMsg in sendOutMsgs) { this.AddInfoLog("Out: {0}", sendOutMsg); RaiseNewOutMessage(sendOutMsg); } } return(retVal); }
public bool SendMail() { try { var subs = new List<SubscriptionInfo>(); var si = new SubscriptionInfo { Email = SendTo, DisplayName = string.Empty, LastName = string.Empty, FirstName = string.Empty }; subs.Add(si); var oEmail = new Email { UseQueue = false, Recipients = subs, Subject = Subject, From = SendFrom, BodyText = BodyText, BodyHTML = Body, }; try { var objThread = new System.Threading.Thread(oEmail.Send); objThread.Start(); return true; } catch (Exception ex) { Services.Exceptions.Exceptions.LogException(ex); return false; } } catch (Exception ex) { Services.Exceptions.Exceptions.LogException(ex); return false; } }
public GetAssignedMessagesOperation(SubscriptionInfo subscriptionInfo, OperationContext context) { _subscriptionInfo = subscriptionInfo; _operationContext = context; }
public Boolean CreateSubscriptionRequest(SubscriptionInfo info) { SMO smo = new SMO(); return smo.RegisterSubscriptionOnPublisher(info.subscriberName,info.subscriptionDbName); return true; }
public void Deserialize(CompactReader reader) { _subscriptionInfo = reader.ReadObject() as SubscriptionInfo; _operationContext = reader.ReadObject() as OperationContext; }
private IEnumerable<SubscriptionInfo> ToDto(HttpEntityManager manager, MonitoringMessage.GetPersistentSubscriptionStatsCompleted message) { if (message == null) yield break; if (message.SubscriptionStats == null) yield break; foreach (var stat in message.SubscriptionStats) { var info = new SubscriptionInfo { Links = new List<RelLink>() { new RelLink(MakeUrl(manager, string.Format("/subscriptions/{0}/{1}", stat.EventStreamId,stat.GroupName)), "detail"), new RelLink(MakeUrl(manager, string.Format("/subscriptions/{0}/{1}/replayParked", stat.EventStreamId,stat.GroupName)), "replayParked") }, EventStreamId = stat.EventStreamId, GroupName = stat.GroupName, Status = stat.Status, AverageItemsPerSecond = stat.AveragePerSecond, TotalItemsProcessed = stat.TotalItems, CountSinceLastMeasurement = stat.CountSinceLastMeasurement, LastKnownEventNumber = stat.LastKnownMessage, LastProcessedEventNumber = stat.LastProcessedEventNumber, ReadBufferCount = stat.ReadBufferCount, LiveBufferCount = stat.LiveBufferCount, RetryBufferCount = stat.RetryBufferCount, TotalInFlightMessages = stat.TotalInFlightMessages, ParkedMessageUri = MakeUrl(manager, string.Format("/streams/$persistentsubscription-{0}::{1}-parked", stat.EventStreamId, stat.GroupName)), Config = new SubscriptionConfigData { CheckPointAfterMilliseconds = stat.CheckPointAfterMilliseconds, BufferSize = stat.BufferSize, LiveBufferSize = stat.LiveBufferSize, MaxCheckPointCount = stat.MaxCheckPointCount, MaxRetryCount = stat.MaxRetryCount, MessageTimeoutMilliseconds = stat.MessageTimeoutMilliseconds, MinCheckPointCount = stat.MinCheckPointCount, NamedConsumerStrategy = stat.NamedConsumerStrategy, PreferRoundRobin = stat.NamedConsumerStrategy == SystemConsumerStrategies.RoundRobin, ReadBatchSize = stat.ReadBatchSize, ResolveLinktos = stat.ResolveLinktos, StartFrom = stat.StartFrom, ExtraStatistics = stat.ExtraStatistics, }, Connections = new List<ConnectionInfo>() }; if (stat.Connections != null) { foreach (var connection in stat.Connections) { info.Connections.Add(new ConnectionInfo { Username = connection.Username, From = connection.From, AverageItemsPerSecond = connection.AverageItemsPerSecond, CountSinceLastMeasurement = connection.CountSinceLastMeasurement, TotalItemsProcessed = connection.TotalItems, AvailableSlots = connection.AvailableSlots, InFlightMessages = connection.InFlightMessages, ExtraStatistics = connection.ObservedMeasurements ?? new Dictionary<string, int>() }); } } yield return info; } }
/// <summary> /// This will be called when Unity IAP has finished initialising. /// </summary> public void OnInitialized(IStoreController controller, IExtensionProvider extensions) { m_Controller = controller; m_AppleExtensions = extensions.GetExtension <IAppleExtensions>(); m_SamsungExtensions = extensions.GetExtension <ISamsungAppsExtensions>(); m_MoolahExtensions = extensions.GetExtension <IMoolahExtension>(); m_MicrosoftExtensions = extensions.GetExtension <IMicrosoftExtensions>(); m_TransactionHistoryExtensions = extensions.GetExtension <ITransactionHistoryExtensions>(); m_GooglePlayStoreExtensions = extensions.GetExtension <IGooglePlayStoreExtensions>(); // Sample code for expose product sku details for google play store // Key is product Id (Sku), value is the skuDetails json string //Dictionary<string, string> google_play_store_product_SKUDetails_json = m_GooglePlayStoreExtensions.GetProductJSONDictionary(); // Sample code for manually finish a transaction (consume a product on GooglePlay store) //m_GooglePlayStoreExtensions.FinishAdditionalTransaction(productId, transactionId); m_GooglePlayStoreExtensions.SetLogLevel(0); // 0 == debug, info, warning, error. 1 == warning, error only. InitUI(controller.products.all); // On Apple platforms we need to handle deferred purchases caused by Apple's Ask to Buy feature. // On non-Apple platforms this will have no effect; OnDeferred will never be called. m_AppleExtensions.RegisterPurchaseDeferredListener(OnDeferred); #if SUBSCRIPTION_MANAGER Dictionary <string, string> introductory_info_dict = m_AppleExtensions.GetIntroductoryPriceDictionary(); #endif // Sample code for expose product sku details for apple store //Dictionary<string, string> product_details = m_AppleExtensions.GetProductDetails(); //Debug.Log("Available items:"); foreach (var item in controller.products.all) { if (item.availableToPurchase) { //Debug.Log(string.Join(" - ", //new[] //{ // item.metadata.localizedTitle, // item.metadata.localizedDescription, // item.metadata.isoCurrencyCode, // item.metadata.localizedPrice.ToString(), // item.metadata.localizedPriceString, // item.transactionID, // item.receipt //})); #if INTERCEPT_PROMOTIONAL_PURCHASES // Set all these products to be visible in the user's App Store according to Apple's Promotional IAP feature // https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/StoreKitGuide/PromotingIn-AppPurchases/PromotingIn-AppPurchases.html m_AppleExtensions.SetStorePromotionVisibility(item, AppleStorePromotionVisibility.Show); #endif #if SUBSCRIPTION_MANAGER // this is the usage of SubscriptionManager class if (item.receipt != null) { if (item.definition.type == ProductType.Subscription) { if (checkIfProductIsAvailableForSubscriptionManager(item.receipt)) { string intro_json = (introductory_info_dict == null || !introductory_info_dict.ContainsKey(item.definition.storeSpecificId)) ? null : introductory_info_dict[item.definition.storeSpecificId]; SubscriptionManager p = new SubscriptionManager(item, intro_json); SubscriptionInfo info = p.getSubscriptionInfo(); //Debug.Log("product id is: " + info.getProductId()); //Debug.Log("purchase date is: " + info.getPurchaseDate()); //Debug.Log("subscription next billing date is: " + info.getExpireDate()); //Debug.Log("is subscribed? " + info.isSubscribed().ToString()); //Debug.Log("is expired? " + info.isExpired().ToString()); //Debug.Log("is cancelled? " + info.isCancelled()); //Debug.Log("product is in free trial peroid? " + info.isFreeTrial()); //Debug.Log("product is auto renewing? " + info.isAutoRenewing()); //Debug.Log("subscription remaining valid time until next billing date is: " + info.getRemainingTime()); //Debug.Log("is this product in introductory price period? " + info.isIntroductoryPricePeriod()); //Debug.Log("the product introductory localized price is: " + info.getIntroductoryPrice()); //Debug.Log("the product introductory price period is: " + info.getIntroductoryPricePeriod()); //Debug.Log("the number of product introductory price period cycles is: " + info.getIntroductoryPricePeriodCycles()); } else { //Debug.Log("This product is not available for SubscriptionManager class, only products that are purchase by 1.19+ SDK can use this class."); } } else { //Debug.Log("the product is not a subscription product"); } } else { //Debug.Log("the product should have a valid receipt"); } #endif } } // Populate the product menu now that we have Products AddProductUIs(m_Controller.products.all); LogProductDefinitions(); }
private void AddSrcComboBox(SubscriptionInfo info) { var checkBox = new CheckBox(); checkBox.Attributes["value"] = info.ContactListId; checkBox.AutoPostBack = true; checkBox.CssClass = "msCheckBox"; checkBox.Checked = info.UserSubscribed; checkBox.Text = info.Name; this.SrcList.Controls.Add(checkBox); if (!String.IsNullOrEmpty(info.Description)) { this.SrcList.Controls.Add(new Literal { Text = "<div class=\"msDescription\">" + info.Description + "</div>" }); } }
public SubscriptionResponse Add(SubscriptionInfo subscription) { var response = _subscriptionRepository.Add(subscription); return(response); }
private void StoreSubscriptionInfo(IRedisClient redis, SubscriptionInfo info) { var id = info.SubscriptionId; using (var trans = redis.CreateTransaction()) { trans.QueueCommand(r => r.AddItemToSortedSet(RedisIndex.ActiveSubscriptionsSet, id, RedisPubSub.CurrentServerTime.Ticks)); trans.QueueCommand(r => r.Set(RedisIndex.Subscription.Fmt(id), info)); trans.QueueCommand(r => r.AddItemToSet(RedisIndex.UserIdSet.Fmt(info.UserId), id)); foreach (var channel in info.Channels) { trans.QueueCommand(r => r.AddItemToSet(RedisIndex.ChannelSet.Fmt(channel), id)); } if (info.UserName != null) trans.QueueCommand(r => r.AddItemToSet(RedisIndex.UserNameSet.Fmt(info.UserName), id)); if (info.SessionId != null) trans.QueueCommand(r => r.AddItemToSet(RedisIndex.SessionSet.Fmt(info.SessionId), id)); trans.Commit(); } }
private Subscription TryGetSubscription(long id, bool remove, DateTimeOffset?time, out SubscriptionInfo info) { info = TryGetInfo(id, remove, time); return(info?.Subscription); }