Пример #1
0
        public void Initialize(TimeSpan updateCycle)
        {
            BeginLogging();
            _updateCycle = updateCycle;

            _dbLog.InfoFormat("Initializing application node to update every {0}", updateCycle);
        }
        public virtual void DemoteAccount(string toRole, ApplicationUser user = null)
        {
            Debug.Assert(!string.IsNullOrEmpty(toRole));

            if (null == user)
            {
                IUserContext _uc = Catalog.Factory.Resolve <IUserContext>();
                user = _uc.GetCurrentUser();
            }

            var billingExt =
                (ApplicationUserSubscription)user.Extensions.GetOrAdd(ApplicationUserSubscription.Extension,
                                                                      _ => new ApplicationUserSubscription());

            billingExt.BillingPlan     = null;
            billingExt.SubscriptionEnd = DateTime.UtcNow;
            billingExt.BillingStatus   = BillingStatus.NotEnrolled;

            user.AccountRoles = new List <string>(new[] { toRole });

            _dblog.InfoFormat("User {0} demoted to role {1}", user.PrincipalId, toRole);

            using (var ds = DocumentStoreLocator.ResolveOrRoot(CommonConfiguration.CoreDatabaseRoute))
            {
                ds.Store(user);
                ds.SaveChanges();
            }
        }
Пример #3
0
 private void CreateThreadsForAllWorkers()
 {
     _dbg.InfoFormat("Creating tasks for {0} workers", _workers.EmptyIfNull().Count());
     foreach (var worker in _workers.EmptyIfNull())
     {
         _dbg.InfoFormat("Task for worker of type {1}", worker.GetType().FullName);
         worker.Initialize(_cts.Token);
         _tasks.Add(new Task(worker.ProtectedRun, _cts.Token, TaskCreationOptions.LongRunning));
     }
 }
Пример #4
0
        public T Get(string objId)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(objId));

            CloudBlob blob = _container.GetBlobReference(String.Concat(objId, ".json"));

            try
            {
                var json = blob.DownloadText();
                _dblog.InfoFormat("Retrieved {0}: {1}", objId, json);
                return(JsonConvert.DeserializeObject <T>(json));
            }
            catch (StorageClientException)
            {
                return(default(T));
            }
        }
        public byte[] RetrieveKey(string key, bool fromCache = true)
        {
            byte[] retval = null;

            bool found = false;

            if (fromCache)
            {
                _dblog.InfoFormat("Found image {0} in cache", key);
                lock (_cache)
                {
                    found = _cache.MaybeGetItem(key, out retval);
                }
            }

            if (!found)
            {
                _log.InfoFormat("Retrieving image {0} from blob storage into cache", key);
                return(RetrieveFromBlobStorage(key));
            }

            return(retval);
        }
Пример #6
0
        /// <summary>
        ///   PluginTemplate wants to fire a trigger.
        /// </summary>
        /// <param name="agentId"> </param>
        /// <param name="machine"> </param>
        /// <param name="trigger"> </param>
        /// <param name="msg"> </param>
        public void FireOnHostedWorkflow(string agentId, string machine, string trigger)
        {
            _dblog.InfoFormat("PluginTemplate host firing on instance {0}: machine {1}: {2}.", agentId, machine, trigger);


            var fire = new WorkflowTrigger
            {
                TriggerName    = trigger,
                InstanceTarget = agentId,
                MachineContext = machine,
                Route          = TriggerRoutes.FireRoute,
                Id             = Guid.NewGuid().ToString()
            };

            InternalFireOnHostedWorkflow(agentId, fire);
        }
        public Guid BeginUpload(string fileName, Guid owner)
        {
            _dblog.InfoFormat("Begin uploading file {0} for owner {1}", fileName, owner);

            Guid id = Guid.NewGuid();

            var blobs  = Client.FromConfig().ForBlobs();
            var buffer = blobs.GetContainerReference(UploadBufferContainer);

            buffer.CreateIfNotExist();

            string metaDataUri  = string.Format("{0}/metadata.txt", id);
            var    metadataInfo = buffer.GetBlobReference(metaDataUri);

            StringBuilder manifestContent = new StringBuilder();

            manifestContent.AppendLine(fileName);
            manifestContent.AppendLine(owner.ToString());
            manifestContent.AppendLine(DateTime.UtcNow.ToString(CultureInfo.InvariantCulture));

            metadataInfo.UploadText(manifestContent.ToString());

            return(id);
        }
Пример #8
0
        public byte[] DownloadData(string file, int startRange, int length)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(file));
            Debug.Assert(startRange >= 0);
            Debug.Assert(length < _memoryHog);

            Stream data;

            if (!_cache.MaybeGetItem(file, out data))
            {
                _log.InfoFormat("Downloading {0} from blob storage and caching", file);

                var blobs = Client.FromConfig().ForBlobs();
                var c     = blobs.GetContainerReference(_container);
                var b     = c.GetBlobReference(file);
                using (MemoryStream ms = new MemoryStream())
                {
                    b.DownloadToStream(ms);
                    _cache.Add(file, ms);
                    data = ms;
                }
            }
            else
            {
                _dblog.InfoFormat("Cache hit for file download {0}", file);
            }

            if (startRange >= data.Length)
            {
                return(null);
            }

            byte[] retval = new byte[length];
            data.Seek(startRange, SeekOrigin.Begin);
            int read = data.Read(retval, 0, length);

            if (read < length)
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    ms.Write(retval, 0, read);
                    retval = ms.ToArray();
                }
            }

            return(retval);
        }
        private void ExpireDups()
        {
            var keys = _duplicateTracking.Keys;

            foreach (var key in keys)
            {
                DateTime dupTime;
                if (_duplicateTracking.TryGetValue(key, out dupTime))
                {
                    var elapsed = DateTime.UtcNow - dupTime;
                    if (elapsed.TotalSeconds > ExpireSeconds)
                    {
                        _dbLog.InfoFormat("app alert for {0} from {1} expired", key, dupTime);
                        _duplicateTracking.TryRemove(key, out dupTime);
                    }
                }
            }
        }
Пример #10
0
        public bool Open()
        {
            if (_leaseId != null)
            {
                return(true);
            }


            _leaseId = _leaseBlob.TryAcquireLease();
            if (null != _leaseId)
            {
                StopRenewal();
                _leaseBlob.SetExpiration(_expireUnused);

                var ct = _cts.Token;
                _renewLease = new Task(
                    c =>
                {
                    var cancel = (CancellationToken)c;
                    while (!cancel.IsCancellationRequested)
                    {
                        if (!cancel.WaitHandle.WaitOne(TimeSpan.FromSeconds(40)))
                        {
                            _leaseBlob.RenewLease(_leaseId);
                            _leaseBlob.SetExpiration(_expireUnused);

                            _dblog.InfoFormat("Renewed lock lease for {0}", _name);
                        }
                    }
                },
                    ct,
                    ct,
                    TaskCreationOptions.LongRunning);
                _renewLease.Start();

                _log.InfoFormat("Acquired lock on {0}", _name);

                return(true);
            }

            return(false);
        }
Пример #11
0
        /// <summary>
        ///   groom out blobs that are too old
        /// </summary>
        /// <param name="containerName"> </param>
        /// <param name="old"> </param>
        /// <param name="ct"> </param>
        /// <param name="removeEmptyContainer"> </param>
        public static void GroomOldBlobsFrom(string containerName, TimeSpan old, CancellationToken?ct = null,
                                             bool removeEmptyContainer = false)
        {
            ILog            log   = ClassLogger.Create(typeof(AzureStorageAssistant));
            DebugOnlyLogger dblog = DebugOnlyLogger.Create(log);

            try
            {
                log.InfoFormat("Grooming blobs from {0} older than {1}", containerName, old.ToString());

                var account =
                    CloudStorageAccount.FromConfigurationSetting(CommonConfiguration.DefaultStorageConnection.ToString());
                account.Ensure(containers: new[] { containerName });

                var bc        = account.CreateCloudBlobClient();
                var container = bc.GetContainerReference(containerName);


                BlobRequestOptions blobQuery = new BlobRequestOptions();
                blobQuery.BlobListingDetails = BlobListingDetails.None;
                blobQuery.UseFlatBlobListing = true;

                blobQuery.AccessCondition = AccessCondition.IfNotModifiedSince(DateTime.UtcNow.AddDays(-1 * old.Days));

                if (ct.HasValue)
                {
                    ct.Value.ThrowIfCancellationRequested();
                }


                IEnumerable <IListBlobItem> blobs;
                blobs = container.ListBlobs(blobQuery).ToArray();


                foreach (IListBlobItem blob in blobs)
                {
                    if (ct.HasValue)
                    {
                        ct.Value.ThrowIfCancellationRequested();
                    }

                    CloudBlob cloudBlob;

                    cloudBlob = container.GetBlobReference(blob.Uri.ToString());

                    dblog.InfoFormat("Grooming blob {0}", cloudBlob.Uri);
                    cloudBlob.DeleteIfExists(blobQuery);
                }

                if (removeEmptyContainer)
                {
                    if (!container.ListBlobs().Any())
                    {
                        container.Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                log.Warn(ex.Message);
                log.Warn(ex.ToString());
                throw;
            }
        }
Пример #12
0
        /// <summary>
        ///   groom using the expired metadata attribute
        /// </summary>
        /// <param name="containerName"> </param>
        /// <param name="ct"> </param>
        /// <param name="removeEmptyContainer"> </param>
        public static void CleanExpiredBlobsFrom(string containerName, CancellationToken?ct = null,
                                                 bool removeEmptyContainer = false)
        {
            ILog            log   = ClassLogger.Create(typeof(AzureStorageAssistant));
            DebugOnlyLogger dblog = DebugOnlyLogger.Create(log);

            try
            {
                var account =
                    CloudStorageAccount.FromConfigurationSetting(CommonConfiguration.DefaultStorageConnection.ToString());
                account.Ensure(containers: new[] { containerName });

                var bc        = account.CreateCloudBlobClient();
                var container = bc.GetContainerReference(containerName);


                BlobRequestOptions blobQuery = new BlobRequestOptions();
                blobQuery.BlobListingDetails = BlobListingDetails.Metadata;
                blobQuery.UseFlatBlobListing = true;

                if (ct.HasValue)
                {
                    ct.Value.ThrowIfCancellationRequested();
                }


                IEnumerable <IListBlobItem> blobs;
                blobs = container.ListBlobs(blobQuery).ToArray();


                foreach (IListBlobItem blob in blobs)
                {
                    if (ct.HasValue)
                    {
                        ct.Value.ThrowIfCancellationRequested();
                    }

                    CloudBlob cloudBlob;

                    cloudBlob = container.GetBlobReference(blob.Uri.ToString());

                    var md = cloudBlob.Metadata[BlobMetaPropertyExpired];
                    if (!string.IsNullOrWhiteSpace(md))
                    {
                        DateTime expirationDate = DateTime.Parse(md, CultureInfo.InvariantCulture);
                        if (DateTime.UtcNow > expirationDate)
                        {
                            dblog.InfoFormat("Grooming blob {0}", cloudBlob.Uri);
                            cloudBlob.DeleteIfExists(blobQuery);
                        }
                    }
                }

                if (removeEmptyContainer)
                {
                    if (!container.ListBlobs().Any())
                    {
                        container.Delete();
                    }
                }
            }
            catch (Exception ex)
            {
                log.Warn(ex.Message);
                log.Warn(ex.ToString());
                throw;
            }
        }
Пример #13
0
        protected override string BuildPaymentButton(string trxInfo, BillingPlan bp, BrokerTransactionType tt)
        {
            Debug.Assert(!string.IsNullOrEmpty(trxInfo));
            Debug.Assert(null != bp);

            _logger.InfoFormat(
                "Building payment button with transaction info {0}, billing plan {1} and transaction type {2}", trxInfo,
                bp.Name, tt);

            PayPalEncryptedButton subscribeButton = new PayPalEncryptedButton();

            IConfig config          = Catalog.Factory.Resolve <IConfig>();
            var     businessID      = config[PayPalConfiguration.BusinessId];
            var     cancelReturnUrl = config[PayPalConfiguration.CancelReturnUrl];
            var     notificationUrl = config[PayPalConfiguration.NotificationUrl];

            string     itemName, returnUrl, invoice;
            TemporalId payId = new TemporalId();

            if (tt == BrokerTransactionType.Upgrade)
            {
                itemName  = config[PayPalConfiguration.UpgradeItem];
                returnUrl = config[PayPalConfiguration.UpgradeReturnUrl];

                invoice = string.Format("{0}:{1}:{2}", UpgradePrefix, bp.Name, payId);
            }
            else
            {
                itemName  = config[PayPalConfiguration.ExpressItem];
                returnUrl = config[PayPalConfiguration.ExpressReturnUrl];

                invoice = string.Format("{0}:{1}:{2}", ExpressPrefix, bp.Name, payId);
            }
            _logger.InfoFormat("invoice: {0}", invoice);

            const int one = 1;

            subscribeButton.AddParameter(PayPal.Command, PayPal.ClickSubscription)
            .AddParameter(PayPal.Business, businessID)
            .AddParameter(PayPal.SubscribeButtonLanguage, PayPal.USEnglishLanguage)
            .AddParameter(PayPal.ItemName, itemName)
            .AddParameter(PayPal.BuyerIncludeNoteWithPayment, PayPal.HideNoteFromUser)
            .AddParameter(PayPal.ShippingAddressMode, PayPal.ShippingModeHideAddress)
            .AddParameter(PayPal.ReturnToAppMethod, PayPal.ReturnMethodGetNoVariables)
            .AddParameter(PayPal.GoToOnPayment, returnUrl)
            .AddParameter(PayPal.SubscriptionRecurrence, PayPal.SubscriptionRecurs)
            .AddParameter(PayPal.SubscriptionPrice, string.Format("{0:0.00}", bp.Rate))
            .AddParameter(PayPal.SubscriptionDuration, one.ToString())
            .AddParameter(PayPal.SubscriptionUnits, PayPal.TimeUnitMonth)
            .AddParameter(PayPal.CurrencyCode, PayPal.CurrencyUSDollar)
            .AddParameter(PayPal.TransactionNotificationGatewayURL, notificationUrl)
            .AddParameter(PayPal.GotoOnCancel, cancelReturnUrl)
            .AddParameter(PayPal.Custom, trxInfo)
            .AddParameter(PayPal.InvoiceIdentifier, invoice);


            if (bp.GracePeriodDays > 0)
            {
                subscribeButton.AddParameter(PayPal.TrialPeriodPrice, "0.00")
                .AddParameter(PayPal.TrialPeriodDuration, bp.GracePeriodDays.ToString())
                .AddParameter(PayPal.TrialPeriodUnits, PayPal.TimeUnitDay);
            }

            _dblogger.InfoFormat("subscription button: {0}", subscribeButton.Plain);

            return(subscribeButton.Encrypted);
        }
Пример #14
0
        public void ProcessIPNRequest(HttpRequest ipnRequest)
        {
            Debug.Assert(!string.IsNullOrWhiteSpace(EmailTemplateShare));
            Debug.Assert(!string.IsNullOrWhiteSpace(EmailTemplateSubscriptionAuthCode));
            Debug.Assert(!string.IsNullOrWhiteSpace(EmailTemplateSubscriptionFail));
            Debug.Assert(!string.IsNullOrWhiteSpace(EmailTemplateSubscriptionSignUp));
            Debug.Assert(!string.IsNullOrWhiteSpace(SubscriptionRole));
            Debug.Assert(!string.IsNullOrWhiteSpace(UnsubscribedRole));


            PaymentTransaction trx = null;

            try
            {
                string itemName        = ipnRequest.Form[PayPal.ItemName];
                string receiverEmail   = ipnRequest.Form[PayPal.ReceiverEmail];
                string payerEmail      = ipnRequest.Form[PayPal.PayerEmail];
                string trxInfo         = ipnRequest.Form[PayPal.Custom];
                string transactionCode = ipnRequest.Form[PayPal.TransactionCode];
                string invoice         = ipnRequest.Form[PayPal.InvoiceIdentifier];
                string txnId           = ipnRequest.Form[PayPal.TransactionId];
                if (string.IsNullOrEmpty(txnId))
                {
                    txnId = invoice;
                }
                _dblog.InfoFormat("Payment notification: {0}", ipnRequest.Form);

                string[] checkNames =
                {
                    PayPal.ItemName,        PayPal.ReceiverEmail,     PayPal.PayerEmail, PayPal.Custom,
                    PayPal.TransactionCode, PayPal.InvoiceIdentifier, PayPal.TransactionId
                };
                var bad = from c in checkNames where string.IsNullOrWhiteSpace(ipnRequest.Form[c]) select c;
                if (bad.Any())
                {
                    _log.FatalFormat("Bad payment notification, missing arguments: {0}", string.Join(",", bad));
                    return;
                }


                trx = new PaymentTransaction
                {
                    Id              = txnId,
                    Item            = itemName,
                    Currency        = "USD",
                    PaymentStatus   = "x",
                    Principal       = trxInfo,
                    ReceiverEmail   = receiverEmail,
                    PayerEmail      = payerEmail,
                    Response        = "VERIFIED",
                    TransactionTime = DateTime.UtcNow,
                    TransactionCode = transactionCode
                };

                //Post back to either sandbox or live
                //string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
                //string strLive = "https://www.paypal.com/cgi-bin/webscr";
                string postback = _config[PayPalConfiguration.PostUrl];

                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(postback);

                //Set values for the request back
                req.Method      = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                byte[] param      = ipnRequest.BinaryRead(ipnRequest.ContentLength);
                string strRequest = Encoding.ASCII.GetString(param);
                strRequest       += "&cmd=_notify-validate";
                req.ContentLength = strRequest.Length;

                //Send the request to PayPal and get the response
                StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII);
                streamOut.Write(strRequest);
                streamOut.Close();
                StreamReader streamIn    = new StreamReader(req.GetResponse().GetResponseStream());
                string       strResponse = streamIn.ReadToEnd();
                streamIn.Close();

                if (strResponse == PayPal.Verified)
                {
                    //check that receiver_email is your Primary PayPal email
                    string receiverEmailVerify = _config[PayPalConfiguration.ReceiveEmail];
                    if (string.IsNullOrEmpty(receiverEmail) || receiverEmail != receiverEmailVerify)
                    {
                        throw new IPNGatewayException(string.Format("Bad IPN receiver.", receiverEmail));
                    }

                    // check that txn_id has not been previously processed
                    using (var ds = DocumentStoreLocator.ResolveOrRoot(CommonConfiguration.CoreDatabaseRoute))
                    {
                        var prev = ds.Load <PaymentTransaction>(txnId);
                        if (prev != null)
                        {
                            trx.Id = string.Format("dup: {0} @{1}", txnId, Guid.NewGuid());
                            throw new IPNGatewayException("Duplicate completed transaction received.");
                        }
                    }

                    // process payment
                    _accountBroker.ProcessPaymentNotification(trxInfo, invoice, transactionCode, payerEmail,
                                                              SubscriptionRole, UnsubscribedRole,
                                                              EmailTemplateSubscriptionAuthCode,
                                                              EmailTemplateSubscriptionSignUp,
                                                              EmailTemplateSubscriptionFail, EmailTemplateShare);
                }
                else if (strResponse == PayPal.Invalid)
                {
                    trx.Response = PayPal.Invalid;

                    throw new IPNGatewayException("Invalid IPN notification");
                }
            }
            catch (Exception ex)
            {
                _log.Error("IPN notification not verified!");
                _log.Error(ex.Message);
                _log.Error(ex.TraceInformation());
            }
            finally
            {
                if (trx != null && !string.IsNullOrEmpty(trx.PaymentStatus) && trx.PaymentStatus == "Completed")
                {
                    try
                    {
                        using (var ds = DocumentStoreLocator.ResolveOrRoot(CommonConfiguration.CoreDatabaseRoute))
                        {
                            ds.Store(trx);
                            ds.SaveChanges();
                        }
                    }
                    catch
                    {
                    }
                }
            } // finally
        }