Example #1
0
        public async Task <bool> SubscribeWithDetails <T>(SubscriptionDetails details, Func <T, Task> callback) where T : SpatialEvent
        {
            var result = await State.Controller.HandleSubscription(this, details);

            if (!result)
            {
                return(false);
            }
            var method = callback.Method;

            if (method.DeclaringType == null || !CodeGenerator.IsValidLanguageIndependentIdentifier(method.Name))
            {
                throw new SubscriptionCallbackNotMethodException();
            }
            var self = GetType();

            if (self.GetMethod(method.Name) == null)
            {
                throw new SubscriptionCallbackNotMemberException();
            }
            _callbacks[EventHelper.GetEventName <T>()] = e => callback((T)e); // TODO: since event name and event type is a strict relation, see if all checks are disabled
            State.CallbackMethodInfos[typeof(T)]       = callback.Method;     // save reflection info to reconstruct callbacks during activation
            await WriteStateAsync();

            return(true);
        }
        public ActionResult Update(string accountId, string subscriptionId, SubscriptionDetails details)
        {
            var accounts = GetAccountsRepository();

            accounts.UpdateSubscription(subscriptionId, details);
            return(new EmptyResult());
        }
        public string AddSubscription(SubscriptionDetails obj, string Token)
        {
            string     data        = JsonConvert.SerializeObject(obj);
            string     drugname    = obj.Drug_name;
            Uri        baseAddress = new Uri("http://20.193.136.3/api");
            HttpClient client      = new HttpClient();

            client.BaseAddress = baseAddress;
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);
            HttpResponseMessage response = client.GetAsync(client.BaseAddress + "/Drugs/GetDrugDetailByName/" + drugname).Result;

            if (response.IsSuccessStatusCode)
            {
                data = response.Content.ReadAsStringAsync().Result;
                Drug drug = JsonConvert.DeserializeObject <Drug>(data);
                if (drug.Quantity > 0)
                {
                    ls.Add(obj);

                    return("Your Subscription Added Successfully!");
                }
                return("Sorry! Subscription Not Possible Due To Unavailable drug.");
            }

            return("Sorry! Subscription Not Possible Due To Unavailable drug.");
        }
Example #4
0
        public ActionResult AddSubscription(SubscriptionDetails obj)
        {
            string     data        = JsonConvert.SerializeObject(obj);
            int        x           = obj.Drug_ID;
            Uri        baseAddress = new Uri("https://localhost:44372/api");
            HttpClient client      = new HttpClient();

            client.BaseAddress = baseAddress;

            HttpResponseMessage response = client.GetAsync(client.BaseAddress + "/Drugs/" + x).Result;

            if (response.IsSuccessStatusCode)
            {
                data = response.Content.ReadAsStringAsync().Result;
                Drug drug = JsonConvert.DeserializeObject <Drug>(data);
                if (drug.Quantity > 0)
                {
                    ls.Add(obj);

                    return(Ok("Added"));
                }
                return(BadRequest("Unavailable"));
            }

            return(BadRequest());
        }
        public void CreateSubscriptionDetail()
        {
            logic    = new SubscriptionTypeLogic();
            proLogic = new ProductLogic();
            var proList = proLogic.GetProducts();
            var sub     = logic.GetSubscriptionType();

            if (proList.Count > 0 && sub.Count > 0)
            {
                var proId = proList.FirstOrDefault(p => p.ProductCode.ToUpper() == "PRO-01").Id;
                var subscriptioinTypeId    = sub.FirstOrDefault(s => s.Name == "Sub1").Id;
                SubscriptionDetails detail = new SubscriptionDetails();
                detail.ProductId          = proId;
                detail.SubscriptionTypeId = subscriptioinTypeId;
                detail.Quantity           = 4;
                List <SubscriptionDetails> details = new List <SubscriptionDetails>();
                details.Add(detail);
                var status = detailLogic.CreateSubscriptionDetails(details);
                Assert.IsTrue(status);
            }
            else
            {
                Assert.Fail("No Subscription and Product Details created");
            }
        }
        public dynamic RemoveSubscription(SubscriptionDetails obj, string Token)
        {
            string data = JsonConvert.SerializeObject(obj);

            Uri        baseAddress = new Uri("https://refillservice856709.azurewebsites.net/api");
            HttpClient client      = new HttpClient();

            client.BaseAddress = baseAddress;
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Token);

            HttpResponseMessage response = client.GetAsync(client.BaseAddress + "/Refill/RefillStatus/" + obj.Sub_id).Result;

            if (response.IsSuccessStatusCode)
            {
                data = response.Content.ReadAsStringAsync().Result;
                Refill refill = JsonConvert.DeserializeObject <Refill>(data);
                if (refill.Status == "clear")
                {
                    ls.Remove(obj);
                    return("Unsubscription Done. Thank You!");
                }
                return("Sorry!Clear The Dues Before Unsubscription");
            }
            return(null);
        }
Example #7
0
        public ActionResult AddSubscription(string id, SubscriptionDetails details)
        {
            var repo = AccountsRepositoryFactory.GetAccountsRepository();

            repo.CreateSubscription(id, details);
            return(RedirectToAction("Index"));
        }
        // Get information about the changed messages and send to the browser via SignalR.
        // A production application would typically queue a background job for reliability.
        public async Task GetChangedMessagesAsync(IEnumerable <Notification> notifications)
        {
            List <MessageViewModel> messages = new List <MessageViewModel>();

            foreach (var notification in notifications)
            {
                SubscriptionDetails subscription = SubscriptionCache.GetSubscriptionCache().GetSubscriptionInfo(notification.SubscriptionId);

                var graphClient = GraphHelper.GetAuthenticatedClient(subscription.UserId, subscription.RedirectUrl);

                // Get the message
                var message = await graphClient.Me.Messages[notification.ResourceData.Id].Request()
                              .Select("id,subject,bodyPreview,createdDateTime,isRead,conversationId,changeKey")
                              .GetAsync();

                // Clear the additional data from Graph (purely for display purposes)
                message.AdditionalData.Clear();

                MessageViewModel messageViewModel = new MessageViewModel(message, subscription.UserId);
                messages.Add(messageViewModel);
            }
            if (messages.Count > 0)
            {
                NotificationService notificationService = new NotificationService();
                notificationService.SendNotificationToClient(messages);
            }
        }
Example #9
0
        public async Task <bool> HandleSubscription <T>(T subscriber, SubscriptionDetails details) where T : ISpatialGrain
        {
            var eventName = details.EventTypeFilter.GetTypename();
            var filter    = new SubscriptionFilter
            {
                Area             = details.Area,
                OriginTypeFilter = details.OriginTypeFilter
            };
            // Setup interest management
            var result = State.InterestManager.AddInterest(subscriber, eventName, filter);

            // If the subscription could not be added, return false
            if (!result)
            {
                return(false);
            }
            // Make sure events are forwarded
            var queue = State.InterestManager.GetForwardCommandsForSubscription(subscriber, eventName, filter);

            if (queue.Count > 0)
            {
                await ProcessForwardCommandQueue(queue);
            }
            await WriteStateAsync();

            return(true);
        }
        public ActionResult Create(string accountId, SubscriptionDetails details)
        {
            var accounts        = GetAccountsRepository();
            var newSubscription = accounts.CreateSubscription(accountId, details);

            return(new JsonResult {
                Data = newSubscription
            });
        }
        void TestSubscriptionAgency()
        {
            var client = new SubscriptionAgencyExternalECClient("ST01");
            var subscr = new SubscriptionDetails();

            subscr.SystemUserCode   = "SKDEN";
            subscr.Subscriptionlist = new SubscriptionList();
            subscr.Subscriptionlist.Add(new Subscription());
            var x = client.SubmitSubscriptionEC(SOA1User, SOA2Pass, "1", subscr);
        }
Example #12
0
        public void UpdateSubscription([FromBody] SubscriptionDetails subData)
        {
            NamespaceManager namespaceManager = CreateNamespaceManager();

            SubscriptionDescription description = namespaceManager.GetSubscription(subData.topicName, subData.name);

            subData.ApplyChangesToDescription(description);

            namespaceManager.UpdateSubscription(description);
        }
Example #13
0
        public SubscriptionDetails PostUnSubscription(int Member_Id, int Subscription_Id, string auth)
        {
            // Get the data from refill microservice
            _log4net.Info("Checking for Subscriptionid= " + Subscription_Id);

            SubscriptionDetails result = new SubscriptionDetails();
            var subs = details.Find(p => p.Id == Subscription_Id);

            if (subs != null)
            {
                _log4net.Info("Interacting with refill microservice for the payment status for subscription id =" + Subscription_Id);

                try
                {
                    using (var httpClient = new HttpClient())
                    {
                        string[] token = auth.Split(" ");

                        var request = new HttpRequestMessage(HttpMethod.Get, "http://20.62.225.11/api/RefillOrders/RefillDues/" + Subscription_Id);
                        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token[1]);

                        using (var response = httpClient.SendAsync(request).Result)
                        {
                            if (!response.IsSuccessStatusCode)
                            {
                                return(result);
                            }

                            var data = response.Content.ReadAsStringAsync().Result;

                            var due = JsonConvert.DeserializeObject <int>(data);

                            result = subs;

                            _log4net.Info("Number of Refills pending for payment" + due + "for subscriptionId" + Subscription_Id);


                            if (due == 0 || due == -1)
                            {
                                var unsubscribe = details.Find(p => p.Id == Subscription_Id);
                                result.Status = false;
                                details.Remove(unsubscribe);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    _log4net.Error(ex.Message);
                    return(null);
                }
                return(result);
            }
            return(null);
        }
        public ActionResult RemoveSubscription(SubscriptionDetails obj)
        {
            string Token = HttpContext.Request.Headers["Authorization"].Single().Split(" ")[1];
            SubscriptionRepository sub = new SubscriptionRepository();
            string status = sub.RemoveSubscription(obj, Token);

            if (status == null)
            {
                return(BadRequest());
            }
            return(Ok(status));
        }
Example #15
0
        public ApplicationModel(IServiceBus bus)
        {
            this.bus = bus;

            Search              = new Search(bus);
            MyQueue             = new QueueManager(bus);
            SubscriptionDetails = new SubscriptionDetails(bus);
            Recommendations     = new Recommendations();

            PotentialBooks = Recommendations;

            MyBooks = new BindableCollection <BookModel>();
        }
Example #16
0
        public ApplicationModel(IServiceBus bus)
        {
            this.bus = bus;

            Search = new Search(bus);
            MyQueue = new QueueManager(bus);
            SubscriptionDetails = new SubscriptionDetails(bus);
            Recommendations = new Recommendations();

            PotentialBooks = Recommendations;

            MyBooks = new BindableCollection<BookModel>();
        }
Example #17
0
        SubscriptionDetails ISubscriptionService.GetCustomerSubscription(string customerBillingId)
        {
            SubscriptionDetails subscription = null;

            try
            {
                var            customerService = new StripeCustomerService();
                StripeCustomer stripeCustomer  = customerService.Get(customerBillingId);
                Coupon         coupon          = null;
                Discount       discount        = null;
                if (stripeCustomer.StripeDiscount != null && stripeCustomer.StripeDiscount.StripeCoupon != null)
                {
                    coupon = new Coupon
                    {
                        AmountOff        = stripeCustomer.StripeDiscount.StripeCoupon.AmountOff,
                        Duration         = stripeCustomer.StripeDiscount.StripeCoupon.Duration,
                        DurationInMonths = stripeCustomer.StripeDiscount.StripeCoupon.DurationInMonths,
                        Id         = stripeCustomer.StripeDiscount.StripeCoupon.Id,
                        PercentOff = stripeCustomer.StripeDiscount.StripeCoupon.PercentOff,
                        RedeemBy   = stripeCustomer.StripeDiscount.StripeCoupon.RedeemBy
                    };
                    discount = new Discount
                    {
                        Coupon = coupon,
                        End    = stripeCustomer.StripeDiscount.End,
                        Id     = stripeCustomer.StripeDiscount.Id,
                        Start  = stripeCustomer.StripeDiscount.Start
                    };
                }

                subscription = new SubscriptionDetails
                {
                    Created     = stripeCustomer.Created,
                    Deleted     = stripeCustomer.Deleted,
                    CanceledAt  = stripeCustomer.StripeSubscription != null? stripeCustomer.StripeSubscription.CanceledAt : null,
                    CustomerId  = stripeCustomer.StripeSubscription != null?stripeCustomer.StripeSubscription.CustomerId: null,
                    EndedAt     = stripeCustomer.StripeSubscription != null?stripeCustomer.StripeSubscription.EndedAt: null,
                    PeriodEnd   = stripeCustomer.StripeSubscription != null?stripeCustomer.StripeSubscription.PeriodEnd: null,
                    PeriodStart = stripeCustomer.StripeSubscription != null?stripeCustomer.StripeSubscription.PeriodStart: null,
                    Start       = stripeCustomer.StripeSubscription != null?stripeCustomer.StripeSubscription.Start: null,
                    TrialEnd    = stripeCustomer.StripeSubscription != null?stripeCustomer.StripeSubscription.TrialEnd: null,
                    TrialStart  = stripeCustomer.StripeSubscription != null?stripeCustomer.StripeSubscription.TrialStart: null,
                    Status      = stripeCustomer.StripeSubscription != null? stripeCustomer.StripeSubscription.Status: null,
                    Plan        = stripeCustomer.StripeSubscription != null ? stripeCustomer.StripeSubscription.StripePlan.Name : null,
                    Discount    = discount
                };
            }
            catch { }

            return(subscription);
        }
Example #18
0
        public SubscriptionDetails PostSubscription(PrescriptionDetails prescription, string PolicyDetails, int Member_Id, string auth)
        {
            _log4net.Info("DruApi is being called to check for the availability of the DrugName= " + prescription.DrugName);

            List <LocationWiseDrug> location = new List <LocationWiseDrug>();
            var drugs = "";
            var query = prescription.DrugName;

            string[] token = auth.Split(" ");

            HttpClient          client = new HttpClient();
            HttpResponseMessage result = null;

            try
            {
                var request = new HttpRequestMessage(HttpMethod.Get, "http://20.62.208.42/api/DrugsApi/searchDrugsByName/" + query);
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token[1]);

                result = client.SendAsync(request).Result;

                if (!result.IsSuccessStatusCode)
                {
                    return(null);
                }
            }
            catch (Exception ex)
            {
                _log4net.Error("Exception occured in calling Drug Api" + nameof(SubscribeDrugs) + " and error is" + ex.Message);

                return(null);
            }
            drugs    = result.Content.ReadAsStringAsync().Result;
            location = JsonConvert.DeserializeObject <List <LocationWiseDrug> >(drugs);
            if (location.Count != 0)
            {
                _log4net.Info(prescription.DrugName + " Drug Available");
                var last = details.Last();
                SubscriptionDetails subscription = new SubscriptionDetails {
                    Id = (details[details.Count - 1].Id + 1), MemberId = Member_Id, MemberLocation = "Delhi", PrescriptionId = 3, RefillOccurrence = prescription.RefillOccurrence, Status = true, SubscriptionDate = DateTime.Now
                };
                details.Add(subscription);
                return(subscription);
            }
            else
            {
                _log4net.Info(prescription.DrugName + " Drug NotAvailable");
                return(new SubscriptionDetails {
                    Id = 0, MemberId = 0, MemberLocation = "", PrescriptionId = 0, RefillOccurrence = "", Status = false, SubscriptionDate = Convert.ToDateTime("2020-12-01 01:01:00 AM")
                });
            }
        }
        public IActionResult PostUnsubscribe([FromRoute] int MemberId, int SubscriptionId, [FromHeader(Name = "Authorization")] string auth)
        {
            SubscriptionDetails data = new SubscriptionDetails();

            _log4net.Info("UnSubscribe Request is raised from client side for subscriptionid = " + SubscriptionId);

            if (MemberId <= 0 || SubscriptionId <= 0 || auth == null)
            {
                _log4net.Info("MemberId is" + MemberId + "SubscriptionId is " + SubscriptionId + " less or equal to  zero");
                return(BadRequest());
            }
            data = Provider.UnSubscribe(MemberId, SubscriptionId, auth);

            return(Ok(data));
        }
        public IActionResult PostSubscribe([FromBody] PrescriptionDetails details, [FromRoute] string PolicyDetails, int MemberId, [FromHeader(Name = "Authorization")] string auth)
        {
            SubscriptionDetails data = new SubscriptionDetails();

            if (details == null || PolicyDetails == null || MemberId <= 0 || auth == null)
            {
                _log4net.Info("PrescriptionDetails is null or " + "MemberId is= " + MemberId + " PolicyDetails is= " + PolicyDetails + " less or equal to  zero");
                return(BadRequest());
            }
            _log4net.Info("Subscription Request is raised from client side  for Drug= " + details.DrugName);

            data = Provider.Subscribe(details, PolicyDetails, MemberId, auth);

            return(Ok(data));
        }
Example #21
0
        /// <summary>
        /// Updates the configuration of a subscription
        /// </summary>
        /// <param name="subscriptionId">The ID of the subscription to be updated</param>
        /// <param name="subscriptionDetails">The new details of the subscription</param>
        public void UpdateSubscription(string subscriptionId, SubscriptionDetails subscriptionDetails)
        {
            var context      = GetAccountsContext();
            var subscription = context.Subscriptions.FirstOrDefault(s => s.Id.Equals(subscriptionId));

            if (subscription != null)
            {
                subscription.IsActive        = subscriptionDetails.IsActive;
                subscription.IsTrial         = subscriptionDetails.IsTrial;
                subscription.Label           = subscriptionDetails.Label;
                subscription.StoreCountLimit = subscriptionDetails.StoreLimit;
                subscription.StoreSizeLimit  = subscriptionDetails.StoreSizeLimit;
                subscription.TotalSizeLimit  = subscriptionDetails.TotalSizeLimit;
                context.SaveChanges();
            }
        }
        /// <summary>
        /// Registers a Service or Actor <paramref name="reference"/> as subscriber for messages of type <paramref name="messageTypeName"/>
        /// </summary>
        /// <param name="reference">Reference to the Service or Actor to register.</param>
        /// <param name="messageTypeName">Full type name of message object.</param>
        /// <param name="isOrdered"></param>
        /// <returns></returns>
        public async Task SubscribeAsync(ReferenceWrapper reference, string messageTypeName, bool isOrdered = true)
        {
            await WaitForInitializeAsync(CancellationToken.None);

            var brokerState = await TimeoutRetryHelper.Execute((token, state) => StateManager.GetOrAddAsync <IReliableDictionary <string, BrokerServiceState> >(messageTypeName));

            await TimeoutRetryHelper.ExecuteInTransaction(StateManager, async (tx, token, state) =>
            {
                var subscriptionDetails = new SubscriptionDetails(reference, messageTypeName, isOrdered);
                var subscription        = await _subscriptionFactory.CreateAsync(tx, subscriptionDetails);
                await brokerState.AddOrUpdateSubscription(tx, Subscribers, subscriptionDetails);

                _subscriptions.AddOrUpdate(subscriptionDetails.QueueName, subscription, (key, old) => subscription);
                ServiceEventSourceMessage($"Registered subscriber: {reference.Name}");
                await _brokerEventsManager.OnSubscribedAsync(subscriptionDetails.QueueName, reference, messageTypeName);
            }, cancellationToken : CancellationToken.None);
        }
Example #23
0
        public ActionResult Add_Subscription(SubscriptionDetails obj)
        {
            if (HttpContext == null)
            {
                Token = "Token";
            }
            else
            {
                Token = HttpContext.Request.Headers["Authorization"].Single().Split(" ")[1];
            }

            //SubscriptionRepository sub = new SubscriptionRepository();
            string status = _sub.AddSubscription(obj, Token);

            if (status == null)
            {
                return(BadRequest());
            }
            return(Ok(status));
        }
        /// <summary>
        /// Unregisters a Service or Actor <paramref name="reference"/> as subscriber for messages of type <paramref name="messageTypeName"/>
        /// </summary>
        /// <param name="reference"></param>
        /// <param name="messageTypeName"></param>
        /// <returns></returns>
        public async Task UnsubscribeAsync(ReferenceWrapper reference, string messageTypeName)
        {
            await WaitForInitializeAsync(CancellationToken.None);

            var brokerState = await TimeoutRetryHelper.Execute((token, state) => StateManager.GetOrAddAsync <IReliableDictionary <string, BrokerServiceState> >(messageTypeName));

            await TimeoutRetryHelper.ExecuteInTransaction(StateManager, async (tx, token, state) =>
            {
                var queueName = SubscriptionDetails.CreateQueueName(reference, messageTypeName);
                if (_subscriptions.TryGetValue(queueName, out var subscription))
                {
                    await brokerState.RemoveSubscription(tx, Subscribers, subscription.SubscriptionDetails);
                }

                await StateManager.RemoveAsync(tx, queueName);

                ServiceEventSourceMessage($"Unregistered subscriber: {reference.Name}");
                _subscriptions.TryRemove(queueName, out _);
                await _brokerEventsManager.OnUnsubscribedAsync(queueName, reference, messageTypeName);
            });
        }
        public SubscriptionDetails SubscriptionInfo(string id)
        {
            var userId        = _http.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "00000000-0000-0000-0000-000000000000";
            var authenticated = _http.HttpContext.User.Identity.IsAuthenticated;


            if (id != userId || !authenticated)
            {
                return(null);
            }

            var user = _db.Users.Find(userId);

            if (user == null)
            {
                return(null);
            }

            var methods = _db.PaymentMethods.Where(x => x.Country == user.Country).ToList();
            List <PaymentMethod> list = new List <PaymentMethod>();

            foreach (var method in methods)
            {
                list.Add(new PaymentMethod {
                    Name = method.Name, PhoneNumber = method.PhoneNumber
                });
            }

            SubscriptionDetails model = new SubscriptionDetails
            {
                Methods     = list,
                Amount      = methods[0].Amount,
                From        = user.SubscriptionStart.ToString("dd/MM/yyyy"),
                To          = user.SubscriptionEnd.ToString("dd/MM/yyyy"),
                PaymentCode = user.MoneyCode,
                UserId      = user.Id,
            };

            return(model);
        }
        public SubscriptionDetails PostUnSubscribe(int Member_Id, int Subscription_Id)
        {
            // Get the data from refill microservice
            _log4net.Info("Checking for Subscription ");


            var subs = details.Find(p => p.Id == Subscription_Id);

            if (subs != null)
            {
                _log4net.Info("interacting with refill microservice for the payment status of the partiular subscription id ");
                SubscriptionDetails result = new SubscriptionDetails();


                using (var httpClient = new HttpClient())
                {
                    using (var response = httpClient.GetAsync("https://localhost:44329/api/RefillOrders/RefillDues/" + SubscriptionId).Result)
                    {
                        if (!response.IsSuccessStatusCode)
                        {
                            return(result);
                        }

                        var data = response.Content.ReadAsStringAsync().Result;

                        var due = JsonConvert.DeserializeObject <int>(data);

                        result = subs;

                        if (due == 0)
                        {
                            result.Status = false;
                        }

                        return(result);
                    }
                }
            }
        }
Example #27
0
        /// <summary>
        /// Creates a new subscription for an account
        /// </summary>
        /// <param name="accountId">The ID of the account</param>
        /// <param name="subscriptionDetails">The configuration for the new subscription</param>
        /// <returns>The ID of the new subscription</returns>
        public SubscriptionDetails CreateSubscription(string accountId, SubscriptionDetails subscriptionDetails)
        {
            var context = GetAccountsContext();
            var account = context.Accounts.FirstOrDefault(a => a.Id.Equals(accountId));

            if (account == null)
            {
                return(null);
            }

            if (subscriptionDetails.IsTrial)
            {
                var existingTrial =
                    context.Subscriptions.FirstOrDefault(s => s.Account.Equals(account) && s.IsTrial);
                if (existingTrial != null)
                {
                    throw new AccountsRepositoryException(AccountsRepositoryException.AccountHasTrialSubscription, "Account already has a trial subscription.");
                }
                subscriptionDetails = SubscriptionDetails.TrialDetails;
            }

            var subscription = context.Subscriptions.Create();

            subscription.Account         = account;
            subscription.Created         = DateTime.UtcNow;
            subscription.IsActive        = true;
            subscription.IsTrial         = subscriptionDetails.IsTrial;
            subscription.Label           = subscriptionDetails.Label;
            subscription.StoreCountLimit = subscriptionDetails.StoreLimit;
            subscription.StoreSizeLimit  = subscriptionDetails.StoreSizeLimit;
            subscription.TotalSizeLimit  = subscriptionDetails.TotalSizeLimit;
            context.SaveChanges();
            _cache.DropAccountDetails(accountId);
            foreach (var userToken in account.UserTokens.Select(ut => ut.Id))
            {
                _cache.DropAccountDetails(userToken);
            }
            return(new SubscriptionDetails(subscription));
        }
Example #28
0
        public ActionResult RemoveSubscription(SubscriptionDetails obj)
        {
            string     data        = JsonConvert.SerializeObject(obj);
            int        x           = obj.Sub_id;
            Uri        baseAddress = new Uri("https://localhost:44322/api");
            HttpClient client      = new HttpClient();

            client.BaseAddress = baseAddress;

            HttpResponseMessage response = client.GetAsync(client.BaseAddress + "/Refill/" + x).Result;

            if (response.IsSuccessStatusCode)
            {
                data = response.Content.ReadAsStringAsync().Result;
                Refill refill = JsonConvert.DeserializeObject <Refill>(data);
                if (refill.Status == "clear")
                {
                    ls.Remove(obj);
                    return(Ok("done"));
                }
                return(BadRequest("Clear the Dues"));
            }
            return(BadRequest());
        }
Example #29
0
        public IActionResult Subscribe([Bind("InsurancePolicyNumber,InsuranceProvider,PrescriptionDate,DrugName,DoctorName,RefillOccurrence")] PrescriptionDetails prescription)
        {
            if (String.IsNullOrEmpty(HttpContext.Session.GetString("Token")))
            {
                _log4net.Warn("Anonymous user trying to Subscribe");
                return(RedirectToAction("Index", "Home"));
            }

            // Get MemberId from Session

            SubscriptionDetails result = new SubscriptionDetails();
            int    id     = (int)HttpContext.Session.GetInt32("MemberId");
            string policy = "sad";

            // Call Subscription Service -- Subscribe method with prescription details and policy details and Member Id



            using (var httpClient = new HttpClient())
            {
                var content = new StringContent(JsonConvert.SerializeObject(prescription), Encoding.UTF8, "application/json");

                string url = "" + configuration["ServiceUrls:Subscription"] + "PostSubscribe";

                var request = new HttpRequestMessage(HttpMethod.Post, url + "/" + policy + "/" + id)
                {
                    Content = content
                };

                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", HttpContext.Session.GetString("Token"));

                using (var response = httpClient.SendAsync(request).Result)
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        _log4net.Error("False Response");
                        string message = "Something Went Wrong " + response.StatusCode;
                        return(RedirectToAction("Subscribe", new { message }));
                    }

                    var data = response.Content.ReadAsStringAsync().Result;

                    result = JsonConvert.DeserializeObject <SubscriptionDetails>(data);

                    if (result == null)
                    {
                        _log4net.Error("Exception On Subscription Service side");
                        string message = "Something Went Wrong " + response.StatusCode;
                        return(RedirectToAction("Subscribe", new { message }));
                    }

                    if (!result.Status)
                    {
                        _log4net.Info(prescription.DrugName + " Drug Not Available.... Subscription Failed ");
                        string message = "Subscription failed due to InAvailability of Drugs ";
                        return(RedirectToAction("Subscribe", new { message }));
                    }

                    details.Add(result);

                    var db = context.Subscriptions.FirstOrDefault(x => x.Id == result.Id);
                    if (db == null)
                    {
                        context.Subscriptions.Add(result);
                        context.SaveChanges();
                    }

                    string status1  = "Success";
                    string message1 = " Subscription Successfull..... Subscription Id is " + result.Id;
                    return(RedirectToAction("Index", new { status = status1, message = message1 }));
                }
            }
        }
Example #30
0
        public IActionResult UnSubscribe(int id)
        {
            if (String.IsNullOrEmpty(HttpContext.Session.GetString("Token")))
            {
                _log4net.Warn("Anonymous access to Unsubscribe");
                return(RedirectToAction("Index", "Home"));
            }

            SubscriptionDetails result = new SubscriptionDetails();
            int MemberId = (int)HttpContext.Session.GetInt32("MemberId");

            // call subscription microservice

            using (var httpClient = new HttpClient())
            {
                var content = new StringContent(JsonConvert.SerializeObject("hello"), Encoding.UTF8, "application/json");

                string url = "" + configuration["ServiceUrls:Subscription"] + "PostUnSubscribe";

                var request = new HttpRequestMessage(HttpMethod.Post, url + "/" + MemberId + "/" + id)
                {
                    Content = content
                };

                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", HttpContext.Session.GetString("Token"));

                using (var response = httpClient.SendAsync(request).Result)
                {
                    if (!response.IsSuccessStatusCode)
                    {
                        string status  = "Error";
                        string message = "Something Went Wrong " + response.StatusCode;
                        return(RedirectToAction("Index", new { status, message }));
                    }

                    var data = response.Content.ReadAsStringAsync().Result;

                    result = JsonConvert.DeserializeObject <SubscriptionDetails>(data);

                    if (result == null)
                    {
                        string status  = "Error";
                        string message = "Subscription Not Found";
                        return(RedirectToAction("Index", new { status, message }));
                    }

                    if (result.Status)
                    {
                        string status  = "Error";
                        string message = "UnSubscription failed due to pending refill dues ";
                        return(RedirectToAction("Index", new { status, message }));
                    }

                    var ob = details.Find(x => x.Id == id);
                    details.Remove(ob);

                    var db = context.Subscriptions.FirstOrDefault(x => x.Id == result.Id);

                    if (db != null)
                    {
                        context.Remove(db);
                        context.SaveChanges();
                    }

                    string status1  = "Success";
                    string message1 = " Successfully Unsubscribed for Id " + id;
                    return(RedirectToAction("Index", new { status = status1, message = message1 }));
                }
            }
        }
 public AccountAndSubscription(AccountDetails account, SubscriptionDetails subscription, string apiEndpoint)
 {
     Account      = account;
     Subscription = subscription;
     ApiEndpoint  = apiEndpoint;
 }