Esempio n. 1
0
        private void Initialize(WorkflowHost host, string templateData)
        {
            _log   = ClassLogger.Create(GetType());
            _dblog = DebugOnlyLogger.Create(_log);

            _host = host;


            _workspaceContainerName = WorkflowShared.WorkflowInstanceWorkspaceName(Id);

            Workspace = Catalog.Preconfigure()
                        .Add(WorkspaceLocalConfig.WorkspaceName, _workspaceContainerName)
                        .ConfiguredResolve <IWorkspace>(_workflowWorkspaceKey);


            if (null == _wfLock)
            {
                _wfLock = ConstructLock(Id);
            }



            SpecifyUsingTemplate(templateData);

            var instance = new WorkflowInstanceInfo
            {
                Id                 = Id,
                TemplateName       = Name,
                LastActivity       = DateTime.UtcNow,
                NextActivationTime = DateTime.UtcNow,
                Status             = WorkflowStatus.Active.ToString(),
            };

            _instanceData.Store(instance);
        }
Esempio n. 2
0
        public DocumentDistributedMutex()
        {
            _log   = ClassLogger.Create(GetType());
            _dblog = DebugOnlyLogger.Create(_log);

            var config = Catalog.Factory.Resolve <IConfig>(SpecialFactoryContexts.Routed);

            _name = config[DistributedMutexLocalConfig.Name].ToLowerInvariant();
            var seconds = config.Get <int>(DistributedMutexLocalConfig.UnusedExpirationSeconds);

            if (seconds < 15)
            {
                seconds = 15;
            }


            _expireUnused = TimeSpan.FromSeconds(seconds);
            _renewWait    = TimeSpan.FromSeconds(seconds - 5);

            _cts                 = new CancellationTokenSource();
            _cancelGrooming      = new CancellationTokenSource();
            _cancelGroomingToken = _cancelGrooming.Token;

            _groomingTask = Task.Factory.StartNew(GroomExpired, _cancelGroomingToken);
            _acquirer     = Guid.NewGuid();
            CreateIfNotExists();
        }
        public PrincipalTenancyContextProvider()
        {
            try
            {
                _log = ClassLogger.Create(this.GetType());
                this.principalContextProvider =
                    (Catalog.Factory.Resolve <IContextProvider>(
                         PrincipalTenancyContextProviderConfiguration.PrincipalContextFactoryKey)
                     ?? Catalog.Factory.Resolve <IContextProvider>("TenancyContext"))
                    ?? Catalog.Factory.Resolve <IContextProvider>();
            }
            catch (Exception ex)
            {
                if (ex.InnerException != null)
                {
                    _log.Error(ex.ToString() + " \n InnerException: " + ex.InnerException.ToString());
                }
                else
                {
                    _log.Error(ex.ToString());
                }
                Console.WriteLine(ex.ToString());
            }

            this.cachedTenancies =
                Catalog.Preconfigure().Add(CachedDataLocalConfig.OptionalMaximumCacheSize, 5000).Add(
                    CachedDataLocalConfig.OptionalGroomExpiredData, true).Add(
                    CachedDataLocalConfig.OptionalDefaultExpirationTimeSeconds, 600).Add(
                    CachedDataLocalConfig.OptionalCacheHitRenewsExpiration, true).ConfiguredCreate(
                    () => new InMemoryCachedData <string, string>());
        }
Esempio n. 4
0
 public WorkflowStateMachine(WorkflowContext ctx, StateMachine <string, string> inner, string activationTrigger)
 {
     _ctx               = ctx;
     _machine           = inner;
     _activationTrigger = activationTrigger;
     _log               = ClassLogger.Create(GetType());
 }
        private static void DistributeDefaultApplications(IDocumentSession coreSession, IEnumerable <Tenant> tenants)
        {
            var log          = ClassLogger.Create(typeof(ApplicationManager));
            var applications = new List <Application>();
            var query        = (from apps in coreSession.Query <Application>() select apps).ToList();

            if (query.Any())
            {
                applications.AddRange(query);
            }

            foreach (var tenant in tenants)
            {
                using (var session = DocumentStoreLocator.Resolve(tenant.Site))
                {
                    var q = (from apps in session.Query <Application>() select apps).ToList();

                    if (!q.Any())
                    {
                        Storage(ref applications);
                        foreach (var app in applications)
                        {
                            session.Store(app);
                            log.InfoFormat("The {0} Application has been Stored in {1} Tenant sucessfully", app.Name, tenant.Name);
                        }
                    }

                    session.SaveChanges();
                }
            }
        }
        public AzureFilesBlobContainer()
        {
            _log   = ClassLogger.Create(GetType());
            _dblog = DebugOnlyLogger.Create(_log);

            var config = Catalog.Factory.Resolve <IConfig>(SpecialFactoryContexts.Routed);

            _containerName = config[BlobContainerLocalConfig.ContainerName];
            EntityAccess access = (EntityAccess)Enum.Parse(typeof(EntityAccess),
                                                           config.Get(BlobContainerLocalConfig.OptionalAccess,
                                                                      EntityAccess.Private.ToString()));

            _contentType = config.Get(BlobContainerLocalConfig.OptionalContentType, "application/raw");

            _account = Client.FromConfig();
            _client  = _account.CreateCloudBlobClient();

            _client.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(5));

            var blobContainerPermissions = new BlobContainerPermissions
            {
                PublicAccess = AzureEntityAccessTranslator.Translate(access)
            };

            _blobContainerPermissions = blobContainerPermissions;
            _container = _client.GetContainerReference(_containerName.ToLowerInvariant());

            if (_container.CreateIfNotExist())
            {
                _container.SetPermissions(_blobContainerPermissions);
            }
        }
Esempio n. 7
0
 public PayPalIPNGateway()
 {
     _accountBroker = Catalog.Factory.Resolve <IAccountTypeBroker>();
     _log           = ClassLogger.Create(GetType());
     _dblog         = DebugOnlyLogger.Create(_log);
     _config        = Catalog.Factory.Resolve <IConfig>();
 }
 public AccountController()
 {
     _accountBusinessLogic    = new AccountBusinessLogic();
     _navigationBusinessLogic = new NavigationBusinessLogic();
     _log = ClassLogger.Create(this.GetType());
     _applicationAlert = Catalog.Factory.Resolve <IApplicationAlert>();
 }
Esempio n. 9
0
        public LocalMessageBus()
        {
            _log   = ClassLogger.Create(GetType());
            _dblog = DebugOnlyLogger.Create(_log);

            var source = new CancellationTokenSource();

            _ct = source.Token;
        }
Esempio n. 10
0
        public override bool InterceptInstead(Invocation invocation, object target, ShapeableExpando extensions, out object resultData)
        {
            _log = ClassLogger.Create(target.GetType());
            var msg = string.Format("Intercept the method {0}, with name {1}.", invocation.Kind, invocation.Name);

            _log.Info(msg);
            resultData = null;
            return(true);
        }
Esempio n. 11
0
        public void Initialize(CancellationToken token)
        {
            _log   = ClassLogger.Create(GetType());
            _dblog = DebugOnlyLogger.Create(_log);

            _ct = token;

            Compose();
        }
Esempio n. 12
0
        /// <summary>
        ///   use the expiration metadata attribute to remove expired containers.
        /// </summary>
        /// <param name="prefix"> </param>
        /// <param name="ct"> </param>
        public static void GroomExpiredContainers(string prefix = null, CancellationToken?ct = null)
        {
            ILog            log   = ClassLogger.Create(typeof(AzureStorageAssistant));
            DebugOnlyLogger dblog = DebugOnlyLogger.Create(log);

            try
            {
                var account =
                    CloudStorageAccount.FromConfigurationSetting(CommonConfiguration.DefaultStorageConnection.ToString());
                var bc = account.CreateCloudBlobClient();

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

                IEnumerable <CloudBlobContainer> containers;
                if (!string.IsNullOrEmpty(prefix))
                {
                    containers = bc.ListContainers(prefix);
                }
                else
                {
                    containers = bc.ListContainers();
                }

                if (ct.HasValue)
                {
                    ct.Value.ThrowIfCancellationRequested();
                }
                Parallel.ForEach(containers,
                                 c =>
                {
                    c.FetchAttributes();
                    if (ct.HasValue)
                    {
                        ct.Value.ThrowIfCancellationRequested();
                    }
                    if (c.Metadata.AllKeys.Contains(BlobMetaPropertyExpired))
                    {
                        DateTime expirationTime =
                            DateTime.Parse(c.Metadata[BlobMetaPropertyExpired],
                                           CultureInfo.InvariantCulture);
                        if (DateTime.UtcNow > expirationTime)
                        {
                            c.Delete();
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                log.Warn(ex.Message);
                log.Warn(ex.ToString());
                throw;
            }
        }
        public AccountTypeBrokerBase()
        {
            _log    = ClassLogger.Create(GetType());
            _dblog  = DebugOnlyLogger.Create(_log);
            _config = Catalog.Factory.Resolve <IConfig>();

            _sender   = _config[SendEmailSettings.EmailReplyAddress];
            _authCode = string.Empty;
        }
Esempio n. 14
0
        public override bool InterceptBefore(Invocation invocation, object target, ShapeableExpando extensions, out object resultData)
        {
            _log = ClassLogger.Create(target.GetType());
            var msg = string.Format("Intercept the method {0}, with name{1}", invocation.Kind, invocation.Name);

            if (invocation.Arguments.Length > 0)
            {
                msg += string.Format(" that has the following parameters:{0}", invocation.Arguments);
            }
            _log.Info(msg);
            resultData = null;
            return(true);
        }
Esempio n. 15
0
        public RavenGlobalConfig()
        {
            var cf      = Catalog.Factory.Resolve <IConfig>(SpecialFactoryContexts.Routed);
            var company = cf[ApplicationTopologyLocalConfig.CompanyKey];
            var product = cf[ApplicationTopologyLocalConfig.ApplicationKey];

            _reg = new ApplicationNodeRegistry(company, product);

            _log   = ClassLogger.Create(GetType());
            _dbLog = DebugOnlyLogger.Create(_log);

            _updateCycle = Catalog.Factory.Resolve <IRecurrence <object> >();
        }
Esempio n. 16
0
        public AzureEnvironmentDistributedMutex()
        {
            _log   = ClassLogger.Create(GetType());
            _dblog = DebugOnlyLogger.Create(_log);

            var config = Catalog.Factory.Resolve <IConfig>(SpecialFactoryContexts.Routed);

            _name         = config[DistributedMutexLocalConfig.Name].ToLowerInvariant();
            _expireUnused = TimeSpan.FromSeconds(config.Get <int>(DistributedMutexLocalConfig.UnusedExpirationSeconds));

            var account = Client.FromConfig().ForBlobs();

            _container = account.GetContainerReference(AzureConstants.LeaseContainer);
            _container.CreateIfNotExist();

            _leaseBlob = _container.GetBlobReference(_name);

            _cts            = new CancellationTokenSource();
            _cancelGrooming = new CancellationTokenSource();

            try
            {
                if (!_leaseBlob.Exists())
                {
                    _leaseBlob.UploadText("1");
                    _leaseBlob.SetExpiration(_expireUnused);

                    _log.InfoFormat("Creating distributed mutex for {0}, auto expires in {1}", _name, _expireUnused);
                }
            }
            catch (StorageClientException storageClientException1)
            {
                StorageClientException storageClientException = storageClientException1;
                if (storageClientException.ErrorCode == StorageErrorCode.BlobAlreadyExists ||
                    storageClientException.StatusCode == HttpStatusCode.PreconditionFailed)
                {
                }
                else
                {
                    throw;
                }
            }


            _groomingTask =
                Task.Factory.StartNew(
                    () =>
                    AzureStorageAssistant.CleanExpiredBlobsFrom(AzureConstants.LeaseContainer, _cancelGrooming.Token,
                                                                false));
        }
Esempio n. 17
0
        private static void Listen(object that)
        {
            var  @this = (MemMessageListener)that;
            var  log   = ClassLogger.Create(typeof(MemMessageListener));
            bool first = true;

            try
            {
                while (!@this._ct.IsCancellationRequested)
                {
                    bool sent = true;

                    {
                        first = false;
                        sent  = @this._sev.Wait(60000, @this._ct);
                    }

                    if (sent && !@this._ct.IsCancellationRequested)
                    {
                        try
                        {
                            LightMessageQueueEnvelope env;
                            var messageRead = @this._q.TryDequeue(out env);
                            while (messageRead)
                            {
                                var msg = env.Decode();

                                if (@this._sinks.ContainsKey(env.MessageType))
                                {
                                    var sink = @this._sinks[env.MessageType];
                                    sink(msg, @this._cts.Token, new MemQueueAcknowledge(@this, env));
                                }

                                messageRead = @this._q.TryDequeue(out env);
                            }
                        }
                        catch (Exception ex)
                        {
                            var es = ex.TraceInformation();
                            log.Error(es);
                        }

                        @this._sev.Reset();
                    }
                }
            }
            catch (OperationCanceledException)
            {
            }
        }
Esempio n. 18
0
        public OwnerInvitationController()
        {
            _invitationUILogic = new InvitationUILogic();
            _systemOwnerId     = _invitationUILogic.GetSuperAdminId();

            _log = ClassLogger.Create(this.GetType());
            _applicationAlert = Catalog.Factory.Resolve <IApplicationAlert>();
            _command          = new List <string> {
                "Create", "Edit", "Details", "Delete", "Sent Email"
            };
            _command1 = new List <string> {
                "Edit", "Details", "Delete", "Sent Email"
            };
        }
Esempio n. 19
0
        public ItemRegistrationController()
        {
            _itemRegistrationUILogic = new ItemRegistrationUILogic();

            _log = ClassLogger.Create(GetType());
            _applicationAlert = Catalog.Factory.Resolve <IApplicationAlert>();
            _command          = new List <string>
            {
                "Add",
                "Delete",
                "Assign Tag",
                "Clear Tag"
            };
        }
Esempio n. 20
0
        public BlobFileDownload(string container = null)
        {
            if (string.IsNullOrWhiteSpace(container))
            {
                IConfig config = Catalog.Factory.Resolve <IConfig>();
                _container = config.Get(CommonConfiguration.DefaultDownloadContainer, "downloads");
            }
            else
            {
                _container = container;
            }

            _log   = ClassLogger.Create(GetType());
            _dblog = DebugOnlyLogger.Create(_log);
        }
Esempio n. 21
0
        public ScheduledJobWorker()
        {
            _hostEnv = Catalog.Factory.Resolve <IHostEnvironment>();

            _logger = ClassLogger.Create(typeof(ScheduledJobWorker));
            _dlog   = DebugOnlyLogger.Create(_logger);

            _jobScheduler = Catalog.Factory.Resolve <IJobScheduler>();

            var config = Catalog.Factory.Resolve <IConfig>();

            _sender = Catalog.Preconfigure()
                      .Add(MessagePublisherLocalConfig.HostConnectionString, config[CommonConfiguration.DefaultBusConnection])
                      .Add(MessagePublisherLocalConfig.ExchangeName, ExchangeName)
                      .ConfiguredResolve <IMessagePublisher>(ScopeFactoryContexts.Distributed);
        }
Esempio n. 22
0
        public AzureBlobBlobContainer()
        {
            _log   = ClassLogger.Create(GetType());
            _dblog = DebugOnlyLogger.Create(_log);

            var config = Catalog.Factory.Resolve <IConfig>(SpecialFactoryContexts.Routed);

            _containerName = config.Get(BlobContainerLocalConfig.ContainerName, string.Empty);
            EntityAccess access = (EntityAccess)Enum.Parse(typeof(EntityAccess),
                                                           config.Get(BlobContainerLocalConfig.OptionalAccess,
                                                                      EntityAccess.Private.ToString()));

            _contentType = config.Get(BlobContainerLocalConfig.OptionalContentType, "application/json");

            _account = Client.FromConfig();

            if (String.IsNullOrEmpty(_containerName))
            {
                var type = typeof(T);
                if (!type.IsClass)
                {
                    throw new ArgumentNullException("You must specify a container for containers that use value types.");
                }
                _containerName = type.Name.ToLowerInvariant();
                if ((_containerName.EndsWith("blob") || _containerName.EndsWith("view")) && _containerName.Length > 4)
                {
                    _containerName = _containerName.Substring(0, _containerName.Length - 4);
                }
            }

            _client             = _account.CreateCloudBlobClient();
            _client.RetryPolicy = RetryPolicies.Retry(3, TimeSpan.FromSeconds(5));

            var blobContainerPermissions = new BlobContainerPermissions
            {
                PublicAccess = AzureEntityAccessTranslator.Translate(access)
            };

            _blobContainerPermissions = blobContainerPermissions;
            _container = _client.GetContainerReference(_containerName.ToLowerInvariant());

            if (_container.CreateIfNotExist())
            {
                _container.SetPermissions(_blobContainerPermissions);
            }
        }
Esempio n. 23
0
        public BlobDataSpooler()
        {
            _log   = ClassLogger.Create(GetType());
            _dblog = DebugOnlyLogger.Create(_log);

            var      config          = Catalog.Factory.Resolve <IConfig>(SpecialFactoryContexts.Routed);
            var      spoolId         = config[DataSpoolerLocalConfig.SpoolId];
            var      pageSize        = config.Get <int>(DataSpoolerLocalConfig.PageSize);
            var      lifeTimeMinutes = config.Get(DataSpoolerLocalConfig.OptionalLifeTimeMinutes, -1);
            TimeSpan?lifeTime        = null;

            if (lifeTimeMinutes != -1)
            {
                lifeTime = TimeSpan.FromMinutes(lifeTimeMinutes);
            }

            Initialize(spoolId, pageSize, lifeTime);
        }
Esempio n. 24
0
        public HorizonalScaleCloudQueue(CloudQueueClient queueClient, string queueBaseName, int numberOfPartitions)
        {
            _log   = ClassLogger.Create(GetType());
            _dblog = DebugOnlyLogger.Create(_log);


            _queueClient   = queueClient;
            _queueBaseName = queueBaseName;

            List <CloudQueue> partitions = new List <CloudQueue>();

            for (int i = 0; i < numberOfPartitions; i++)
            {
                CloudQueue q = queueClient.GetQueueReference(_queueBaseName + i);
                partitions.Add(q);
            }

            _queues = new List <CloudQueue>(Shuffle(partitions));
        }
Esempio n. 25
0
        private static void LogException(Exception exception, object target)
        {
            var message = string.Empty;
            if (HttpContext.Current != null)
            {
                message = string.Format("Url: {0}{1}", HttpContext.Current.Request.Url, Environment.NewLine);
            }

            message = message + exception.Message + Environment.NewLine + exception.TraceInformation();

            var reflectionException = exception as ReflectionTypeLoadException;
            if (reflectionException != null)
            {
                var sb2 = new StringBuilder();
                foreach (var exSub in reflectionException.LoaderExceptions)
                {
                    sb2.AppendLine(exSub.Message);
                    
                    var exFileNotFound = exSub as FileNotFoundException;
                    if (exFileNotFound != null)
                    {
                        if (!string.IsNullOrEmpty(exFileNotFound.FusionLog))
                        {
                            sb2.AppendLine("Fusion Log:");
                            sb2.AppendLine(exFileNotFound.FusionLog);
                        }
                    }
                    sb2.AppendLine();
                }

                // The message indicating the library or file is write in the project log.
                message = message + " Reflection Exception: " + sb2;
            }

            var logger = ClassLogger.Create(target.GetType());
            logger.Error(message);

            var aa = Catalog.Factory.Resolve<IApplicationAlert>();
            aa.RaiseAlert(ApplicationAlertKind.System, exception.TraceInformation());
        }
        public AzureBlobImageStorage()
        {
            _log   = ClassLogger.Create(GetType());
            _dblog = DebugOnlyLogger.Create(_log);

            var config              = Catalog.Factory.Resolve <IConfig>(SpecialFactoryContexts.Routed);
            var maxCacheSize        = config.Get <int>(ImageStorageLocalConfig.CacheSize);
            var hitRenewsExpiration = config.Get <bool>(ImageStorageLocalConfig.CacheHitRenewsExpiration);
            var minutes             = config.Get(ImageStorageLocalConfig.OptionalExpirationTimeMinutes, 60);
            var expirationLife      = TimeSpan.FromMinutes(minutes);

            _containerName = config[ImageStorageLocalConfig.ContainerName];

            _cache = Catalog.Preconfigure()
                     .Add(CachedDataLocalConfig.OptionalCacheHitRenewsExpiration, hitRenewsExpiration)
                     .Add(CachedDataLocalConfig.OptionalDefaultExpirationTimeSeconds, expirationLife)
                     .Add(CachedDataLocalConfig.OptionalGroomExpiredData, true)
                     .Add(CachedDataLocalConfig.OptionalMaximumCacheSize, maxCacheSize)
                     .ConfiguredResolve <ICachedData <string, byte[]> >(DurabilityFactoryContexts.Volatile);

            _bc = Client.FromConfig().ForBlobs();
        }
Esempio n. 27
0
        public AzureDistributedMessageBus()
        {
            var account =
                CloudStorageAccount.FromConfigurationSetting(CommonConfiguration.DefaultStorageConnection.ToString());

            account.Ensure(containers: new[] { _containerName });
            _qc = account.CreateCloudQueueClient();

            IConfig config = Catalog.Factory.Resolve <IConfig>(SpecialFactoryContexts.Routed);

            int partitionCount = 5;
            var busName        = config.Get(MessageBusLocalConfig.OptionalNamedMessageBus, GlobalBusName);

            if (GlobalBusName != busName)
            {
                _queueName = busName;
            }

            _q         = new HorizonalScaleCloudQueue(_qc, _queueName, partitionCount);
            _bc        = account.CreateCloudBlobClient();
            _container = _bc.GetContainerReference(_containerName);
            _log       = ClassLogger.Create(typeof(AzureDistributedMessageBus));
            _dblog     = DebugOnlyLogger.Create(_log);
        }
Esempio n. 28
0
        public UserController()
        {
            _userBusinessLogic = new UserBusinessLogic();
            _userUILogic       = new UserUILogic();
            _log = ClassLogger.Create(GetType());

            _applicationAlert = Catalog.Factory.Resolve <IApplicationAlert>();

            _command = new List <string>
            {
                "Invite New User",
                "Enable",
                "Disable",
                "Change User Role",
                "Edit User",
                "Details User",
                "Delete User",
                "Assign Tags",
                "Clear Tags",
                "ReSent Email",
                "Assign Group",
                "Remove Group"
            };
        }
Esempio n. 29
0
        public static void Check(params string[] roles)
        {
            Debug.Assert(roles.EmptyIfNull().Any());

            var log   = ClassLogger.Create(typeof(WebPermitRoles));
            var dblog = DebugOnlyLogger.Create(log);

            var context = HttpContext.Current;
            var user    = context.User;

            foreach (string role in roles)
            {
                if (user.IsInRole(role))
                {
                    dblog.InfoFormat("{0} granted access through role {1}", user.Identity.Name, role);
                    return;
                }
            }

            log.ErrorFormat("{0} is not in any role {1}, security exception", user.Identity.Name,
                            string.Join(",", roles));
            throw new SecurityException(string.Format("user {0} does not have role required for action.",
                                                      user.Identity.Name));
        }
 public void BeginLogging()
 {
     _log   = ClassLogger.Create(GetType());
     _dbLog = DebugOnlyLogger.Create(_log);
 }