/// <summary> /// Map entities to models /// </summary> /// <param name="linkTrackers"></param> /// <param name="searchModel"></param> /// <returns></returns> private IQueryable <LinkTrackerModel> Maps(IQueryable <LinkTracker> linkTrackers, LinkTrackerSearchModel searchModel) { var trackerLink = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "SiteApi", "LinkTracker", new { area = "" }, true); // Caculate the end date from date to DateTime?dateTo = null; if (searchModel.DateTo.HasValue) { dateTo = searchModel.DateTo.Value.ToEndDate(); } return(linkTrackers.Select(l => new LinkTrackerModel { Id = l.Id, Name = l.Name, TrackerLink = trackerLink + "?id=" + SqlFunctions.StringConvert((double)l.Id).Trim(), IsAllowMultipleClick = l.IsAllowMultipleClick, RedirectUrl = l.RedirectUrl ?? string.Empty, PageId = l.PageId, PageTitle = l.PageId.HasValue ? l.Page.Title : string.Empty, ClickCount = l.LinkTrackerClicks .Count(lc => (!searchModel.DateFrom.HasValue || lc.Created >= searchModel.DateFrom.Value) && (!dateTo.HasValue || lc.Created <= dateTo)), RecordOrder = l.RecordOrder, Created = l.Created, CreatedBy = l.CreatedBy, LastUpdate = l.LastUpdate, LastUpdateBy = l.LastUpdateBy })); }
public NewsCurlyBracket(EntityModel.News news) { Id = news.Id; Title = news.Title; Description = news.Description; Content = news.Content; ImageUrl = news.ImageUrl; DetailsUrl = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "News", "Details", new { id = news.Id, title = news.Title.ToUrlString() }); LastUpdate = news.Updated ?? news.Created; LastUpdatedBy = news.Updated.HasValue ? news.UpdatedBy : news.CreatedBy; RecordOrder = news.RecordOrder; Created = news.Created; CreatedBy = news.CreatedBy; Updated = news.Updated; UpdatedBy = news.UpdatedBy; var newsCategories = news.NewsNewsCategories.Select(nc => nc.NewsCategory).ToList(); Categories = newsCategories.Any() ? newsCategories.Select(c => new CategoryItemModel(c)).ToList() : new List <CategoryItemModel>(); }
public List <ServiceCurlyBracket> GetServices(int count) { return(Fetch(s => s.Status == (int)ServiceEnums.StatusEnums.Active) .OrderBy(m => m.RecordOrder) .Take(count) .ToList().Select(s => new ServiceCurlyBracket { Id = s.Id, Title = s.Title, Description = s.Description, Content = s.Content, ImageUrl = s.ImageUrl, DetailsUrl = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "Services", "Details", new { area = "Admin", id = s.Id }), RecordOrder = s.RecordOrder, Created = s.Created, CreatedBy = s.CreatedBy, Updated = s.Updated, UpdatedBy = s.UpdatedBy }).ToList()); }
public FormWidget(Form form) : this() { var encryptId = PasswordUtilities.ComplexEncrypt(form.Id.ToString(CultureInfo.InvariantCulture)); ScriptUrl = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "SiteApi", "ScriptLoader", new { area = "", f = encryptId }, true); IframeUrl = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "SiteApi", "IframeLoader", new { area = "", f = encryptId }, true); }
public FormLoaderScriptModel(Form form) : base(form) { AllowAjaxSubmit = form.AllowAjaxSubmit; Content = Content.RemoveNewLine(); PostUrl = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "SiteApi", "SubmitForm", new { area = "", f = EncryptId, isAjaxRequest = form.AllowAjaxSubmit }, true); CurrentSiteUrl = "~/".ToAbsoluteUrl(); }
public CategoryItemModel(NewsCategory category) { Id = category.Id; Name = category.Name; Description = category.Description; ParentId = category.ParentId; ParentName = category.ParentId.HasValue ? category.NewsCategory1.Name : string.Empty; Total = category.NewsNewsCategories.Count; DetailsUrl = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "NewsCategory", "Details", new { id = category.Id, title = category.Name.ToUrlString() }); }
/// <summary> /// Get authorize url /// </summary> /// <param name="model"></param> /// <returns></returns> public string GetAuthorizeUrl(SocialMediaToken model) { var callbackUrl = UrlUtilities.GenerateUrl( HttpContext.Current.Request.RequestContext, "SocialMediaTokens", "Callback", new { id = model.Id }, true); var socialMedia = _socialMediaRepository.GetById(model.SocialMediaId); switch (socialMedia.Id.ToEnum <SocialMediaEnums.SocialNetwork>()) { case SocialMediaEnums.SocialNetwork.Facebook: return(SocialUtilities.GetFacebookAuthorizeUrl(model.AppId, callbackUrl, new List <string> { SocialMediaEnums.FacebookPermission.Email.GetEnumName(), SocialMediaEnums.FacebookPermission.PublishActions.GetEnumName(), SocialMediaEnums.FacebookPermission.UserPosts.GetEnumName(), SocialMediaEnums.FacebookPermission.PublicProfile.GetEnumName() })); case SocialMediaEnums.SocialNetwork.Twitter: //Twitter do not need the authorize url return(callbackUrl); case SocialMediaEnums.SocialNetwork.LinkedIn: callbackUrl = UrlUtilities.GenerateUrl( HttpContext.Current.Request.RequestContext, "SocialMediaTokens", "LinkedInCallback", null, true); StateManager.SetSession(EzCMSContants.LinkedInCallbackId, model.Id); return(SocialUtilities.GetLinkedInAuthorizeUrl(model.AppId, callbackUrl)); } return(string.Empty); }
/// <summary> /// On authorizing /// </summary> /// <param name="authorizationContext">the authorize context</param> public override void OnAuthorization(AuthorizationContext authorizationContext) { var localizedResourceServices = HostContainer.GetInstance <ILocalizedResourceServices>(); base.OnAuthorization(authorizationContext); var urlHelper = new UrlHelper(authorizationContext.RequestContext); var url = UrlUtilities.GenerateUrl(authorizationContext.RequestContext, "Account", "Login", new { area = "Admin", returnUrl = authorizationContext.HttpContext.Request.Path }); if (authorizationContext.Result is HttpUnauthorizedResult) { authorizationContext.Controller.TempData["ErrorMessage"] = localizedResourceServices.T("AdminModule:::GroupPermissions:::AccessDenied:::You don't have permission to access this featured. Please log in"); //If its an unauthorized/timed out ajax request go to top window and redirect to logon. if (authorizationContext.HttpContext.Request.IsAjaxRequest()) { authorizationContext.Result = new JavaScriptResult { Script = string.Format("top.location = {0};", url) }; } //If it's a child action, return 404 result else if (authorizationContext.Controller.ControllerContext.IsChildAction) { authorizationContext.Result = new HttpNotFoundResult(); } // Redirect to login page else { authorizationContext.Result = new RedirectResult(url); } } }
public IEnumerable <ValidationResult> Validate(ValidationContext validationContext) { var contactService = HostContainer.GetInstance <IContactService>(); var localizedResourceService = HostContainer.GetInstance <IEzCMSLocalizedResourceService>(); if (!Id.HasValue) { var currentContact = contactService.FetchFirst(c => c.FirstName.Equals(FirstName) && c.LastName.Equals(LastName) && (c.Email.Equals(Email) || c.PhoneHome.Equals(PhoneHome) || c.PhoneWork.Equals(PhoneWork) || c.PreferredPhoneNumber.Equals(PreferredPhoneNumber))); if (currentContact != null) { var url = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "Contacts", "Details", new { id = currentContact.Id }); yield return(new ValidationResult(localizedResourceService.TFormat("Contact_Message_ExistsContactInformation", url), new[] { "Contact" })); } } }
/// <summary> /// Handle link tracker actions /// </summary> /// <param name="id"></param> /// <returns></returns> public ResponseModel TriggerLinkTrackerAction(int id) { var linkTracker = GetById(id); if (linkTracker != null) { var now = DateTime.UtcNow; var userAgentInformation = HttpContext.Current.GetUserAgentInformationFromRequest(); var linkTrackerClick = new LinkTrackerClick { IpAddress = userAgentInformation.IpAddress, Platform = userAgentInformation.Platform, OsVersion = userAgentInformation.OsVersion, BrowserType = userAgentInformation.BrowserType, BrowserName = userAgentInformation.BrowserName, BrowserVersion = userAgentInformation.BrowserVersion, MajorVersion = userAgentInformation.MajorVersion, MinorVersion = userAgentInformation.MinorVersion, IsBeta = userAgentInformation.IsBeta, IsCrawler = userAgentInformation.IsCrawler, IsAOL = userAgentInformation.IsAOL, IsWin16 = userAgentInformation.IsWin16, IsWin32 = userAgentInformation.IsWin32, SupportsFrames = userAgentInformation.SupportsFrames, SupportsTables = userAgentInformation.SupportsTables, SupportsCookies = userAgentInformation.SupportsCookies, SupportsVBScript = userAgentInformation.SupportsVBScript, SupportsJavaScript = userAgentInformation.SupportsJavaScript, SupportsJavaApplets = userAgentInformation.SupportsJavaApplets, SupportsActiveXControls = userAgentInformation.SupportsActiveXControls, JavaScriptVersion = userAgentInformation.JavaScriptVersion, LinkTrackerId = linkTracker.Id }; // Get the url var url = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "LinkTrackers", "Index", new { area = "", id = linkTracker.Id }, true); // Check cookie to prevent multiple count var cookieName = url.ToIdStringByHash(); var linkTrackerCookie = HttpContext.Current.Request.Cookies[cookieName]; if (linkTracker.IsAllowMultipleClick || linkTrackerCookie == null) { // Add new cookie linkTrackerCookie = new HttpCookie(cookieName) { Value = true.ToString(), Expires = now.AddDays(EzCMSContants.LinkTrackerCookieExpireDay) }; HttpContext.Current.Response.Cookies.Add(linkTrackerCookie); _linkTrackerClickService.AddLinkTrackerClick(linkTrackerClick); } // Parse link tracker to url if (linkTracker.PageId.HasValue) { return(new ResponseModel { Success = true, Data = linkTracker.Page.FriendlyUrl.ToPageFriendlyUrl(linkTracker.Page.IsHomePage) }); } return(new ResponseModel { Success = true, Data = linkTracker.RedirectUrl }); } return(new ResponseModel { Success = false, Message = T("LinkTracker_Message_InvalidLinkTracker") }); }
/// <summary> /// Execute the background task /// </summary> /// <param name="context"></param> public void Run(BackgroundTaskExecuteContext context) { var logger = HostContainer.GetInstance <ILogger>(); if (Interlocked.CompareExchange(ref _hasActiveTask, 1, 0) == 0) { var countUsers = 0; try { logger.Info(string.Format("[{0}] Start account expires notification task", EzCMSContants.AccountExpiresNotificationTaskName)); //Update the background task last running time var backgroundTaskService = HostContainer.GetInstance <IEzBackgroundTaskService>(); backgroundTaskService.UpdateLastRunningTimeTask(GetType()); var userService = HostContainer.GetInstance <IUserService>(); var emailLogService = HostContainer.GetInstance <IEmailLogService>(); var emailTemplateService = HostContainer.GetInstance <IEmailTemplateService>(); var nearExpirationDateUsers = userService.GetUsersNearExpirationDate().ToList(); foreach (var user in nearExpirationDateUsers) { if (user.AccountExpiresDate.HasValue) { var authorizeCode = PasswordUtilities.EncryptString(String.Format("{0}{1}{2}", user.Id, FrameworkConstants.UniqueLinkSeparator, user.Email)); var extendExpirationDateLink = UrlUtilities.GenerateUrl(HttpContext.Current.Request.RequestContext, "Account", "ExtendAccountExpiresDate", new { area = "Admin", authorizeCode = authorizeCode }, true); var model = new NotifyAccountExpiredEmailModel { FullName = user.FullName, Username = user.Username, Email = user.Email, ExpirationDate = user.AccountExpiresDate.Value, ExtendExpirationDateLink = extendExpirationDateLink }; var emailResponse = emailTemplateService.ParseEmail(EmailEnums.EmailTemplateType.AccountExpiredNotification, model); var emailLog = new EmailLog { To = user.Email, ToName = user.FullName, From = emailResponse.From, FromName = emailResponse.FromName, CC = emailResponse.CC, Bcc = emailResponse.BCC, Subject = emailResponse.Subject, Body = emailResponse.Body, Priority = EmailEnums.EmailPriority.Medium }; emailLogService.CreateEmail(emailLog, true); countUsers++; } } } catch (Exception exception) { logger.Error(exception); } logger.Info(string.Format("[{0}] End account expires notification task. Notify to {1} account(s) near expiration date", EzCMSContants.AccountExpiresNotificationTaskName, countUsers)); Interlocked.Exchange(ref _hasActiveTask, 0); } }
/// <summary> /// Get social information /// </summary> /// <param name="id"></param> /// <returns></returns> public ResponseModel SaveSocialMediaTokenInformation(int id) { var socialMediaToken = GetById(id); if (socialMediaToken != null) { var model = new SocialMediaResponseModel { Id = socialMediaToken.Id, AppId = socialMediaToken.AppId, AppSecret = socialMediaToken.AppSecret, FullName = socialMediaToken.FullName, Email = socialMediaToken.Email, AccessToken = socialMediaToken.AccessToken, AccessTokenSecret = socialMediaToken.AccessTokenSecret, Verifier = socialMediaToken.Verifier }; var callbackUrl = UrlUtilities.GenerateUrl( HttpContext.Current.Request.RequestContext, "SocialMediaTokens", "Callback", new { id }, true); try { switch (socialMediaToken.SocialMediaId.ToEnum <SocialMediaEnums.SocialNetwork>()) { case SocialMediaEnums.SocialNetwork.Facebook: model = SocialUtilities.GetFacebookAccountInfo(model, callbackUrl); break; case SocialMediaEnums.SocialNetwork.Twitter: model = SocialUtilities.GetTwitterAccountInfo(model); break; case SocialMediaEnums.SocialNetwork.LinkedIn: //Specific callback url for LinkedIn callbackUrl = UrlUtilities.GenerateUrl( HttpContext.Current.Request.RequestContext, "SocialMediaTokens", "LinkedInCallback", null, true); StateManager.SetSession(EzCMSContants.LinkedInCallbackId, id); model = SocialUtilities.GetLinkedInAccountInfo(model, callbackUrl); break; } return(SaveSocialMediaResponse(model)); } catch (Exception exception) { return(new ResponseModel { Success = false, Message = T("SocialMediaToken_Message_InvalidConfigure"), DetailMessage = exception.BuildErrorMessage() }); } } return(new ResponseModel { Success = false }); }
/// <summary> /// Logic for exception handler /// </summary> /// <param name="context"></param> public override void OnException(ExceptionContext context) { if (context.ExceptionHandled) { return; } //Log the error var logger = HostContainer.GetInstance <ILogger>(); var siteSettingService = HostContainer.GetInstance <ISiteSettingService>(); if (context.Exception != null) { var localizedResourceService = HostContainer.GetInstance <IEzCMSLocalizedResourceService>(); var requestType = GetRequestType(context); var exceptionType = context.Exception.GetType(); var errorHandlingSeting = siteSettingService.LoadSetting <ErrorHandlingSetting>(); //Check unauthorized exception if (exceptionType == typeof(EzCMSUnauthorizeException)) { //Clear error response ClearError(context); //Generate login url var unauthorizeUrl = UrlUtilities.GenerateUrl(context.RequestContext, "Account", "Login", new { area = "Admin", returnUrl = context.HttpContext.Request.RawUrl }); var unauthorizedMessage = context.Exception.Message; if (string.IsNullOrEmpty(unauthorizedMessage)) { if (WorkContext.CurrentUser == null) { unauthorizedMessage = localizedResourceService.T("System_Message_AccessDenied"); } else { unauthorizedMessage = localizedResourceService.T("System_Message_AccessDeniedForLoggedInUser"); } } if (requestType == RequestType.ChildRequest) { context.Controller.TempData[FrameworkConstants.EzErrorMessage] = unauthorizedMessage; context.Result = new HttpNotFoundResult(); } else if (requestType == RequestType.AjaxRequest) { context.Result = new JsonResult { Data = new ResponseModel { Success = false, ResponseStatus = ResponseStatusEnums.AccessDenied, Message = string.Format("{0} {1}", unauthorizedMessage, localizedResourceService.T("System_Message_AccessDeniedReturnUrl")), Data = unauthorizeUrl }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } else { context.Controller.TempData[FrameworkConstants.EzErrorMessage] = unauthorizedMessage; context.Result = new RedirectResult(unauthorizeUrl); } } else if (exceptionType == typeof(EzCMSNotFoundException)) { if (requestType == RequestType.AjaxRequest || requestType == RequestType.ChildRequest) { context.Result = new HttpNotFoundResult(); } else { //Clear error response ClearError(context); if (context.HttpContext.Request.Url != null) { var requestUrl = context.HttpContext.Request.Url.LocalPath; // This maybe is local resouce if (string.IsNullOrEmpty(requestUrl.GetExtension())) { var pageNotFoundUrl = errorHandlingSeting.PageNotFoundUrl; if (!pageNotFoundUrl.Equals(requestUrl)) { var exception = (EzCMSNotFoundException)context.Exception; pageNotFoundUrl = pageNotFoundUrl.AddQueryParam("url", exception.Url); /* Remove error logging for 404 * * // Check if 404 error had been logged for this application * var notFoundHandledUrls = EzWorkContext.EzWorkContext.NotFoundHandledUrls; * if (!notFoundHandledUrls.Contains(requestUrl)) * { * // Add 404 error url to handled 404 list in Application * notFoundHandledUrls.Add(requestUrl); * logger.Error(context.Exception); * * EzWorkContext.EzWorkContext.NotFoundHandledUrls = notFoundHandledUrls; * } * */ context.Result = new RedirectResult(pageNotFoundUrl); //Set current page status code to 404 Ez.Framework.Core.Context.EzWorkContext.CurrentControllerContext.Controller.TempData[EzCMSContants.CurrentPageStatusCode] = (int)HttpStatusCode.NotFound; return; } } } context.Result = new HttpNotFoundResult(); } } else { logger.Error(context.Exception); if (requestType == RequestType.AjaxRequest) { //Clear error response ClearError(context); // Generate exception list var exceptionInformation = new List <ExceptionInformation>(); for (var exception = context.Exception; exception != null; exception = exception.InnerException) { exceptionInformation.Add(new ExceptionInformation(exception)); } context.Result = new JsonResult { Data = new ResponseModel { Success = false, ResponseStatus = ResponseStatusEnums.Error, Message = localizedResourceService.T("System_Message_JsonError"), DetailMessage = string.Join("<br />", exceptionInformation.Select(ResponseModel.BuildDetailMessage)) } }; } else { if (context.HttpContext.Request.Url != null) { var requestUrl = context.HttpContext.Request.Url.LocalPath; var enableLiveSite = siteSettingService.GetSetting <bool>(SettingNames.EnableLiveSiteMode); if (enableLiveSite) { var errorUrl = errorHandlingSeting.PageErrorUrl; if (!errorUrl.Equals(requestUrl)) { //Clear error response ClearError(context); context.Result = new RedirectResult(errorUrl); return; } } } base.OnException(context); } } } }