public LoggingService(CancellationToken cancellationToken = default)
        {
#if DEBUG
            this.MaxItems = 3;
#else
            try
            {
                this.MaxItems = UtilityService.GetAppSetting("Logs:MaxItems", "13").CastAs <int>();
            }
            catch
            {
                this.MaxItems = 13;
            }
#endif
            try
            {
                this.KeepLogDays = UtilityService.GetAppSetting("Logs:KeepLogDays", "7").CastAs <int>();
            }
            catch
            {
                this.KeepLogDays = 7;
            }
            this.LoggingDataSource       = RepositoryMediator.GetDataSource(UtilityService.GetAppSetting("Logs:DataSource"));
            this.CancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
        }
Exemple #2
0
        void GenerateId()
        {
            string temp     = Email + Firstname;
            long   hashcode = Math.Abs(temp.GetHashCode());
            string verify   = new RepositoryMediator().AccountCheck(hashcode);

            if (verify.Equals("Job Searcher") || verify.Equals("Recruiter"))
            {
                Response.Write("Retry with another name and email id");
            }
            else
            {
                PersonDetails person = new PersonDetails(Firstname, Phonenumber, Lastname, Address, Password, Gender, Role, Email, hashcode);

                int result = new RepositoryMediator().CreateAccount(person);
                if (result == 1)
                {
                    Response.Write("signin successfully!!! Your account number is: " + hashcode);
                }
                else
                {
                    Response.Write("Unable to create account");
                }
            }
        }
 /// <summary>
 /// 依赖注入构造器
 /// </summary>
 /// <param name="svcMediator">领域服务中介者</param>
 /// <param name="repMediator">仓储中介者</param>
 /// <param name="unitOfWork">单元事务</param>
 public OnShelfDecorationPackEventHandler(DomainServiceMediator svcMediator, RepositoryMediator repMediator, IUnitOfWorkDesign unitOfWork)
 {
     this._svcMediator = svcMediator;
     this._repMediator = repMediator;
     this._unitOfWork  = unitOfWork;
     this.Sort         = uint.MaxValue;
 }
 /// <summary>
 /// 依赖注入构造器
 /// </summary>
 /// <param name="svcMediator">领域服务中介者</param>
 /// <param name="repMediator">仓储中介者</param>
 /// <param name="unitOfWork">单元事务</param>
 public PackSkuChangedEventHandler(DomainServiceMediator svcMediator, RepositoryMediator repMediator, IUnitOfWorkDesign unitOfWork)
 {
     this._svcMediator = svcMediator;
     this._repMediator = repMediator;
     this._unitOfWork  = unitOfWork;
     this.Sort         = uint.MaxValue;
 }
        public void GetAll_Should_Correctly_Get_The_Relevant_Entities()
        {
            var mediator = new RepositoryMediator <Entity>();
            var entity1  = new Entity()
            {
                Id = 1
            };
            var entity2 = new Entity()
            {
                Id = 2
            };
            var entity3 = new Entity()
            {
                Id = 3
            };
            var list = new List <Entity>()
            {
                entity1, entity2, entity3
            };
            var repo = new Repository <Entity>(mediator, list);

            var result = repo.GetAll();

            CollectionAssert.AreEquivalent(list, result.ToList());
        }
Exemple #6
0
 /// <summary>
 /// 依赖注入构造器
 /// </summary>
 /// <param name="svcMediator">领域服务中介者</param>
 /// <param name="repMediator">仓储中介者</param>
 /// <param name="unitOfWork">单元事务</param>
 public AuthorityCreatedEventHandler(DomainServiceMediator svcMediator, RepositoryMediator repMediator, IUnitOfWorkIdentity unitOfWork)
 {
     this._svcMediator = svcMediator;
     this._repMediator = repMediator;
     this._unitOfWork  = unitOfWork;
     this.Sort         = uint.MaxValue;
 }
Exemple #7
0
        /// <summary>
        /// Gets the parent content-type of this content-type
        /// </summary>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public static ContentType GetParent(this ContentType contentType)
        {
            var parentDefinition = RepositoryMediator.GetEntityDefinition(contentType?.EntityDefinition?.ParentType);

            return(parentDefinition != null
                                ? contentType?.Module?.ContentTypes?.FirstOrDefault(type => type.ContentTypeDefinitionID.Equals(parentDefinition.ID))
                                : null);
        }
        internal async Task CleanLogsAsync(CancellationToken cancellationToken = default)
        {
            using (var context = new RepositoryContext(false, await this.LoggingDataSource.StartSessionAsync <LoggingItem>(cancellationToken).ConfigureAwait(false)))
            {
                var filter = Filters <LoggingItem> .LessThan("Time", DateTime.Now.AddDays(0 - this.KeepLogDays));

                await RepositoryMediator.DeleteManyAsync(context, this.LoggingDataSource, filter, null, cancellationToken).ConfigureAwait(false);
            }
        }
Exemple #9
0
 /// <summary>
 /// 依赖注入构造器
 /// </summary>
 /// <param name="svcMediator">领域服务中介者</param>
 /// <param name="repMediator">仓储中介者</param>
 /// <param name="unitOfWork">单元事务</param>
 /// <param name="productContract"></param>
 /// <param name="craftEntityContract"></param>
 public PackPricedEventHandler(DomainServiceMediator svcMediator, RepositoryMediator repMediator, IUnitOfWorkDesign unitOfWork, IProductContract productContract, ICraftEntityContract craftEntityContract)
 {
     this._svcMediator    = svcMediator;
     this._repMediator    = repMediator;
     this._unitOfWork     = unitOfWork;
     _productContract     = productContract;
     _craftEntityContract = craftEntityContract;
     this.Sort            = uint.MaxValue;
 }
Exemple #10
0
 /// <summary>
 /// 依赖注入构造器
 /// </summary>
 /// <param name="repMediator">仓储中介者</param>
 /// <param name="unitOfWork">单元事务</param>
 public DataInitializer(RepositoryMediator repMediator, IUnitOfWorkIdentity unitOfWork)
 {
     this._repMediator = repMediator;
     this._unitOfWork  = unitOfWork;
     this._systems     = new List <InfoSystem>();
     this._users       = new List <User>();
     this._roles       = new List <Role>();
     this._menus       = new List <Menu>();
 }
 /// <summary>
 /// 依赖注入构造器
 /// </summary>
 /// <param name="svcMediator">领域服务中介者</param>
 /// <param name="repMediator">仓储中介者</param>
 /// <param name="unitOfWork">单元事务</param>
 /// <param name="customerModelContract">客户模型服务契约</param>
 /// <param name="productContract">商品资源服务契约</param>
 /// <param name="craftEntityContract">工艺资源服务契约</param>
 public ForAppContract(DomainServiceMediator svcMediator, RepositoryMediator repMediator, IUnitOfWorkDesign unitOfWork, ICustomerModelContract customerModelContract, IProductContract productContract, ICraftEntityContract craftEntityContract)
 {
     this._svcMediator      = svcMediator;
     this._repMediator      = repMediator;
     this._unitOfWork       = unitOfWork;
     _customerModelContract = customerModelContract;
     _productContract       = productContract;
     _craftEntityContract   = craftEntityContract;
 }
 async Task FlushIntoDatabaseAsync(CancellationToken cancellationToken = default)
 {
     using (var context = new RepositoryContext(true, await this.LoggingDataSource.StartSessionAsync <LoggingItem>(cancellationToken).ConfigureAwait(false)))
     {
         while (this.LoggingItems.TryDequeue(out var logItem))
         {
             await RepositoryMediator.CreateAsync(context, this.LoggingDataSource, logItem, cancellationToken).ConfigureAwait(false);
         }
     }
 }
Exemple #13
0
        protected void SubmitDetails(object sender, EventArgs e)
        {
            jobtype       = rdJobType.Text;
            jobposition   = txtPosition.Text;
            joblocation   = rdLocation.Text;
            jobgraduation = txtgraduation.Text;
            salary        = Convert.ToInt32(txtSalary.Text);
            string result = new RepositoryMediator().JobDetails(jobtype, joblocation, salary, jobgraduation, jobposition);

            Response.Write(result);
        }
Exemple #14
0
        public void Service_Should_Support_Manipulating_Of_Entities()
        {
            var mediator    = new RepositoryMediator <Entity>();
            var list        = new List <Entity>();
            var repo        = new Repository <Entity>(mediator, list);
            var cacheHelper = new FakeCacheHelper <Entity>(mediator);
            var service     = new Service <Entity>(repo, cacheHelper);
            var entity      = new Entity()
            {
                Id = 0
            };

            IEntity result;
            IEnumerable <IEntity> enumerable;

            IEntity[] array;

            result = service.GetById(0);

            Assert.AreEqual(null, result);

            service.Add(entity);

            result = service.GetById(0);

            Assert.AreEqual(entity, result);

            enumerable = service.GetAll();

            array = enumerable.ToArray();

            Assert.AreEqual(1, array.Length);
            Assert.AreEqual(entity, array[0]);

            service.Delete(entity);

            result = service.GetById(0);

            Assert.AreEqual(null, result);

            enumerable = service.GetAll();

            array = enumerable.ToArray();

            Assert.AreEqual(0, array.Length);

            cacheHelper.Dispose();

            service.Add(entity);

            result = service.GetById(0);

            Assert.AreEqual(entity, result);
        }
        public void Add_Should_Correctly_Add_The_Entity()
        {
            var mediator = new RepositoryMediator <Entity>();

            var list   = new List <Entity>();
            var repo   = new Repository <Entity>(mediator, list);
            var entity = new Entity()
            {
                Id = 0
            };

            repo.Add(entity);

            Assert.AreSame(entity, list[0]);
        }
        public void Get_Should_Correctly_Get_The_Correct_Entity()
        {
            var mediator = new RepositoryMediator <Entity>();
            var entity   = new Entity()
            {
                Id = 0
            };
            var list = new List <Entity>()
            {
                entity
            };
            var repo = new Repository <Entity>(mediator, list);

            var result = repo.Get(0);

            Assert.AreEqual(entity, result);
        }
        public void Delete_Should_Correctly_Delete_The_Entity()
        {
            var mediator = new RepositoryMediator <Entity>();
            var entity   = new Entity()
            {
                Id = 0
            };
            var list = new List <Entity>()
            {
                entity
            };
            var repo = new Repository <Entity>(mediator, list);

            repo.Delete(entity);

            Assert.AreEqual(list.Count, 0);
        }
        public async Task <JToken> FetchLogsAsync(int pageNumber = 1, int pageSize = 100, string correlationID = null, string developerID = null, string appID = null, string serviceName = null, string objectName = null, CancellationToken cancellationToken = default)
        {
            var  logs         = new JArray();
            long totalRecords = 0;

            using (var context = new RepositoryContext(false, await this.LoggingDataSource.StartSessionAsync <LoggingItem>(cancellationToken).ConfigureAwait(false)))
            {
                var filter = Filters <LoggingItem> .And();

                if (!string.IsNullOrWhiteSpace(correlationID))
                {
                    filter.Add(Filters <LoggingItem> .Equals("CorrelationID", correlationID));
                }
                if (!string.IsNullOrWhiteSpace(developerID))
                {
                    filter.Add(Filters <LoggingItem> .Equals("DeveloperID", developerID));
                }
                if (!string.IsNullOrWhiteSpace(appID))
                {
                    filter.Add(Filters <LoggingItem> .Equals("AppID", appID));
                }
                if (!string.IsNullOrWhiteSpace(serviceName))
                {
                    filter.Add(Filters <LoggingItem> .Equals("ServiceName", serviceName));
                }
                if (!string.IsNullOrWhiteSpace(objectName))
                {
                    filter.Add(Filters <LoggingItem> .Equals("ObjectName", objectName));
                }

                totalRecords = await RepositoryMediator.CountAsync(context, this.LoggingDataSource, filter, null, false, null, 0, cancellationToken).ConfigureAwait(false);

                var loggingItems = await RepositoryMediator.FindAsync(context, this.LoggingDataSource, filter, Sorts <LoggingItem> .Descending("Time"), pageSize, pageNumber, null, false, null, 0, cancellationToken).ConfigureAwait(false);

                loggingItems?.ForEach(loggingItem => logs.Add(loggingItem.ToJson()));
            }

            var totalPages = new Tuple <long, int>(totalRecords, pageSize).GetTotalPages();

            return(new JObject
            {
                { "Pagination", new Tuple <long, int, int, int>(totalRecords, totalPages, pageSize, totalPages > 0 && pageNumber > totalPages ? totalPages : pageNumber).GetPagination() },
                { "Objects", logs }
            });
        }
        public void Repository_Add_Generates_Event()
        {
            IEntity addedEntity = null;
            var     entity      = new Entity()
            {
                Id = 0
            };

            var mediator = new RepositoryMediator <Entity>();
            var list     = new List <Entity>();
            var repo     = new Repository <Entity>(mediator, list);

            mediator.EntityAdded += (s, e) => addedEntity = e.AddedEntity;

            repo.Add(entity);

            Assert.AreEqual(entity, addedEntity);
        }
        public void Repository_Get_Generates_Event()
        {
            IEntity retrievedEntity = null;
            var     entity          = new Entity()
            {
                Id = 0
            };

            var mediator = new RepositoryMediator <Entity>();

            var list = new List <Entity>();
            var repo = new Repository <Entity>(mediator, list);

            mediator.EntityRetrieved += (s, e) => retrievedEntity = e.RetrievedEntity;
            repo.Add(entity);
            repo.Get(0);

            Assert.AreEqual(entity, retrievedEntity);
        }
        public void Can_Subscribe_To_Multiple_Repositories()
        {
            var entity          = new Entity();
            var invocationCount = 0;

            var mediator = new RepositoryMediator <Entity>();

            var list1 = new List <Entity>();
            var list2 = new List <Entity>();
            var repo1 = new Repository <Entity>(mediator, list1);
            var repo2 = new Repository <Entity>(mediator, list2);

            mediator.EntityAdded += (s, e) => invocationCount++;

            repo1.Add(entity);
            repo1.Add(entity);
            repo2.Add(entity);

            Assert.AreEqual(3, invocationCount);
        }
        public void FakeCacheHelper_Should_Correctly_Support_Caching()
        {
            var mediator    = new RepositoryMediator <Entity>();
            var list        = new List <Entity>();
            var repo        = new Repository <Entity>(mediator, list);
            var cacheHelper = new FakeCacheHelper <Entity>(mediator);

            var entity = new Entity()
            {
                Id = 0
            };

            IEntity result;

            result = cacheHelper.GetFromCache(0);

            Assert.AreEqual(null, result);

            repo.Add(entity);

            result = cacheHelper.GetFromCache(0);

            Assert.AreEqual(entity, result);

            repo.Delete(entity);

            result = cacheHelper.GetFromCache(0);

            Assert.AreEqual(null, result);

            cacheHelper.Dispose();

            repo.Add(entity);

            result = cacheHelper.GetFromCache(0);

            Assert.AreEqual(null, result);
        }
Exemple #23
0
 /// <summary>
 /// Ensures indexes of an entity in No SQL database
 /// </summary>
 /// <param name="definition"></param>
 /// <param name="dataSource"></param>
 /// <param name="tracker"></param>
 /// <param name="cancellationToken"></param>
 /// <returns></returns>
 public static async Task EnsureNoSqlIndexesAsync(EntityDefinition definition, DataSource dataSource, Action <string, Exception> tracker = null, CancellationToken cancellationToken = default)
 {
     if (definition != null && dataSource != null && dataSource.Mode.Equals(RepositoryMode.NoSQL))
     {
         try
         {
             tracker?.Invoke($"Ensure indexes of No SQL: {definition.Type} [{dataSource.Name} @ {dataSource.Mode} => {definition.CollectionName}]", null);
             if (tracker == null && RepositoryMediator.IsDebugEnabled)
             {
                 RepositoryMediator.WriteLogs($"Ensure indexes of No SQL: {definition.Type} [{dataSource.Name} @ {dataSource.Mode} => {definition.CollectionName}]", null);
             }
             await definition.EnsureIndexesAsync(dataSource, tracker, cancellationToken).ConfigureAwait(false);
         }
         catch (Exception ex)
         {
             tracker?.Invoke($"Error occurred while ensuring indexes of No SQL: {definition.Type} [{dataSource.Name} @ {dataSource.Mode} => {definition.CollectionName}]", ex);
             if (tracker == null)
             {
                 RepositoryMediator.WriteLogs($"Cannot ensure indexes of No SQL: {definition.Type} [{dataSource.Name} @ {dataSource.Mode} => {definition.CollectionName}]", ex);
             }
         }
     }
 }
Exemple #24
0
        public void Mediator_Should_Support_Storing_Of_Mediators()
        {
            var mediator     = new Mediator();
            var repoMediator = new RepositoryMediator <Entity>();

            IMediator result;

            result = mediator.GetMediator <IRepositoryMediator <Entity> >();

            Assert.AreSame(null, result);

            mediator.AddMediator(typeof(IRepositoryMediator <Entity>), repoMediator);

            result = mediator.GetMediator <IRepositoryMediator <Entity> >();

            Assert.AreSame(repoMediator, result);

            mediator.RemoveMediator(typeof(IRepositoryMediator <Entity>));

            result = mediator.GetMediator <IRepositoryMediator <Entity> >();

            Assert.AreSame(null, result);
        }
 /// <summary>
 /// 依赖注入构造器
 /// </summary>
 /// <param name="repMediator">仓储中介者</param>
 /// <param name="unitOfWork">单元事务</param>
 public UserContract(RepositoryMediator repMediator, IUnitOfWorkIdentity unitOfWork)
 {
     this._repMediator = repMediator;
     this._unitOfWork  = unitOfWork;
 }
Exemple #26
0
 /// <summary>
 /// 依赖注入构造器
 /// </summary>
 /// <param name="repMediator">仓储中介者</param>
 public UserService(RepositoryMediator repMediator)
 {
     this._repMediator = repMediator;
 }
 /// <summary>
 /// 依赖注入构造器
 /// </summary>
 /// <param name="svcMediator">领域服务中介者</param>
 /// <param name="repMediator">仓储中介者</param>
 /// <param name="unitOfWork">单元事务</param>
 public AuthorizationContract(DomainServiceMediator svcMediator, RepositoryMediator repMediator, IUnitOfWorkIdentity unitOfWork)
 {
     this._svcMediator = svcMediator;
     this._repMediator = repMediator;
     this._unitOfWork  = unitOfWork;
 }
		static async Task SendNotificationAsync(this RequestInfo requestInfo, IPortalObject @object, string @event, Settings.Notifications notificationSettings, ApprovalStatus previousStatus, ApprovalStatus status, CancellationToken cancellationToken)
		{
			// check
			if (@object == null)
				return;

			// prepare settings
			var events = notificationSettings?.Events;
			var methods = notificationSettings?.Methods;
			var emails = notificationSettings?.Emails;
			var emailsByApprovalStatus = notificationSettings?.EmailsByApprovalStatus;
			var emailsWhenPublish = notificationSettings?.EmailsWhenPublish;
			var webHooks = notificationSettings?.WebHooks;
			var category = @object is Content ? (@object as Content).Category : null;
			var emailSettings = category != null ? category.EmailSettings : @object is Organization ? (@object as Organization).EmailSettings : null;

			var parent = @object.Parent;
			while (parent != null)
			{
				Settings.Notifications parentNotificationSettings = null;
				if (parent is Category parentAsCategory)
				{
					parentNotificationSettings = parentAsCategory.Notifications;
					emailSettings = emailSettings ?? parentAsCategory.EmailSettings;
				}
				else if (parent is ContentType parentAsContentType)
				{
					parentNotificationSettings = parentAsContentType.Notifications;
					emailSettings = emailSettings ?? parentAsContentType.EmailSettings;
				}
				else if (parent is Module parentAsModule)
				{
					parentNotificationSettings = parentAsModule.Notifications;
					emailSettings = emailSettings ?? parentAsModule.EmailSettings;
				}
				else if (parent is Organization parentAsOrganization)
				{
					parentNotificationSettings = parentAsOrganization.Notifications;
					emailSettings = emailSettings ?? parentAsOrganization.EmailSettings;
				}

				events = events != null && events.Count > 0 ? events : parentNotificationSettings?.Events;
				methods = methods != null && methods.Count > 0 ? methods : parentNotificationSettings?.Methods;
				emails = emails ?? parentNotificationSettings?.Emails;
				emailsByApprovalStatus = emailsByApprovalStatus ?? parentNotificationSettings?.EmailsByApprovalStatus;
				emailsWhenPublish = emailsWhenPublish ?? parentNotificationSettings?.EmailsWhenPublish;
				webHooks = webHooks ?? parentNotificationSettings?.WebHooks;
				parent = parent.Parent;
			}

			// stop if has no event
			if (events == null || events.Count < 1 || events.FirstOrDefault(e => e.IsEquals(@event)) == null)
				return;

			// prepare parameters
			var sender = (await requestInfo.GetUserProfilesAsync(new[] { requestInfo.Session.User.ID }, cancellationToken).ConfigureAwait(false) as JArray)?.FirstOrDefault();
			var businessObject = @object is IBusinessObject ? @object as IBusinessObject : null;
			var serviceName = ServiceBase.ServiceComponent.ServiceName;
			var objectName = (businessObject as RepositoryBase)?.GetObjectName() ?? @object.GetTypeName(true);
			var contentType = businessObject?.ContentType as ContentType;
			var organization = await (@object.OrganizationID ?? "").GetOrganizationByIDAsync(cancellationToken).ConfigureAwait(false);
			var alwaysUseHtmlSuffix = organization == null || organization.AlwaysUseHtmlSuffix;
			if (organization != null && organization._siteIDs == null)
				await organization.FindSitesAsync(cancellationToken).ConfigureAwait(false);
			var site = organization?.Sites.FirstOrDefault();
			var siteDomain = $"{site?.SubDomain}.{site?.PrimaryDomain}".Replace("*.", "www.").Replace("www.www.", "www.");
			var siteURL = $"http{(site != null && site.AlwaysUseHTTPs ? "s" : "")}://{siteDomain}/";

			// prepare the recipients and notification settings
			var recipientIDs = new List<string>();
			var sendWebHookNotifications = methods?.FirstOrDefault(method => method.IsEquals("WebHook")) != null && webHooks != null && webHooks.EndpointURLs != null && webHooks.EndpointURLs.Count > 0;
			var sendEmailNotifications = methods?.FirstOrDefault(method => method.IsEquals("Email")) != null;
			var emailNotifications = new Settings.EmailNotifications();

			switch (status)
			{
				case ApprovalStatus.Draft:
					recipientIDs = new[] { @object.CreatedID }.ToList();
					emailNotifications = emailsByApprovalStatus != null && emailsByApprovalStatus.ContainsKey($"{status}")
						? emailsByApprovalStatus[$"{status}"]
						: emails;
					break;

				case ApprovalStatus.Pending:
					recipientIDs = await @object.WorkingPrivileges.GetUserIDsAsync(PrivilegeRole.Editor, cancellationToken).ConfigureAwait(false);
					if (recipientIDs.Count < 1)
						recipientIDs = await @object.WorkingPrivileges.GetUserIDsAsync(PrivilegeRole.Moderator, cancellationToken).ConfigureAwait(false);
					if (recipientIDs.Count < 1)
						recipientIDs = await @object.WorkingPrivileges.GetUserIDsAsync(PrivilegeRole.Administrator, cancellationToken).ConfigureAwait(false);
					if (recipientIDs.Count < 1)
						recipientIDs = new[] { organization.OwnerID }.ToList();
					emailNotifications = emailsByApprovalStatus != null && emailsByApprovalStatus.ContainsKey($"{status}")
						? emailsByApprovalStatus[$"{status}"]
						: emails;
					break;

				case ApprovalStatus.Rejected:
					recipientIDs = new[] { @object.CreatedID }.ToList();
					emailNotifications = emailsByApprovalStatus != null && emailsByApprovalStatus.ContainsKey($"{status}")
						? emailsByApprovalStatus[$"{status}"]
						: emails;
					break;

				case ApprovalStatus.Approved:
					recipientIDs = await @object.WorkingPrivileges.GetUserIDsAsync(PrivilegeRole.Moderator, cancellationToken).ConfigureAwait(false);
					if (recipientIDs.Count < 1)
						recipientIDs = await @object.WorkingPrivileges.GetUserIDsAsync(PrivilegeRole.Administrator, cancellationToken).ConfigureAwait(false);
					if (recipientIDs.Count < 1)
						recipientIDs = new[] { organization.OwnerID }.ToList();
					emailNotifications = emailsByApprovalStatus != null && emailsByApprovalStatus.ContainsKey($"{status}")
						? emailsByApprovalStatus[$"{status}"]
						: emails;
					break;

				case ApprovalStatus.Published:
					recipientIDs = (await @object.WorkingPrivileges.GetUserIDsAsync(PrivilegeRole.Moderator, cancellationToken).ConfigureAwait(false))
						.Concat(await @object.WorkingPrivileges.GetUserIDsAsync(PrivilegeRole.Administrator, cancellationToken).ConfigureAwait(false))
						.Concat(new[] { @object.CreatedID }).ToList();
					if (recipientIDs.Count < 1)
						recipientIDs = new[] { organization.OwnerID }.ToList();
					emailNotifications = emailsByApprovalStatus != null && emailsByApprovalStatus.ContainsKey($"{status}")
						? emailsByApprovalStatus[$"{status}"]
						: emails;
					break;

				case ApprovalStatus.Archieved:
					recipientIDs = (await @object.WorkingPrivileges.GetUserIDsAsync(PrivilegeRole.Moderator, cancellationToken).ConfigureAwait(false))
						.Concat(await @object.WorkingPrivileges.GetUserIDsAsync(PrivilegeRole.Administrator, cancellationToken).ConfigureAwait(false))
						.Concat(new[] { @object.CreatedID, @object.LastModifiedID }).ToList();
					if (recipientIDs.Count < 1)
						recipientIDs = new[] { organization.OwnerID }.ToList();
					emailNotifications = emailsByApprovalStatus != null && emailsByApprovalStatus.ContainsKey($"{status}")
						? emailsByApprovalStatus[$"{status}"]
						: emails;
					break;
			}

			// prepare recipients
			recipientIDs = recipientIDs.Except(new[] { requestInfo.Session.User.ID }).Where(id => !string.IsNullOrWhiteSpace(id)).Distinct(StringComparer.OrdinalIgnoreCase).ToList();
			var recipients = await requestInfo.GetUserProfilesAsync(recipientIDs, cancellationToken).ConfigureAwait(false) as JArray;

			//  send app notifications
			try
			{
				var baseMessage = new BaseMessage
				{
					Type = $"Portals#Notification#{@event}",
					Data = new JObject
					{
						{ "Sender", new JObject
							{
								{ "ID", requestInfo.Session.User.ID },
								{ "Name", sender?.Get<string>("Name") ?? "Unknown" }
							}
						},
						{ "Action", @event },
						{ "Info", new JObject
							{
								{ "ServiceName", serviceName },
								{ "ObjectName", objectName },
								{ "SystemID", @object.OrganizationID },
								{ "ObjectID", @object.ID },
								{ "ObjectTitle", @object.Title },
								{ "Status", $"{status}" },
								{ "PreviousStatus", $"{previousStatus}" },
								{ "Time", DateTime.Now },
							}
						}
					}
				};
				await recipients.Select(recipient => recipient.Get<JArray>("Sessions"))
					.Where(sessions => sessions != null)
					.SelectMany(sessions => sessions.Select(session => session.Get<string>("DeviceID")))
					.ForEachAsync(deviceID => Utility.RTUService.SendUpdateMessageAsync(new UpdateMessage(baseMessage) { DeviceID = deviceID }, cancellationToken)).ConfigureAwait(false);
				if (Utility.Logger.IsEnabled(LogLevel.Debug))
					await requestInfo.WriteLogAsync($"Send app notifications successful\r\n{baseMessage.ToJson()}", cancellationToken).ConfigureAwait(false);
			}
			catch (Exception exception)
			{
				await requestInfo.WriteErrorAsync(exception, cancellationToken, "Error occurred while sending app notifications").ConfigureAwait(false);
			}

			// send email notifications
			if (sendEmailNotifications || emailsWhenPublish != null)
			{
				var appURL = $"/portals/initializer?x-request={("{" + $"\"SystemID\":\"{organization?.ID}\",\"ObjectName\":\"{objectName}\",\"ObjectID\":\"{@object.ID}\"" + "}").Url64Encode()}".GetAppURL();
				var normalizedHTMLs = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
				var definition = RepositoryMediator.GetEntityDefinition(@object.GetType());
				if (definition != null)
				{
					definition.Attributes.Where(attribute => attribute.IsCLOB != null && attribute.IsCLOB.Value).ForEach(attribute =>
					{
						var value = @object.GetAttributeValue<string>(attribute);
						normalizedHTMLs[attribute.Name] = value?.NormalizeHTML().NormalizeURLs(siteURL);
					});
					if (businessObject?.ExtendedProperties != null && definition.BusinessRepositoryEntities.TryGetValue(businessObject.RepositoryEntityID, out var repositiryEntity))
						repositiryEntity?.ExtendedPropertyDefinitions?.Where(propertyDefinition => propertyDefinition.Mode.Equals(ExtendedPropertyMode.LargeText)).ForEach(propertyDefinition =>
						{
							if (businessObject.ExtendedProperties.TryGetValue(propertyDefinition.Name, out var value))
								normalizedHTMLs[propertyDefinition.Name] = (value as string)?.NormalizeHTML().NormalizeURLs(siteURL);
						});
				}

				var @params = new Dictionary<string, ExpandoObject>(StringComparer.OrdinalIgnoreCase)
				{
					["Organization"] = organization?.ToJson(false, false, json =>
					{
						OrganizationProcessor.ExtraProperties.ForEach(name => json.Remove(name));
						json.Remove("Privileges");
						json["AlwaysUseHtmlSuffix"] = alwaysUseHtmlSuffix;
					}).ToExpandoObject(),
					["Site"] = site?.ToJson(json =>
					{
						SiteProcessor.ExtraProperties.ForEach(name => json.Remove(name));
						json.Remove("Privileges");
						json["Domain"] = siteDomain;
						json["URL"] = siteURL;
					}).ToExpandoObject(),
					["ContentTypeDefinition"] = contentType?.ContentTypeDefinition?.ToJson().ToExpandoObject(),
					["ModuleDefinition"] = contentType?.ContentTypeDefinition?.ModuleDefinition?.ToJson(json =>
					{
						(json as JObject).Remove("ContentTypeDefinitions");
						(json as JObject).Remove("ObjectDefinitions");
					}).ToExpandoObject(),
					["Module"] = contentType?.Module?.ToJson(false, false, json =>
					{
						ModuleProcessor.ExtraProperties.ForEach(name => json.Remove(name));
						json.Remove("Privileges");
					}).ToExpandoObject(),
					["ContentType"] = contentType?.ToJson(false, json =>
					{
						ModuleProcessor.ExtraProperties.ForEach(name => json.Remove(name));
						json.Remove("Privileges");
					}).ToExpandoObject(),
					["ParentContentType"] = contentType?.GetParent()?.ToJson(false, json =>
					{
						ModuleProcessor.ExtraProperties.ForEach(name => json.Remove(name));
						json.Remove("Privileges");
					}).ToExpandoObject(),
					["URLs"] = new JObject
					{
						{ "Public", $"{businessObject?.GetURL() ?? $"~/index"}{(alwaysUseHtmlSuffix ? ".html" : "")}".GetWebURL(siteURL) },
						{ "Portal", $"{businessObject?.GetURL() ?? $"~/index"}{(alwaysUseHtmlSuffix ? ".html" : "")}".GetWebURL($"{Utility.PortalsHttpURI}/~{organization?.Alias}/") },
						{ "Private", appURL },
						{ "Review", appURL }
					}.ToExpandoObject(),
					["HTMLs"] = normalizedHTMLs.ToExpandoObject(),
					["Sender"] = new JObject
					{
						{ "ID", requestInfo.Session.User.ID },
						{ "Name", sender?.Get<string>("Name") ?? "Unknown" },
						{ "Email", sender?.Get<string>("Email") },
						{ "URL", $"/users/profiles/{(sender?.Get<string>("Name") ?? "Unknown").GetANSIUri()}?x-request={("{\"ID\":\"" + requestInfo.Session.User.ID + "\"}").Url64Encode()}".GetAppURL() },
						{ "Location", await requestInfo.GetLocationAsync(cancellationToken).ConfigureAwait(false) },
						{ "IP", requestInfo.Session.IP },
						{ "AppName", requestInfo.Session.AppName },
						{ "AppPlatform", requestInfo.Session.AppPlatform }
					}.ToExpandoObject()
				};

				// add information of the CMS Category
				if (category != null)
					@params["Category"] = category.ToJson(false, false, json =>
					{
						CategoryProcessor.ExtraProperties.ForEach(name => json.Remove(name));
						json.Remove("Privileges");
						json["URL"] = $"{category.GetURL()}{(alwaysUseHtmlSuffix ? ".html" : "")}".GetWebURL(siteURL);
					}).ToExpandoObject();

				// normalize parameters for evaluating
				var language = requestInfo.CultureCode ?? "vi-VN";
				var languages = Utility.Languages.ContainsKey(language) ? Utility.Languages[language] : null;
				var requestExpando = requestInfo.ToExpandoObject(requestInfoAsExpandoObject =>
				{
					requestInfoAsExpandoObject.Set("Body", requestInfo.BodyAsExpandoObject);
					requestInfoAsExpandoObject.Get<ExpandoObject>("Header")?.Remove("x-app-token");
				});
				var objectExpando = @object.ToExpandoObject();
				var paramsExpando = new Dictionary<string, object>(@params.ToDictionary(kvp => kvp.Key, kvp => kvp.Value as object), StringComparer.OrdinalIgnoreCase)
				{
					{ "Event", @event },
					{ "Event-i18n", languages?.Get<string>($"events.{@event}") ?? @event },
					{ "ObjectName", objectName },
					{ "ObjectType", @object.GetTypeName() },
					{ "Status", $"{status}" },
					{ "Status-i18n", languages?.Get<string>($"status.approval.{status}") ?? $"{status}" },
					{ "PreviousStatus", $"{previousStatus}" },
					{ "PreviousStatus-i18n", languages?.Get<string>($"status.approval.{previousStatus}") ?? $"{previousStatus}" },
					{ "Signature", emailSettings?.Signature?.NormalizeHTMLBreaks() },
					{ "EmailSignature", emailSettings?.Signature?.NormalizeHTMLBreaks() }
				}.ToExpandoObject();

				JObject instructions = null;
				if (sendEmailNotifications || ([email protected]("Delete") && businessObject != null && status.Equals(ApprovalStatus.Published) && !status.Equals(previousStatus) && emailsWhenPublish != null))
					try
					{
						instructions = JObject.Parse(await UtilityService.FetchWebResourceAsync($"{Utility.APIsHttpURI}/statics/instructions/portals/{language}.json", cancellationToken).ConfigureAwait(false))?.Get<JObject>("notifications");
					}
					catch (Exception exception)
					{
						await requestInfo.WriteErrorAsync(exception, cancellationToken, "Error occurred while fetching instructions").ConfigureAwait(false);
					}

				// send email message
				if (sendEmailNotifications)
					try
					{
						var subject = emailNotifications?.Subject ?? instructions?.Get<JObject>("emailByApprovalStatus")?.Get<JObject>($"{status}")?.Get<string>("subject") ?? instructions?.Get<JObject>("email")?.Get<string>("subject");
						if (string.IsNullOrWhiteSpace(subject))
							subject = "[{{@params(Organization.Alias)}}] - \"{{@current(Title)}}\" was {{@toLower(@params(Event))}}d";
						var body = emailNotifications?.Body ?? instructions?.Get<JObject>("emailByApprovalStatus")?.Get<JObject>($"{status}")?.Get<string>("body") ?? instructions?.Get<JObject>("email")?.Get<string>("body");
						if (string.IsNullOrWhiteSpace(body))
							body = @"Hi,
							The content that titled as ""<b>{{@current(Title)}}</b>"" ({{@params(ObjectName)}} on <a href=""{{@params(Site.URL)}}"">{{@params(Site.Title)}}</a>) was {{@toLower(@params(Event))}}d by {{@params(Sender.Name)}}.
							You can reach that content by one of these URLs below:
							<ul>
								<li>Public website: <a href=""{{@params(URLs.Public)}}"">{{@params(URLs.Public)}}</a></li>
								<li>CMS portals: <a href=""{{@params(URLs.Portal)}}"">{{@params(URLs.Portal)}}</a></li>
								<li>CMS apps: <a href=""{{@params(URLs.Private)}}"">{{@params(URLs.Private)}}</a></li>
							</ul>
							{{@params(EmailSignature)}}";
						var parameters = $"{subject}\r\n{body}"
							.GetDoubleBracesTokens()
							.Select(token => token.Item2)
							.Distinct(StringComparer.OrdinalIgnoreCase)
							.ToDictionary(token => token, token =>
							{
								return token.StartsWith("@[") && token.EndsWith("]")
									? Extensions.JsEvaluate(token.GetJsExpression(requestExpando, objectExpando, paramsExpando))
									: token.StartsWith("@")
										? token.Evaluate(new Tuple<ExpandoObject, ExpandoObject, ExpandoObject>(requestExpando, objectExpando, paramsExpando))
										: token;
							});
						var message = new EmailMessage
						{
							From = emailSettings?.Sender,
							To = recipients.Select(recipient => recipient.Get<string>("Email")).Where(email => !string.IsNullOrWhiteSpace(email)).Join(";") + (string.IsNullOrWhiteSpace(emailNotifications.ToAddresses) ? "" : $";{emailNotifications.ToAddresses}"),
							Cc = emailNotifications?.CcAddresses,
							Bcc = emailNotifications?.BccAddresses,
							Subject = subject.NormalizeHTMLBreaks().Format(parameters),
							Body = body.NormalizeHTMLBreaks().Format(parameters),
							SmtpServer = emailSettings?.Smtp?.Host,
							SmtpServerPort = emailSettings?.Smtp != null ? emailSettings.Smtp.Port : 0,
							SmtpServerEnableSsl = emailSettings?.Smtp != null && emailSettings.Smtp.EnableSsl,
							SmtpUsername = emailSettings?.Smtp?.User,
							SmtpPassword = emailSettings?.Smtp?.UserPassword,
							CorrelationID = requestInfo.CorrelationID
						};
						await Utility.MessagingService.SendEmailAsync(message, cancellationToken).ConfigureAwait(false);
						var log = "Add an email notification into queue successful" + "\r\n" +
							$"- ID: {message.ID}" + "\r\n" +
							$"- Object: {@object.Title} [{@object.GetType()}#{@object.ID}]" + "\r\n" +
							$"- Event: {@event}" + "\r\n" +
							$"- Status: {status} (previous: {previousStatus})" + "\r\n" +
							$"- Sender: {sender?.Get<string>("Name")} ({sender?.Get<string>("Email")})" + "\r\n" +
							$"- To: {message.To}" + (!string.IsNullOrWhiteSpace(message.Cc) ? $" / {message.Cc}" : "") + (!string.IsNullOrWhiteSpace(message.Bcc) ? $" / {message.Bcc}" : "") + "\r\n" +
							$"- Subject: {message.Subject}";
						await requestInfo.WriteLogAsync(log, cancellationToken).ConfigureAwait(false);
						if (Utility.Logger.IsEnabled(LogLevel.Debug))
							Utility.Logger.LogDebug($"Add an email notification into queue successful\r\n{message.ToJson()}");
					}
					catch (Exception exception)
					{
						await requestInfo.WriteErrorAsync(exception, cancellationToken, "Error occurred while adding an email notification into queue").ConfigureAwait(false);
					}

				// send special email message (when publish)
				if ([email protected]("Delete") && businessObject != null && status.Equals(ApprovalStatus.Published) && !status.Equals(previousStatus) && emailsWhenPublish != null)
					try
					{
						var subject = emailsWhenPublish?.Subject ?? instructions?.Get<JObject>("emailsWhenPublish")?.Get<string>("subject");
						if (string.IsNullOrWhiteSpace(subject))
							subject = "[{{@params(Organization.Alias)}}] - \"{{@current(Title)}}\" was published";
						var body = emailsWhenPublish?.Body ?? instructions?.Get<JObject>("emailsWhenPublish")?.Get<string>("body");
						if (string.IsNullOrWhiteSpace(body))
							body = @"Hi,
							The content that titled as ""<b>{{@current(Title)}}</b>"" ({{@params(ObjectName)}} on <a href=""{{@params(Site.URL)}}"">{{@params(Site.Title)}}</a>) was published by {{@params(Sender.Name)}}.
							You can reach that content by one of these URLs below:
							<ul>
								<li>Public website: <a href=""{{@params(URLs.Public)}}"">{{@params(URLs.Public)}}</a></li>
								<li>CMS portals: <a href=""{{@params(URLs.Portal)}}"">{{@params(URLs.Portal)}}</a></li>
								<li>CMS apps: <a href=""{{@params(URLs.Private)}}"">{{@params(URLs.Private)}}</a></li>
							</ul>
							{{@params(EmailSignature)}}";
						var parameters = $"{subject}\r\n{body}"
							.GetDoubleBracesTokens()
							.Select(token => token.Item2)
							.Distinct(StringComparer.OrdinalIgnoreCase)
							.ToDictionary(token => token, token =>
							{
								return token.StartsWith("@[") && token.EndsWith("]")
									? Extensions.JsEvaluate(token.GetJsExpression(requestExpando, objectExpando, paramsExpando))
									: token.StartsWith("@")
										? token.Evaluate(new Tuple<ExpandoObject, ExpandoObject, ExpandoObject>(requestExpando, objectExpando, paramsExpando))
										: token;
							});
						var message = new EmailMessage
						{
							From = emailSettings?.Sender,
							To = emailsWhenPublish?.ToAddresses,
							Cc = emailsWhenPublish?.CcAddresses,
							Bcc = emailsWhenPublish?.BccAddresses,
							Subject = subject.NormalizeHTMLBreaks().Format(parameters),
							Body = body.NormalizeHTMLBreaks().Format(parameters),
							SmtpServer = emailSettings?.Smtp?.Host,
							SmtpServerPort = emailSettings?.Smtp != null ? emailSettings.Smtp.Port : 0,
							SmtpServerEnableSsl = emailSettings?.Smtp != null && emailSettings.Smtp.EnableSsl,
							SmtpUsername = emailSettings?.Smtp?.User,
							SmtpPassword = emailSettings?.Smtp?.UserPassword,
							CorrelationID = requestInfo.CorrelationID
						};
						await Utility.MessagingService.SendEmailAsync(message, cancellationToken).ConfigureAwait(false);
						var log = "Add an email notification (notify when publish) into queue successful" + "\r\n" +
							$"- ID: {message.ID}" + "\r\n" +
							$"- Object: {@object.Title} [{@object.GetType()}#{@object.ID}]" + "\r\n" +
							$"- Event: {@event}" + "\r\n" +
							$"- Status: {status} (previous: {previousStatus})" + "\r\n" +
							$"- Sender: {sender?.Get<string>("Name")} ({sender?.Get<string>("Email")})" + "\r\n" +
							$"- To: {message.To}" + (!string.IsNullOrWhiteSpace(message.Cc) ? $" / {message.Cc}" : "") + (!string.IsNullOrWhiteSpace(message.Bcc) ? $" / {message.Bcc}" : "") + "\r\n" +
							$"- Subject: {message.Subject}";
						await requestInfo.WriteLogAsync(log, cancellationToken).ConfigureAwait(false);
						if (Utility.Logger.IsEnabled(LogLevel.Debug))
							Utility.Logger.LogDebug($"Add an email notification (notify when publish) into queue successful\r\n{message.ToJson()}");
					}
					catch (Exception exception)
					{
						await requestInfo.WriteErrorAsync(exception, cancellationToken, "Error occurred while adding an email notification (notify when publish) into queue").ConfigureAwait(false);
					}
			}

			// send web-hook notifications
			if (sendWebHookNotifications)
				try
				{
					var signAlgorithm = webHooks.SignAlgorithm ?? "SHA256";
					var signKey = webHooks.SignKey ?? requestInfo.Session.AppID;
					var query = webHooks.AdditionalQuery?.ToExpandoObject().ToDictionary(kvp => kvp.Key, kvp => kvp.Value as string) ?? new Dictionary<string, string>();
					var header = webHooks.AdditionalHeader?.ToExpandoObject().ToDictionary(kvp => kvp.Key, kvp => kvp.Value as string) ?? new Dictionary<string, string>();
					header = new Dictionary<string, string>(header, StringComparer.OrdinalIgnoreCase)
					{
						{ "Event", @event },
						{ "ObjectName", objectName },
						{ "ObjectType", @object.GetTypeName() },
						{ "Status", $"{status}" },
						{ "PreviousStatus", $"{previousStatus}" },
						{ "DeveloperID", requestInfo.Session.DeveloperID },
						{ "AppID", requestInfo.Session.AppID },
						{ "SiteID", site?.ID },
						{ "SiteTitle", site?.Title },
						{ "SiteDomain", siteDomain },
						{ "SiteURL", siteURL },
						{ "OrganizationID", organization?.ID },
						{ "OrganizationTitle", organization?.Title },
						{ "ModuleID", contentType?.Module?.ID },
						{ "ModuleTitle", contentType?.Module?.Title },
						{ "ContentTypeID", contentType?.ID },
						{ "ContentTypeTitle", contentType?.Title }
					};

					var message = new WebHookMessage
					{
						EndpointURL = webHooks.EndpointURLs[0],
						Body = @object.ToJson(json =>
						{
							if (webHooks.GenerateIdentity)
							{
								var id = json.Get<string>("ID");
								if (!string.IsNullOrWhiteSpace(id))
									json["ID"] = id.GenerateUUID();
							}
						}).ToString(Newtonsoft.Json.Formatting.None),
						Query = query,
						Header = header,
						CorrelationID = requestInfo.CorrelationID
					}.Normalize(signAlgorithm, signKey, webHooks.SignatureName, webHooks.SignatureAsHex, webHooks.SignatureInQuery);

					await webHooks.EndpointURLs.ForEachAsync(async (endpointURL, _) =>
					{
						message.ID = UtilityService.NewUUID;
						message.EndpointURL = endpointURL;
						await Utility.MessagingService.SendWebHookAsync(message, cancellationToken).ConfigureAwait(false);
						var log = "Add a web-hook notification into queue successful" + "\r\n" +
							$"- ID: {message.ID}" + "\r\n" +
							$"- Object: {@object.Title} [{@object.GetType()}#{@object.ID}]" + "\r\n" +
							$"- Event: {@event}" + "\r\n" +
							$"- Status: {status} (previous: {previousStatus})" + "\r\n" +
							$"- Endpoint URL: {message.EndpointURL}";
						await requestInfo.WriteLogAsync(log, cancellationToken).ConfigureAwait(false);
						if (Utility.Logger.IsEnabled(LogLevel.Debug))
							Utility.Logger.LogDebug($"Add a web-hook notification into queue successful\r\n{message.ToJson(json => { json["Query"] = message.Query.ToJObject(); json["Header"] = message.Header.ToJObject(); })}");
					}, cancellationToken).ConfigureAwait(false);
				}
				catch (Exception exception)
				{
					await requestInfo.WriteErrorAsync(exception, cancellationToken, "Error occurred while adding a web-hook notification into queue").ConfigureAwait(false);
				}
		}
Exemple #29
0
 /// <summary>
 /// 依赖注入构造器
 /// </summary>
 /// <param name="svcMediator">领域服务中介者</param>
 /// <param name="repMediator">仓储中介者</param>
 /// <param name="unitOfWork">单元事务</param>
 public ForTransContract(DomainServiceMediator svcMediator, RepositoryMediator repMediator, IUnitOfWorkDesign unitOfWork)
 {
     this._svcMediator = svcMediator;
     this._repMediator = repMediator;
     this._unitOfWork  = unitOfWork;
 }
        /// <summary>
        /// 套餐选区映射
        /// </summary>
        /// <param name="choiceArea"></param>
        /// <param name="repMediator"></param>
        /// <returns></returns>
        public static BalePackChoiceAreaInfo ToDTO(this BalePackChoiceArea choiceArea, RepositoryMediator repMediator)
        {
            BalePackChoiceAreaInfo choiceAreaInfo = Transform <BalePackChoiceArea, BalePackChoiceAreaInfo> .Map(choiceArea);

            choiceAreaInfo.BalePackInfo = choiceArea.BalePack.ToDTO();
            if (choiceArea.BalePack.BalePackType == BalePackType.Customized)
            {
                choiceAreaInfo.ExistsSku = repMediator.BalePackGroupRep.IsCustomizedPackShelfed(new List <Guid> {
                    choiceArea.Id
                });
            }
            if (choiceArea.BalePack.BalePackType == BalePackType.Bale)
            {
                choiceAreaInfo.ExistsSku = repMediator.BalePackGroupRep.IsBalePackShelfed(new List <Guid> {
                    choiceArea.Id
                });
            }
            return(choiceAreaInfo);
        }