示例#1
0
        public IEnumerable <MigrationExectutionSummary> ExecutePendingMigrations()
        {
            var executedMigrations = _contentMigrationStateService.GetExecutedMigrations().ToList();

            foreach (var provider in _contentMigrationProviders)
            {
                var pendingMigrations = provider.GetAvailableMigrations().Where(m => !executedMigrations.Contains(m)).ToList();

                if (!pendingMigrations.Any())
                {
                    continue;
                }

                var result = provider.ExecuteMigrations(pendingMigrations);

                foreach (var successfulMigration in result.SuccessfulMigrations)
                {
                    _contentMigrationStateService.MarkMigrationAsExecuted(successfulMigration);
                }

                foreach (var failedMigration in result.FailedMigrations)
                {
                    var message = string.Format("Content Migration {0} failed.", failedMigration);

                    _notifier.Add(NotifyType.Error, T(message));
                    Logger.Error(message);
                }

                yield return(result);
            }
        }
示例#2
0
        public string GetShortLink(string myurl)
        {
            if (String.IsNullOrWhiteSpace(myurl))
            {
                return("");
            }
            var shorturl = "";
            var setting  = _orchardServices.WorkContext.CurrentSite.As <Laser.Orchard.ShortLinks.Models.ShortLinksSettingsPart>();

            if (string.IsNullOrEmpty(setting.GoogleApiKey))
            {
                _notifier.Add(NotifyType.Error, T("No Shorturl Setting Found"));
            }
            else
            {
                var apiurl   = string.Format("https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key={0}", setting.GoogleApiKey);
                var request  = (HttpWebRequest)WebRequest.Create(apiurl);
                var postData = string.Format("{{\"dynamicLinkInfo\": {{\"dynamicLinkDomain\": \"{0}\",\"link\": \"{1}\"}},\"suffix\": {{\"option\": \"{2}\"}}}}", setting.DynamicLinkDomain, myurl, setting.HasSensitiveData ? @"UNGUESSABLE" : @"SHORT");
                request.Method      = "POST";
                request.ContentType = "application/json";
                using (var stream = new StreamWriter(request.GetRequestStream())) {
                    stream.Write(postData);
                    stream.Flush();
                    stream.Close();
                }
                var response = (HttpWebResponse)request.GetResponse();
                using (var streamReader = new StreamReader(response.GetResponseStream())) {
                    var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                    var jsondict   = serializer.Deserialize <Dictionary <string, object> >(streamReader.ReadToEnd());
                    shorturl = jsondict["shortLink"].ToString();
                }
            }
            return(shorturl);
        }
        private async Task SyncToPreviewGraph(ContentItem contentItem)
        {
            // sonar can't see that the set value could be used in the event of an exception
            #pragma warning disable S1854
            AllowSyncResult allowSyncResult = AllowSyncResult.Blocked;
            string          message         = $"Unable to sync '{contentItem.DisplayText}' Page to {GraphReplicaSetNames.Preview} graph(s).";

            try
            {
                IMergeGraphSyncer mergeGraphSyncer = _serviceProvider.GetRequiredService <IMergeGraphSyncer>();
                IContentManager   contentManager   = _serviceProvider.GetRequiredService <IContentManager>();
                IAllowSync        allowSync        = await mergeGraphSyncer.SyncToGraphReplicaSetIfAllowed(
                    _graphCluster.GetGraphReplicaSet(GraphReplicaSetNames.Preview), contentItem, contentManager);

                allowSyncResult = allowSync.Result;
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, "Unable to sync '{ContentItemDisplayText}' Page to {GraphReplicaSetName} graph(s).",
                                 contentItem.DisplayText, GraphReplicaSetNames.Preview);
            }

            if (allowSyncResult == AllowSyncResult.Blocked)
            {
                _notifier.Add(NotifyType.Error, new LocalizedHtmlString(nameof(DefaultPageLocationsContentHandler), message));
            }
            #pragma warning restore S1854
        }
        public ActionResult Save(string id)
        {
            if (!CheckPermission(Permissions.ManageSiteSettings))
            {
                return(new HttpUnauthorizedResult());
            }

            var model = settings.Value.FirstOrDefault(x => x.GetType().FullName == id);

            if (model == null)
            {
                return(HttpNotFound());
            }

            TryUpdateModel(model, ControllerContext);

            service.SaveSetting(model);

            notifier.Add(NotifyType.Info, T(Constants.Messages.GenericSaveSuccess));

            //var returnUrl = Request.Form["_ReturnUrl"];
            //if (string.IsNullOrEmpty(returnUrl))
            //{
            //    returnUrl = Url.Action("Index");
            //}

            return(new AjaxResult().Alert(T("Cập nhật thành công.")));
        }
示例#5
0
 public ActionResult RefreshCache()
 {
     _signals.Trigger("WebAdvanced.Sitemap.XmlRefresh");
     _signals.Trigger("WebAdvanced.Sitemap.Refresh");
     _notifier.Add(NotifyType.Information, T("Sitemap cache cleared"));
     return(RedirectToAction("Indexing"));
 }
        public bool IsMissingRequiredParameters(List <Transformalize.Configuration.Parameter> parameters, INotifier notifier)
        {
            var hasRequiredParameters = true;

            foreach (var parameter in parameters.Where(p => p.Required))
            {
                var value = Request.QueryString[parameter.Name];
                if (value != null && value != "*")
                {
                    continue;
                }

                if (parameter.Sticky && parameter.Value != "*")
                {
                    continue;
                }

                notifier.Add(NotifyType.Warning, T("{0} is required. To continue, please choose a {0}.", parameter.Label));
                if (hasRequiredParameters)
                {
                    hasRequiredParameters = false;
                }
            }

            return(!hasRequiredParameters);
        }
示例#7
0
        public ActionResult DeleteProduct(int productId, int campaignId)
        {
            var camp = _campaignService.GetCampaignById(campaignId);

            try
            {
                camp.Products.First(c => c.Id == productId).WhenDeleted = DateTime.UtcNow;
                _campaignService.UpdateCampaign(camp);
                _notifier.Add(NotifyType.Information, T("The product was removed!"));
            }
            catch
            {
                _notifier.Add(NotifyType.Error, T("An error occurred while deleting"));
            }

            return(RedirectToAction("ChangeInformation", new { id = campaignId }));
        }
示例#8
0
        private bool SendEmail(dynamic contentModel, int templateId, IEnumerable <string> sendTo, IEnumerable <string> cc, IEnumerable <string> bcc, bool NotifyReadEmail, string fromEmail = null, string replyTo = null, IEnumerable <string> attachments = null, bool queued = false, int priority = 0)
        {
            var template = _templateServices.GetTemplate(templateId);

            var body = _templateServices.RitornaParsingTemplate(contentModel, template.Id);

            if (body.StartsWith("Error On Template"))
            {
                _notifier.Add(NotifyType.Error, T("Error on template, mail not sent"));
                return(false);
            }
            var data      = new Dictionary <string, object>();
            var smtp      = _orchardServices.WorkContext.CurrentSite.As <SmtpSettingsPart>();
            var recipient = sendTo != null ? sendTo : new List <string> {
                smtp.Address
            };

            data.Add("Subject", template.Subject);
            data.Add("Body", body);
            data.Add("Recipients", String.Join(",", recipient));
            if (cc != null)
            {
                data.Add("CC", String.Join(",", cc));
            }
            if (bcc != null)
            {
                data.Add("Bcc", String.Join(",", bcc));
            }
            if (fromEmail != null)
            {
                data.Add("FromEmail", fromEmail);
            }
            if (replyTo != null)
            {
                data.Add("ReplyTo", replyTo);
            }
            data.Add("NotifyReadEmail", NotifyReadEmail);
            if (attachments != null)
            {
                if (attachments.Count() > 0)
                {
                    data.Add("Attachments", attachments);
                }
            }


            if (!queued)
            {
                _messageService.Send(SmtpMessageChannel.MessageType, data);
            }
            else
            {
                _jobsQueueService.Enqueue("IMessageService.Send", new { type = SmtpMessageChannel.MessageType, parameters = data }, priority);
            }

            return(true);
        }
示例#9
0
        protected override DriverResult Editor(FacebookConnectWidgetPart part, dynamic shapeHelper)
        {
            if (!_facebookSuiteService.AppSettingsSet)
            {
                _notifier.Add(NotifyType.Error, T("Currently the Facebook app settings are not set, therefore Facebook Connect won't work properly. Please set the app settings first on the page Facebook Suite Settings under Settings."));
            }

            return(null);
        }
        public void Synchronize()
        {
            if (_communicationService != null)
            {
                CommunicationContactPart master = _communicationService.EnsureMasterContact();
                _transactionManager.RequireNew();

                // assegna un contact a ogni device
                int idmaster            = master.Id;
                var notificationrecords = _pushNotificationRepository.Fetch(x => x.Produzione && x.Validated).ToList();
                foreach (PushNotificationRecord rec in notificationrecords)
                {
                    rec.MobileContactPartRecord_Id = EnsureContactId(rec.UUIdentifier, idmaster);
                    _pushNotificationRepository.Update(rec);
                    _transactionManager.RequireNew();
                }
                _pushNotificationRepository.Flush();
                _notifier.Add(NotifyType.Information, T("Linked {0} device To Master contact", notificationrecords.Count().ToString()));
                string message = string.Format("Linked {0} device To Master contact", notificationrecords.Count().ToString());
                Logger.Log(OrchardLogging.LogLevel.Information, null, message, null);

                _transactionManager.RequireNew();

                // elimina gli userDevice riferiti a utenti inesistenti (perché cancellati)
                UserPart user = null;
                List <UserDeviceRecord> elencoUdr = _userDeviceRecord.Fetch(x => x.UserPartRecord.Id > 0).ToList();
                foreach (UserDeviceRecord udr in elencoUdr)
                {
                    user = _orchardServices.ContentManager.Get <UserPart>(udr.UserPartRecord.Id);
                    if (user == null)
                    {
                        _userDeviceRecord.Delete(udr);
                        _transactionManager.RequireNew();
                    }
                }
                _userDeviceRecord.Flush();
                _transactionManager.RequireNew();

                // elimina gli userDevice duplicati (con lo stesso UUIdentifier) e tiene il più recente (in base all'Id del record)
                string uuidPrecedente = "";
                elencoUdr = _userDeviceRecord.Fetch(x => x.UUIdentifier != null).OrderBy(y => y.UUIdentifier).OrderByDescending(z => z.Id).ToList();
                foreach (UserDeviceRecord udr in elencoUdr)
                {
                    if (udr.UUIdentifier == uuidPrecedente)
                    {
                        _userDeviceRecord.Delete(udr);
                        _transactionManager.RequireNew();
                    }
                    else
                    {
                        uuidPrecedente = udr.UUIdentifier;
                    }
                }
                _userDeviceRecord.Flush();
                _transactionManager.RequireNew();
            }
        }
        public ActionResult Edit(EditOrderVM model)
        {
            var order = _orderService.GetOrder(model.Id);

            if (!ModelState.IsValid)
            {
                return(BuildModel(order, model));
            }
            _orderService.UpdateOrderStatus(order, model.Status);
            _notifier.Add(NotifyType.Information, T("The order has been saved"));
            return(RedirectToAction("ListOrders", "CustomerAdmin", new { id = order.CustomerId }));
        }
        public async Task <LoginResponse> Login(LoginRequest userLogin)
        {
            var users = await _userService.GetByAsync(x => x.Email == userLogin.Email);

            if (!users.Any())
            {
                _notifier.Add("Usuário não encontrado");
                return(null);
            }

            var user = users.FirstOrDefault();

            if (user.Password == SecurityUtils.EncryptPassword(userLogin.Password))
            {
                LoginResponse userToken = _mapper.Map <LoginResponse>(user);
                userToken.Token = GenerateToken(user);
                return(userToken);
            }
            _notifier.Add("Senha Incorreta");
            return(null);
        }
        public virtual async Task <int> DeleteAsync(Guid id)
        {
            TEntity entity = await GetByIdAsync(id);

            if (entity != null)
            {
                _context.Set <TEntity>().Remove(entity);
                return(await _context.SaveChangesAsync());
            }
            _notifier.Add("Registro não encontrado");
            return(-1);
        }
示例#14
0
        public override IEnumerable <LocalizedString> Execute(WorkflowContext workflowContext, ActivityContext activityContext)
        {
            var notification = activityContext.GetState <string>("Notification");
            var message      = activityContext.GetState <string>("Message");

            NotifyType notificationType;

            Enum.TryParse(notification, true, out notificationType);
            _notifier.Add(notificationType, T(message));

            yield return(T("Done"));
        }
示例#15
0
        public ActionResult EditPOST(int id)
        {
            if (!_orchardServices.Authorizer.Authorize(TestPermission))
            {
                return(new HttpUnauthorizedResult());
            }

            ContentItem content;

            if (id == 0)
            {
                var newContent = _orchardServices.ContentManager.New(contentType);
                _orchardServices.ContentManager.Create(newContent, VersionOptions.Draft);
                content = newContent;
            }
            else
            {
                content = _orchardServices.ContentManager.Get(id, VersionOptions.DraftRequired);
            }
            var model = _orchardServices.ContentManager.UpdateEditor(content, this);

            if (!ModelState.IsValid)
            {
                foreach (string key in ModelState.Keys)
                {
                    if (ModelState[key].Errors.Count > 0)
                    {
                        foreach (var error in ModelState[key].Errors)
                        {
                            _notifier.Add(NotifyType.Error, T(error.ErrorMessage));
                        }
                    }
                }
                _orchardServices.TransactionManager.Cancel();
                return(View(model));
            }
            _contentManager.Publish(content);
            _notifier.Add(NotifyType.Information, T("Twitter Account Added"));
            return(RedirectToAction("Edit", new { id = content.Id }));
        }
        public ActionResult EditPOST(int id)
        {
            var customer = _customerService.GetCustomer(id);
            var model    = _contentManager.UpdateEditor(customer, this);

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            _notifier.Add(NotifyType.Information, T("Your customer has been saved"));
            return(RedirectToAction("Edit", new { id }));
        }
        public ActionResult EditPOST(int id)
        {
            if (!_orchardServices.Authorizer.Authorize(TestPermission))
            {
                return(new HttpUnauthorizedResult());
            }

            ContentItem content;

            if (id == 0)
            {
                var newContent = _orchardServices.ContentManager.New(contentType);
                _orchardServices.ContentManager.Create(newContent);
                content = newContent;
            }
            else
            {
                content = _orchardServices.ContentManager.Get(id);
            }
            var model = _orchardServices.ContentManager.UpdateEditor(content, this);

            if (!ModelState.IsValid)
            {
                foreach (string key in ModelState.Keys)
                {
                    if (ModelState[key].Errors.Count > 0)
                    {
                        foreach (var error in ModelState[key].Errors)
                        {
                            _notifier.Add(NotifyType.Error, T(error.ErrorMessage));
                        }
                    }
                }
                _orchardServices.TransactionManager.Cancel();
                return(View(model));
            }
            _notifier.Add(NotifyType.Information, T("Query saved"));
            return(RedirectToAction("Index", "MyQueryAdmin"));
        }
示例#18
0
        public ActionResult EditPOST(int id)
        {
            var address = _customerService.GetAddress(id);
            var model   = _contentManager.UpdateEditor(address, this);

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            _notifier.Add(NotifyType.Information, T("Your address has been saved"));
            return(RedirectToAction("ListAddresses", "CustomerAdmin", new { id = address.CustomerId }));
        }
示例#19
0
        public ActionResult Edit(CacheUrlRecord record)
        {
            var save   = (_orchardServices.WorkContext.HttpContext.Request.Form["btnSave"] == "Save");
            var delete = (_orchardServices.WorkContext.HttpContext.Request.Form["btnDelete"] == "Delete");

            if (record.Id == 0)
            {
                if (save)
                {
                    record.CacheURL   = record.CacheURL?.ToLower();
                    record.CacheToken = record.CacheToken?.Replace("}{", "}||{");
                    _cacheUrlRepository.Create(record);
                    _notifier.Add(NotifyType.Information, T("Cache Url added: {0}", record.CacheURL));
                }
            }
            else
            {
                if (delete)
                {
                    var oldUrl = record.CacheURL;
                    _cacheUrlRepository.Delete(_cacheUrlRepository.Get(r => r.Id == record.Id));
                    _notifier.Add(NotifyType.Information, T("Cache Url removed: {0}", oldUrl));
                }
                else
                {
                    if (save)
                    {
                        record.CacheURL   = record.CacheURL?.ToLower();
                        record.CacheToken = record.CacheToken?.Replace("}{", "}||{");
                        _cacheUrlRepository.Update(record);
                        _notifier.Add(NotifyType.Information, T("Cache Url updated: {0}", record.CacheURL));
                    }
                }
            }
            _cacheUrlRepository.Flush();
            _cacheAliasServices.RefreshCachedRouteConfig();
            return(RedirectToAction("Index"));
        }
        protected override void Updated(UpdateContentContext context)
        {
            var part = context.ContentItem.As <ConfigurationPart>();

            if (part == null)
            {
                return;
            }
            try {
                //test if configuration works
                var root = new TflRoot(
                    part.Configuration,
                    null,
                    new CfgNetNotifier(_notifier)
                    );
                CheckAddress(part.StartAddress);
                CheckAddress(part.EndAddress);
                Logger.Information("Loaded {0} with {1} warnings, and {2} errors.", part.Title(), root.Warnings().Length, root.Errors().Length);
            } catch (Exception ex) {
                _notifier.Add(NotifyType.Warning, T(ex.Message));
                Logger.Warning(ex.Message);
            }
        }
        private void ImportLocalizedTerms(PublishContentContext context, TaxonomyPart part)
        {
            // When saving a Taxonomy translation I automatically move to the taxonomy any term in the corresponding language associated to the other translations
            bool termsMoved = false;

            if (context.ContentItem.Has <LocalizationPart>())
            {
                var taxonomyCulture = context.ContentItem.As <LocalizationPart>().Culture;
                if (taxonomyCulture != null)
                {
                    var taxonomyIds = _localizationService.GetLocalizations(context.ContentItem).Select(x => x.Id);

                    foreach (var taxonomyId in taxonomyIds)
                    {
                        var parentTaxonomyCulture = _taxonomyService.GetTaxonomy(taxonomyId).As <LocalizationPart>().Culture;
                        var termIds = _taxonomyService.GetTerms(taxonomyId).Select(x => x.Id);

                        foreach (var termId in termIds)
                        {
                            var term       = _taxonomyService.GetTerm(termId);
                            var parentTerm = _taxonomyExtensionsService.GetParentTerm(term);
                            if (term.Has <LocalizationPart>())
                            {
                                var termCulture = term.As <LocalizationPart>().Culture;

                                if (termCulture != null && termCulture != parentTaxonomyCulture && termCulture == taxonomyCulture)
                                {
                                    term.TaxonomyId = context.ContentItem.Id;
                                    term.Path       = parentTerm != null?parentTerm.As <TermPart>().FullPath + "/" : "/";

                                    if (parentTerm == null)
                                    {
                                        term.Container = context.ContentItem;
                                    }

                                    _taxonomyExtensionsService.RegenerateAutoroute(term.ContentItem);

                                    termsMoved = true;
                                }
                            }
                        }
                    }
                }
            }

            if (termsMoved)
            {
                _notifier.Add(NotifyType.Information, T("Terms in the chosen language have been automatically moved from the other translations."));
            }
        }
        private void ControlDatePublishLater(CommunicationAdvertisingPart communicationAdvertisingPart, ContentItem campaign)
        {
            DateTime?datepublish = _publishLaterService.GetScheduledPublishUtc(communicationAdvertisingPart.ContentItem.As <PublishLaterPart>());

            if (communicationAdvertisingPart.CampaignId > 0 && datepublish != null && campaign != null)
            {
                DateTime datelimitcampaign = (DateTime)(((dynamic)campaign).CommunicationCampaignPart.ToDate.DateTime);
                if (datepublish > datelimitcampaign && datelimitcampaign != DateTime.MinValue)
                {
                    _notifier.Add(NotifyType.Error, T("Cannot Update! publish later date is after Campaign date"));
                    _transactions.Cancel();
                }
            }
        }
示例#23
0
        public static void Error(this INotifier notifier, Exception exception, bool durable = true)
        {
            if (exception == null)
            {
                return;
            }

            while (exception.InnerException != null)
            {
                exception = exception.InnerException;
            }

            notifier.Add(NotifyType.Error, exception.Message, durable);
        }
示例#24
0
        public CommunicationContactPart EnsureMasterContact()
        {
            CommunicationContactPart master             = null;
            List <ContentItem>       mastersToBeDeleted = new List <ContentItem>();
            // cerca tutti i master contact attivi presenti nel sistema e sceglie il più recente
            var activeMasters = _orchardServices.ContentManager.Query <CommunicationContactPart, CommunicationContactPartRecord>().Where(y => y.Master).OrderByDescending(y => y.Id).List();

            foreach (var contact in activeMasters)
            {
                if (master == null)
                {
                    master = contact;
                }
                else
                {
                    mastersToBeDeleted.Add(contact.ContentItem);
                }
            }

            // se non c'è nessun master contact lo crea
            if (master == null)
            {
                var Contact = _orchardServices.ContentManager.Create("CommunicationContact");
                Contact.As <TitlePart>().Title = "Master Contact";
                Contact.As <CommunicationContactPart>().Master = true;
                master = Contact.As <CommunicationContactPart>();
                _notifier.Add(NotifyType.Information, T("Master Contact Created"));
            }

            // elimina i master contact in eccesso
            foreach (var contact in mastersToBeDeleted)
            {
                _orchardServices.ContentManager.Remove(contact);
            }
            return(master);
        }
        public bool UnsetPublishedVersion(int id, int versionId)
        {
            ContentItem contentItem = _contentManager.Get(id, VersionOptions.VersionRecord(versionId));

            if (contentItem == null)
            {
                _notifier.Error(T("Could not find version id {0} of content with id {0}", versionId, id));
                return(false);
            }

            _contentManager.Unpublish(contentItem);
            _notifier.Add(NotifyType.Information, T("Version {0} of content item un-published.", contentItem.Version));

            return(true);
        }
 //POST
 protected override DriverResult Editor(GoogleAnalyticsSettingsPart part, IUpdateModel updater, dynamic shapeHelper)
 {
     if (updater.TryUpdateModel(part, Prefix, null, null))
     {
         if (string.IsNullOrWhiteSpace(part.GoogleAnalyticsKey) && (part.TrackOnFrontEnd || part.TrackOnAdmin))
         {
             updater.AddModelError("TrackingKeyMissing", T("If Google Analytics is enabled for the front end or the back end, the tracking key is required."));
         }
     }
     else
     {
         _notifier.Add(NotifyType.Error, T("Error on updating Google Analytics settings"));
     }
     return(Editor(part, shapeHelper));
 }
示例#27
0
        protected override DriverResult Editor(MediaPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            return(ContentShape(
                       "Parts_Media_Edit_FileName",
                       () => {
                var currentUser = _authenticationService.GetAuthenticatedUser();
                if (!_authorizationService.TryCheckAccess(Permissions.ManageMediaContent, currentUser, part))
                {
                    return null;
                }

                var settings = part.TypeDefinition.Settings.GetModel <MediaFileNameEditorSettings>();
                if (!settings.ShowFileNameEditor)
                {
                    return null;
                }

                MediaFileNameEditorViewModel model = shapeHelper.Parts_Media_Edit_FileName(typeof(MediaFileNameEditorViewModel));

                if (part.FileName != null)
                {
                    model.FileName = part.FileName;
                }

                if (updater != null)
                {
                    var priorFileName = model.FileName;
                    if (updater.TryUpdateModel(model, Prefix, null, null))
                    {
                        if (model.FileName != null && !model.FileName.Equals(priorFileName, StringComparison.OrdinalIgnoreCase))
                        {
                            try {
                                _mediaLibraryService.RenameFile(part.FolderPath, priorFileName, model.FileName);
                                part.FileName = model.FileName;

                                _notifier.Add(NotifyType.Success, T("File '{0}' was renamed to '{1}'", priorFileName, model.FileName));
                            }
                            catch (Exception) {
                                updater.AddModelError("MediaFileNameEditorSettings.FileName", T("Unable to rename file"));
                            }
                        }
                    }
                }

                return model;
            }));
        }
示例#28
0
        public ButtonToWorkflowsPartHandler(IWorkflowManager workflowManager, INotifier notifier, IScheduledTaskManager scheduledTaskManager)
        {
            _workflowManager      = workflowManager;
            _notifier             = notifier;
            _scheduledTaskManager = scheduledTaskManager;
            T = NullLocalizer.Instance;

            OnUpdated <ButtonToWorkflowsPart>((context, part) => {
                if (!string.IsNullOrEmpty(part.ActionToExecute))
                {
                    var content = context.ContentItem;
                    if (part.ActionAsync)
                    {
                        //  part.ButtonsDenied = true;
                        _scheduledTaskManager.CreateTask("Laser.Orchard.ButtonToWorkflows.Task", DateTime.UtcNow.AddMinutes(1), part.ContentItem);
                    }
                    else
                    {
                        _workflowManager.TriggerEvent(part.ActionToExecute, content, () => new Dictionary <string, object> {
                            { "Content", content }
                        });
                        part.MessageToWrite  = "";
                        part.ActionToExecute = "";
                        part.ActionAsync     = false;
                    }
                    try {
                        if (!string.IsNullOrEmpty(part.MessageToWrite))
                        {
                            _notifier.Add(NotifyType.Information, T(part.MessageToWrite));
                        }
                    }
                    catch { }
                }

                //  if (context.ContentItem.As<CommonPart>() != null) {
                //    var currentUser = _orchardServices.WorkContext.CurrentUser;
                //if (currentUser != null) {
                //    ((dynamic)context.ContentItem.As<CommonPart>()).LastModifier.Value = currentUser.Id;
                //    if (((dynamic)context.ContentItem.As<CommonPart>()).Creator.Value == null)
                //        //  ((NumericField) CommonPart.Fields.Where(x=>x.Name=="Creator").FirstOrDefault()).Value = currentUser.Id;
                //        ((dynamic)context.ContentItem.As<CommonPart>()).Creator.Value = currentUser.Id;
                //}
                //   }
            });
        }
示例#29
0
        public async Task <IActionResult> Compare(string contentItemId, CompareContentVersionRecordsOptions options)
        {
            if (options == null)
            {
                options = new CompareContentVersionRecordsOptions();
            }
            ContentItem versionA = null;
            ContentItem versionB = null;

            if (!string.IsNullOrWhiteSpace(options.VersionARecordId) && !string.IsNullOrWhiteSpace(options.VersionBRecordId))
            {
                versionA = await _contentManager.GetVersionAsync(options.VersionARecordId);

                versionB = await _contentManager.GetVersionAsync(options.VersionBRecordId);
            }
            else
            {
                //notifier must supply both versions A and B
                _notifier.Add(NotifyType.Warning, T["Must supply values for Version A and Version B  to compare."]);
            }


            var versionRecords = await _session.Query <ContentItem, ContentItemIndex>().Where(s => s.ContentItemId == contentItemId).ListAsync();

            var model = new CompareContentVersionRecordsViewModel
            {
                ContentItemId         = contentItemId,
                VersionA              = versionA,
                VersionB              = versionB,
                VersionARecordId      = options.VersionARecordId,
                VersionBRecordId      = options.VersionBRecordId,
                ContentVersionRecords = versionRecords
            };

            // var result = await _session.Query<ContentItem, ContentItemIndex>().Where(s => s.ContentItemId == contentItemId).ListAsync();

            //List<ContentItem> query = _contentManager.ge Services.ContentManager.GetAllVersions(id).ToList();
            //if (!query.Any())
            //{
            //    return HttpNotFound();
            //}

            return(View(model));
        }
        public ActionResult Detail(int idQuestionario, string from = null, string to = null, bool export = false)
        {
            DateTime    fromDate, toDate;
            CultureInfo provider = CultureInfo.GetCultureInfo(_orchardServices.WorkContext.CurrentCulture);

            DateTime.TryParse(from, provider, DateTimeStyles.None, out fromDate);
            DateTime.TryParse(to, provider, DateTimeStyles.None, out toDate);
            var model = _questionnairesServices.GetStats(idQuestionario, (DateTime?)fromDate, (DateTime?)toDate);

            if (export == true)
            {
                ContentItem filters = _orchardServices.ContentManager.Create("QuestionnaireStatsExport");
                filters.As <TitlePart>().Title = string.Format("id={0}&from={1:yyyyMMdd}&to={2:yyyyMMdd}", idQuestionario, fromDate, toDate);
                _orchardServices.ContentManager.Publish(filters);
                _taskManager.CreateTask(StasExportScheduledTaskHandler.TaskType, DateTime.UtcNow.AddSeconds(-1), filters);
                //_questionnairesServices.SaveQuestionnaireUsersAnswers(idQuestionario, fromDate, toDate);
                _notifier.Add(NotifyType.Information, T("Export started. Please check 'Show Exported Files' in a few minutes to get the result."));
            }
            return(View((object)model));
        }