Example #1
0
       public void ReloadFlies()
        {
            try
            {
                listcomm = new List<CommandItem>();
                String[] strfilelist = System.IO.Directory.GetFiles(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "command");
                foreach (string file in strfilelist)
                {
                    Assembly ab = Assembly.LoadFile(file);
                    Type[] types = ab.GetExportedTypes();
                    foreach (Type t in types)
                    {

                        if (t.IsSubclassOf(typeof(TCPCommand)))
                        {
                            CommandItem ci = new CommandItem();
                            object obj = ab.CreateInstance(t.FullName);
                            TCPCommand Ic = obj as TCPCommand;
                            ci.MyICommand = Ic;
                            ci.CommName = Ic.Getcommand();
                            Ic.SetGlobalQueueTable(qt);
                            GetAttributeInfo( Ic,obj.GetType(), obj);
                            listcomm.Add(ci);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (EventMylog != null)
                    EventMylog("加载异常", ex.Message);
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="items"></param>
        /// <param name="command"></param>
        /// <param name="schedule"></param>
        public void SetXmLsitemap(Item[] items, CommandItem command, ScheduleItem schedule)
        {
            if (ConfigurationHelper.IsAuthoringServer())
            {
                try
                {
                    XmlDocument xmlDoc = new XmlDocument();
                    XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", null);

                    XmlElement rootNode = xmlDoc.CreateElement("urlset");
                    rootNode.SetAttribute("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
                    xmlDoc.InsertBefore(xmlDeclaration, xmlDoc.DocumentElement);
                    xmlDoc.AppendChild(rootNode);

                    //we will take only approved items / pages
                    string databaseName = "web";
                    string startItemPath = ConfigurationHelper.GetSitecoreSetting("rootPath");
                    Database database = Factory.GetDatabase(databaseName);
                    UrlOptions urlOptions = UrlOptions.DefaultOptions;
                    urlOptions.AlwaysIncludeServerUrl = false;

                    Item item = database.GetItem(startItemPath);
                    AddUrlEntry(item, xmlDoc, rootNode, urlOptions);
                    xmlDoc.Save(System.Web.Hosting.HostingEnvironment.MapPath("/sitemap.xml"));
                }
                catch (Exception ex)
                {
                    Log.Error("Error at sitemap xml handler.", ex, this);
                }
            }
        }
Example #3
0
		public override bool Merge(CommandItem newitem) {
			ElementAddOrRem newitemx = newitem as ElementAddOrRem;
			if (newitemx == null ||
					newitemx._editingMode != _editingMode ||
					newitemx._editingOperationCount != _editingOperationCount) {
				return false;
			}

			// We only implement merging for repeated point-erase operations.
			if (_editingMode != InkCanvasEditingMode.EraseByPoint)
				return false;
			if (newitemx._editingMode != InkCanvasEditingMode.EraseByPoint)
				return false;

			// Note: possible for point-erase to have hit intersection of >1 strokes!
			// For each newly hit stroke, merge results into this command item.
			foreach (UIElement doomed in newitemx._removed)
				if (_added.Contains(doomed))
					_added.Remove(doomed);
				else
					_removed.Add(doomed);
			for (int i = 0; i < newitemx._added.Count; i++)
				_added.Add(newitemx._added[i]);
			return true;
		}
Example #4
0
 private void InsertedCommand_Callback(CommandItem item)
 {
     if (item.Reader.Read())
         ID.SafeValue = (int)item.Reader["idsign"];
     else
         item.SQLiteException = new Exception("Could not get id for inserted sign.", item.SQLiteException);
 }
Example #5
0
        private static KeyGesture GetKeyGesture(CommandItem item)
        {
            var inputGestures = item?.InputGestures;
            if (inputGestures != null && inputGestures.Count != 0)
                return inputGestures[0] as KeyGesture;

            return null;
        }
 public void EmailReports(Item[] itemarray, CommandItem commandItem, ScheduleItem scheduleItem)
 {
     //MultilistField mf = commandItem.InnerItem.Fields["reports"];
     //if (mf != null)
     //{
     //    foreach (Item item in mf.GetItems())
     //    {
     //        runReport(item);
     //    }
     //}
 }
Example #7
0
        public virtual void UnlockIdleUserItems(Item[] items, CommandItem command, ScheduleItem schedule)
        {
            if (ElapsedTimeWhenIdle == TimeSpan.Zero)
            {
                return;
            }

            IEnumerable<Item> lockedItems = GetLockedItems(schedule.Database);
            foreach (Item lockedItem in lockedItems)
            {
                UnlockIfApplicable(lockedItem);
            }
        }
        /// <summary>
        /// This function tells Vault Explorer what custom commands this extension provides.
        /// Part of the IExtension interface.
        /// </summary>
        /// <returns>A collection of CommandSites, which are collections of custom commands.</returns>
        public IEnumerable <CommandSite> CommandSites()
        {
            // Create the DirectView command object.
            CommandItem VaultViewCmdItem = new CommandItem("VaultViewCommand", "D&irect View...")
            {
                // this command is active when a File is selected
                NavigationTypes = new SelectionTypeId[] { SelectionTypeId.File, SelectionTypeId.FileVersion },

                // this command is not active if there are multiple entities selected
                MultiSelectEnabled = false
            };

            // create the selectViewerApp command
            CommandItem SelectViewerAppCmdItem = new CommandItem("SelectViewerAppCommand", "Select DirectView Viewer App...")
            {
                // not sure what options should go in here...
            };


            // The VaultViewCommandHandler function is called when the custom command is executed.
            VaultViewCmdItem.Execute       += HelloWorldCommandHandler;
            SelectViewerAppCmdItem.Execute += SelectViewerAppCommandHandler;


            // Create a command site to hook the DirectView command to the right-click menu for Files.
            CommandSite fileContextCmdSite = new CommandSite("VaultViewCommand.FileContextMenu", "Vault View Menu")
            {
                Location             = CommandSiteLocation.FileContextMenu,
                DeployAsPulldownMenu = false
            };

            fileContextCmdSite.AddCommand(VaultViewCmdItem);

            CommandSite toolsCommandMenuSite = new CommandSite("SelectViewerAppCommand", "Select DirectView Viewer App...")
            {
                Location             = CommandSiteLocation.ToolsMenu,
                DeployAsPulldownMenu = false
            };

            toolsCommandMenuSite.AddCommand(SelectViewerAppCmdItem);


            // Gather the sites in a List.
            List <CommandSite> sites = new List <CommandSite>();

            sites.Add(fileContextCmdSite);
            sites.Add(toolsCommandMenuSite);

            // Return the list of CommandSites.
            return(sites);
        }
Example #9
0
 public void Update(Item[] items, CommandItem command, ScheduleItem schedule)
 {
     using (var session = new ScriptSession(ApplicationNames.Default))
     {
         foreach (Item item in items)
         {
             string script = item["Script"];
             if (!String.IsNullOrEmpty(script))
             {
                 session.ExecuteScriptPart(script);
             }
         }
     }
 }
Example #10
0
            public override bool Equals(object obj)
            {
                CommandItem other = obj as CommandItem;

                if (other == null)
                {
                    return(false);
                }
                if (Mode == null || other.Mode == null)
                {
                    return(Mode == other.Mode);
                }
                return(other.Mode.Id == Mode.Id);
            }
Example #11
0
        private T GetItem <T>(CommandItem item)
            where T : Enum
        {
            SdcpRequest request = new SdcpRequest("SONY", RequestType.Get)
            {
                Item = item,
            };
            SdcpResponse response = SendRequest(request);

            if (response.Result == SdcpResult.OK)
            {
                return((T)(object)response.DataValue);
            }

            return(default);
Example #12
0
        public DependenciesViewModel(bool IsReload, CommandItem commandItem)
        {
            if (IsReload)
            {
                ApiSrv = new Services.ApiService(ApiConsult.ApiMenuB);

                this.CommandItem                = commandItem;
                this.ListViewTitleLot           = string.Format("Lotes de los que depende ({0})", commandItem.NameLot.Split('-')[0].Trim());
                this.ListViewTitleLotDetail     = string.Format("Lotes que dependen de éste ({0})", commandItem.NameLot.Split('-')[0].Trim());
                this.ListViewTitleCommand       = string.Format("Lotes-Comandos de los que depende ({0}-{1})", commandItem.NameLot.Split('-')[0].Trim(), commandItem.NameCommand.Split('-')[0].Trim());
                this.ListViewTitleCommandDetail = string.Format("Lotes-Comandos que dependen de éste ({0}-{1})", commandItem.NameLot.Split('-')[0].Trim(), commandItem.NameCommand.Split('-')[0].Trim());

                GetInitialData();
            }
        }
Example #13
0
 public CommandMenuItem(SmartBar bar, CommandItem item)
 {
     SmartBar    = bar;
     CommandItem = item;
     Icon        = ThemeHelper.GetImage(item.ImageId);
     Header      = new TextBlock {
         Text = item.Name
     };
     item.ItemInitializer?.Invoke(this);
     // the action is installed only when called by this method
     if (item.Action != null)
     {
         Click += ClickHandler;
     }
 }
Example #14
0
        public void RunImport(Item[] itemArray, CommandItem commandItem, ScheduleItem scheduledItem)
        {
            var importItem          = itemArray[0];
            var currentDB           = Context.ContentDatabase;
            var connectionStringKey = importItem.Fields["Default Connection String"] != null
                ? importItem.Fields["Default Connection String"].Value
                : "EPrise";
            var connectionString = ConfigurationManager.ConnectionStrings[connectionStringKey].ToString();

            //new import
            TextField hc = importItem.Fields["Handler Class"];
            TextField ha = importItem.Fields["Handler Assembly"];

            if (ha != null && !string.IsNullOrEmpty(ha.Value))
            {
                if (hc != null && !string.IsNullOrEmpty(hc.Value))
                {
                    BaseDataMap map = null;
                    try
                    {
                        map =
                            (BaseDataMap)
                            ReflectionUtil.CreateObject(ha.Value, hc.Value,
                                                        new object[] { currentDB, connectionString, importItem, scheduledItem.LastRun.ToString() });
                    }
                    catch (FileNotFoundException fnfe)
                    {
                        Log.Info("DataImportTaskError", "the binary specified could not be found");
                    }
                    if (map != null)
                    {
                        Log.Info(map.Process(), "DataImportTask");
                    }
                    else
                    {
                        Log.Info("DataImportTaskError", "the data map provided could not be instantiated");
                    }
                }
                else
                {
                    Log.Info("DataImportTaskError", "import handler class is not defined");
                }
            }
            else
            {
                Log.Info("DataImportTaskError", "import handler assembly is not defined");
            }
        }
Example #15
0
 public void Update(Item[] items, CommandItem command, ScheduleItem schedule)
 {
     using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
     {
         foreach (var item in items)
         {
             var script = item[ScriptItemFieldNames.Script];
             if (!String.IsNullOrEmpty(script))
             {
                 session.SetExecutedScript(item);
                 session.SetItemLocationContext(item);
                 session.ExecuteScriptPart(script);
             }
         }
     }
 }
Example #16
0
 public void Update(Item[] items, CommandItem command, ScheduleItem schedule)
 {
     using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
     {
         foreach (var item in items)
         {
             var script = item[ScriptItemFieldNames.Script];
             if (!String.IsNullOrEmpty(script))
             {
                 session.SetExecutedScript(item);
                 session.SetItemLocationContext(item);
                 session.ExecuteScriptPart(script);
             }
         }
     }
 }
Example #17
0
        public void Run(Item[] itemArray, CommandItem commandItem, ScheduleItem scheduledItem)
        {
            Log.Info("Running Scheduled Publishing Task", this);

            var options = InitialiseSchedulingOptions(itemArray[0]);

            if (!IsValidOptions(options))
            {
                return;
            }

            var now = DateTime.Now;

            RunPublishingInterval(now, options);
            RunPublishingSchedule(now, options);
        }
    private CommandItem AddCommand(CommandManager.CommandInfo cmd)
    {
        CommandItem ci = Instantiate(_cmdItemTemplate, _container);

        if (ci)
        {
            ci.name = $"{cmd.Order}_{cmd.Name}";
            ci.Init(cmd.CmdId, cmd.Name, cmd.Func, ci.gameObject);
            return(ci);
        }
        else
        {
            Debug.LogError("PanelCommands AddCommand Error - Cannot find Command Item Template Object!!!");
        }
        return(null);
    }
Example #19
0
        public void Initialize()
        {
            Shell.RegisterDocumentCreator<MainWindowViewModel>(() =>
            {
                var providers = IOC.Current.GetService<IEnumerable<IImitateProvider>>();
                var doc = new MainWindowViewModel(Shell, providers) { ContentId = "imitater", Title = "模拟输入" };
                return doc;
            });

            var imitaterMenu = new CommandItem("imitater", "模拟", 5);
            imitaterMenu.Items.Add(new CommandItem("imitaterSetting", "模拟录入", 0, p =>
                {
                    Shell.OpenDocument(typeof(MainWindowViewModel), "imitater");
                }));
            Shell.MainMenu.Items.Add(imitaterMenu);
        }
Example #20
0
        public void Update(Item[] items, CommandItem command, ScheduleItem schedule)
        {
            using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
            {
                foreach (var scriptItem in items.Where(si => si.IsPowerShellScript() && !string.IsNullOrWhiteSpace(si[Templates.Script.Fields.ScriptBody])))
                {
                    if (!RulesUtils.EvaluateRules(scriptItem[Templates.Script.Fields.EnableRule], scriptItem))
                    {
                        continue;
                    }

                    session.SetItemLocationContext(scriptItem);
                    session.ExecuteScriptPart(scriptItem, true);
                }
            }
        }
        public void Run(Item[] items, CommandItem command, ScheduleItem schedule)
        {
            lock (_sync)
            {
                if (_IsRunning)
                {
                    return;
                }


                _IsRunning       = true;
                this.CommandItem = command;
            }

            var disableIndexing = this.DisableIndexing && Sitecore.Configuration.Settings.Indexing.Enabled;

            try
            {
                // Get the root
                var root = this.RootItem;
                Assert.ArgumentNotNull(root, "RootItem");

                if (disableIndexing)
                {
                    Log.Info("Temporarily disable indexing...", this);
                    Sitecore.Configuration.Settings.Indexing.Enabled = false;
                }

                Log.Info(string.Format("Start prune search from root item: {0}", root.Paths.Path), this);
                ProcessItemTree(root);
            }
            catch (Exception ex)
            {
                Log.Error("VersionPruner exception", ex, this);
                throw;
            }
            finally
            {
                _IsRunning = false;
                if (disableIndexing)
                {
                    Sitecore.Diagnostics.Log.Info("Re-enabled indexing...", this);
                    Sitecore.Configuration.Settings.Indexing.Enabled = true;
                }
            }
        }
Example #22
0
        /// <summary>
        /// Add a command that opens the settings for a plugin or shows some options as a result using a <see cref="SubItemsSource"/>.
        /// In order for options to be added to the search results, <typeparamref name="TSettings"/> needs to have at least one public property with a getter
        /// and a setter with either a <see cref="GenericOptionAttribute"/>, <see cref="SelectionOptionAttribute"/> or <see cref="NumberOptionAttribute"/>
        /// attached to it.
        /// </summary>
        /// <typeparam name="TSettings">Type of the settings object which has some properties
        /// with a <see cref="GenericOptionAttribute"/>/<see cref="SelectionOptionAttribute"/>/<see cref="NumberOptionAttribute"/>
        /// atteched to it.
        /// </typeparam>
        /// <param name="pluginName">Name of the plugin.</param>
        /// <param name="settings">The settings object used by the plugin or a proxy object for it.</param>
        /// <param name="openSettingsViewAction">
        /// Every <see cref="Playnite.SDK.Plugins.Plugin"/> has the
        /// <see cref="Playnite.SDK.Plugins.Plugin.OpenSettingsView"/> method
        /// that should be used here.
        /// </param>
        /// <returns>The item that was added. Can be used to remove it.</returns>
        public static CommandItem AddPluginSettings <TSettings>(string pluginName, TSettings settings, OpenSettingsViewDelegate openSettingsViewAction)
        {
            var    assembly     = Assembly.GetCallingAssembly();
            string assemblyName = assembly?.GetName()?.Name ?? "Null";

            assemblyName = assemblyName.Replace("_", " ");;
            var key = $"{assemblyName}_{pluginName}_SETTINGS";

            if (!registeredAssemblies.Contains(assemblyName))
            {
                registeredAssemblies.Add(assemblyName);
            }

            var settingsCommand = new CommandItem(pluginName + " " + Application.Current.FindResource("LOCSettingsLabel"), () => { openSettingsViewAction?.Invoke(); }, string.Format(ResourceProvider.GetString("LOC_QS_OpenSettings"), pluginName), ResourceProvider.GetString("LOC_QS_OpenAction"))
            {
                IconChar = IconChars.Settings
            };

            if (settings?.GetType().GetProperties().Any(prop => prop.GetCustomAttribute <GenericOptionAttribute>(true) != null) ?? false)
            {
                var subItemsSource = new SettingsItemSource <TSettings>()
                {
                    Prefix = pluginName + " " + Application.Current.FindResource("LOCSettingsLabel") as string, Settings = settings
                };
                var subItemsAction = new SubItemsAction()
                {
                    Action = () => { }, Name = ResourceProvider.GetString("LOC_QS_ShowAction"), SubItemSource = subItemsSource, CloseAfterExecute = false
                };
                subItemsAction.SubItemSource = subItemsSource;
                settingsCommand.Actions.Add(subItemsAction);
            }
            foreach (CommandItemKey k in settingsCommand.Keys.ToArray())
            {
                settingsCommand.Keys.Add(new CommandItemKey()
                {
                    Key = "> " + k.Key, Weight = 1
                });
            }
            var source = GetOrCreateSource(assemblyName);

            if (!source.entries.ContainsKey(key))
            {
                source.entries.Add(key, settingsCommand);
            }
            return(source.entries[key] as CommandItem);
        }
Example #23
0
        /// <summary>
        /// Check only allowed values for each Command in the CommandItem.
        /// </summary>
        /// <param name="item"></param>
        /// <returns>Returns true if values are correct otherwise false.</returns>
        private bool CheckCommandItem(CommandItem item)
        {
            switch (Enum.Parse <Command>(item.Command.ToString()))
            {
            case Command.CheckUser:
            case Command.OpenDoor when item.CommandValue.Equals(CommandValue.Open.ToString()) ||
                item.CommandValue.Equals(CommandValue.Close.ToString()):
            case Command.OpenGate when item.CommandValue.Equals(CommandValue.Open.ToString()) ||
                item.CommandValue.Equals(CommandValue.Close.ToString()) ||
                item.CommandValue.Equals(CommandValue.ForceOpen.ToString()) ||
                item.CommandValue.Equals(CommandValue.ForceClose.ToString()):
                return(true);

            default:
                return(false);
            }
        }
Example #24
0
        /// <summary>
        /// Checks if the user exists and has access rights.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private async Task <bool> CheckUser(CommandItem item)
        {
            if (_context.Users.Any(u => u.PhoneId.Equals(item.Id)))
            {
                User user = await _context.Users.SingleAsync(u => u.PhoneId.Equals(item.Id));

                user.LastConnection = DateTime.Now;
                await _context.SaveChangesAsync();

                if (user.AccessRights == AccessRights.Allowed)
                {
                    return(true);
                }
                return(false);
            }
            return(false);
        }
Example #25
0
        public void BuildNewXml(Item[] itemArray, CommandItem commandItem, ScheduleItem scheduledItem)
        {
            Item     item     = itemArray[0];
            Database database = Factory.GetDatabase("web");

            Log.Info("XML Sitemap started", this);
            string text             = item["CurrentWebsite"];
            var    addAspxExtension = item["AddAspxExtension"] == "1";

            if (string.IsNullOrEmpty(text))
            {
                text = "website";
            }
            SitemapGenerator sitemapGenerator = new SitemapGenerator(database.Items[ID.Parse(item["RootNode"]), Language.Parse(Factory.GetSite(text).Language)], text, addAspxExtension);

            sitemapGenerator.Generate(item["XmlFilePath"]);
            Log.Info("XML Sitemap ended", this);
        }
Example #26
0
        /// <summary>
        /// This function tells Vault Explorer what custom commands this extension provides.
        /// Part of the IExtension interface.
        /// </summary>
        /// <returns>A collection of CommandSites, which are collections of custom commands.</returns>
        public IEnumerable <CommandSite> CommandSites()
        {
            // Create the Hello World command object.
            CommandItem helloWorldCmdItem = new CommandItem("HelloWorldCommand", "Hello World...")
            {
                // this command is active when a File is selected
                NavigationTypes = new SelectionTypeId[] { SelectionTypeId.File, SelectionTypeId.FileVersion },

                // this command is not active if there are multiple entities selected
                MultiSelectEnabled = false
            };

            // The HelloWorldCommandHandler function is called when the custom command is executed.
            helloWorldCmdItem.Execute += HelloWorldCommandHandler;

            // Create a command site to hook the command to the Advanced toolbar
            CommandSite toolbarCmdSite = new CommandSite("HelloWorldCommand.Toolbar", "Hello World Menu")
            {
                Location             = CommandSiteLocation.AdvancedToolbar,
                DeployAsPulldownMenu = false
            };

            toolbarCmdSite.AddCommand(helloWorldCmdItem);

            // Create another command site to hook the command to the right-click menu for Files.
            CommandSite fileContextCmdSite = new CommandSite("HelloWorldCommand.FileContextMenu", "Hello World Menu")
            {
                Location             = CommandSiteLocation.FileContextMenu,
                DeployAsPulldownMenu = false
            };

            fileContextCmdSite.AddCommand(helloWorldCmdItem);

            // Now the custom command is available in 2 places.

            // Gather the sites in a List.
            List <CommandSite> sites = new List <CommandSite>();

            sites.Add(toolbarCmdSite);
            sites.Add(fileContextCmdSite);

            // Return the list of CommandSites.
            return(sites);
        }
Example #27
0
        public override IEnumerable <CommandItem> GetToolBarItemDescriptions()
        {
            var lst    = base.GetToolBarItemDescriptions().ToList();
            var image1 = SvgIconTarget.CheckCircle.ResourceFile;
            var image3 = new FileImageSource();

            image3.File = image1;

            var cmd = new CommandItem(CommandId.AnalyseThematique)
            {
                Text      = "Find",
                IsPrimary = true,
                Command   = FindItemCommand,
                Icon      = image3
            };

            lst.Add(cmd);
            return(lst);
        }
        /// <summary>
        /// Deletes a command.
        /// </summary>
        /// <param name="command">The command to delete.</param>
        /// <param name="cancellationToken">A token to observe while waiting for the task to complete.</param>
        /// <returns>
        /// A task that represents the asynchronous operation.
        /// </returns>
        public virtual async Task <ValidationResult> DeleteAsync(CommandItem command, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }
            var commandEntity = await Commands.FindAsync(cancellationToken, command.Id);

            if (commandEntity == null)
            {
                throw new InvalidOperationException($"Command was not found: {command.Id}");
            }
            Context.Remove(commandEntity);
            await SaveChangesAsync(cancellationToken);

            return(ValidationResult.Success);
        }
Example #29
0
        public void ImportProducts(Item[] itemArray, CommandItem commandItem, ScheduleItem scheduleItem)
        {
            Sitecore.Diagnostics.Log.Info("Starting import...", this);

            //be sure to populate these values on your schedule item
            var schedule   = new ActiveCommerce.SitecoreX.ScheduledTasks.ExtendedScheduleItem(scheduleItem);
            var file       = schedule.Arguments["file"];
            var path       = schedule.Arguments["path"];
            var templateId = schedule.Arguments["templateId"];

            using (new SecurityDisabler())
            {
                using (new ShopContextSwitcher(schedule.SiteContext, schedule.Database))
                {
                    Sitecore.Diagnostics.Log.Info("Executing import...", this);
                    DoImport(file, path, templateId);
                }
            }
        }
        public void EmailReports(Item[] itemarray, CommandItem commandItem, ScheduleItem scheduleItem)
        {
            var item = commandItem.InnerItem;

            if (item["active"] != "1")
            {
                return;
            }

            Log("Starting task");
            MultilistField mf = item.Fields["reports"];

            if (mf == null)
            {
                return;
            }
            var force     = item["sendempty"] == "1";
            var filePaths = mf.GetItems().Select(i => runReport(i, force));


            var mailMessage = new MailMessage
            {
                From    = new MailAddress(item["from"]),
                Subject = item["subject"],
            };
            var senders = item["to"].Split(',');

            foreach (var sender in senders)
            {
                mailMessage.To.Add(sender);
            }

            mailMessage.Body       = Sitecore.Web.UI.WebControls.FieldRenderer.Render(item, "text");
            mailMessage.IsBodyHtml = true;

            foreach (var path in filePaths.Where(st => !string.IsNullOrEmpty(st)))
            {
                mailMessage.Attachments.Add(new Attachment(path));
            }
            Log("attempting to send message");
            MainUtil.SendMail(mailMessage);
            Log("task finished");
        }
Example #31
0
        private static CommandItem ParseLine(Parser parser, ref int emptyLines, ref int lineCount)
        {
            if (parser.Current != '-' || parser.Next != '-')
            {
                return(null);
            }
            parser.Skip(2);
            parser.JumpWhite();
            if (parser.Current != '#')
            {
                // comment but not prolog comment
                lineCount++;
                return(null);
            }

            emptyLines = 0;
            lineCount++;

            parser.Skip(1);
            string command = parser.ReadToken();

            if (command == null)
            {
                return(null);
            }
            var item = new CommandItem
            {
                LineIndex = lineCount - 1,
                Command   = command,
            };

            while (!parser.IsEof)
            {
                string token = parser.ReadToken();
                if (token == null)
                {
                    break;
                }
                item.Arguments.Add(token);
            }
            return(item);
        }
        /// <summary>
        /// Inserts a command.
        /// </summary>
        /// <param name="command">The command to insert.</param>
        /// <param name="cancellationToken">A token to observe while waiting for the task to complete.</param>
        /// <returns>
        /// A task that represents the asynchronous operation.
        /// </returns>
        public virtual async Task <ValidationResult> CreateAsync(CommandItem command, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }
            var commandEntity = Context.Add(new CommandEntity
            {
                Uri         = command.Uri,
                CreatedDate = command.CreatedDate,
                Line        = command.Line,
                Data        = command.Data
            });

            await SaveChangesAsync(cancellationToken);

            command.Id = commandEntity.Id;
            return(ValidationResult.Success);
        }
Example #33
0
        public IEnumerable <CommandSite> CommandSites()
        {
            CommandSite site = new CommandSite("Autodesk.AAFind.Site", "Advanced Advanced Find")
            {
                DeployAsPulldownMenu = false,
                Location             = CommandSiteLocation.ToolsMenu
            };

            CommandItem cmd = new CommandItem("Autodesk.AAFind.Cmd", "Advanced Advanced Find...")
            {
                Image             = Icons.OnesAndZeros,
                Description       = "A search that supports OR conditions",
                Hint              = "A search that supports OR conditions",
                ToolbarPaintStyle = PaintStyle.TextAndGlyph
            };

            cmd.Execute += new EventHandler <CommandItemEventArgs>(cmd_Execute);

            site.AddCommand(cmd);
            return(new CommandSite[] { site });
        }
Example #34
0
        public CommandItem CreateInsertCommand()
        {
            CommandItem item = new CommandItem()
            {
                Command = new SQLiteCommand()
                {
                    CommandText = "INSERT INTO signs " +
                        "(`name`, `address`, `port`) " +
                        "VALUES " +
                        "(@name, @address, @port);" +
                        "select last_insert_rowid() as idsign;"
                }
            };

            item.Command.Parameters.Add(new SQLiteParameter("@name", Name.SafeValue));
            item.Command.Parameters.Add(new SQLiteParameter("@address", Address.SafeValue));
            item.Command.Parameters.Add(new SQLiteParameter("@port", Port.SafeValue));
            item.Callback += InsertedCommand_Callback;

            return item;
        }
        private void BindCommands()
        {
            var cmdTypes = _sys.GetAvailableCommands();

            _commands.Clear();

            foreach (Type t in cmdTypes.OrderBy(t => t.Name))
            {
                var cmd = new CommandItem();
                cmd.Type        = t;
                cmd.DisplayName = string.Format("{0} ({1})", t.Name, t.Namespace);
                cmd.FullName    = t.FullName;

                _commands.Add(cmd);
            }

            cbCommands.ItemsSource       = _commands;
            cbCommands.DisplayMemberPath = "DisplayName";
            cbCommands.SelectedValuePath = "FullName";
            cbCommands.SelectedValue     = null;
        }
Example #36
0
        public IEnumerable <CommandSite> CommandSites()
        {
            CommandSite folderContextMenu = new CommandSite(s_FolderContextMenuCommandSiteId, "FindOrphaned")
            {
                DeployAsPulldownMenu = false,
                Location             = CommandSiteLocation.FolderContextMenu,
            };
            CommandItem findOrphanedFilesCmd = new CommandItem(s_FindOrphanedFilesCommandId, "Find Orphaned Files ...")
            {
                Description        = "Finds orphaned files in selected folder",
                Hint               = "Find orphaded files in folder",
                MultiSelectEnabled = true,
                NavigationTypes    = new SelectionTypeId[] { SelectionTypeId.Folder },
                ToolbarPaintStyle  = PaintStyle.TextAndGlyph,
                Image              = Resources.Resource.OnesAndZeros
            };

            findOrphanedFilesCmd.Execute += new EventHandler <CommandItemEventArgs>(Handle_FindOrphanedFilesCmd_Execute);

            folderContextMenu.AddCommand(findOrphanedFilesCmd);
            return(new CommandSite[] { folderContextMenu });
        }
Example #37
0
        public IEnumerable <CommandSite> CommandSites()
        {
            var cmdItem = new CommandItem("CreateOrder.Command", "Create new Order...")
            {
                NavigationTypes    = new[] { SelectionTypeId.FileVersion },
                MultiSelectEnabled = false
            };

            cmdItem.Execute += CreateOrderCommand;

            var cmdSite = new CommandSite("CreateOrder.FileContextMenu", "Order")
            {
                Location             = CommandSiteLocation.FileContextMenu,
                DeployAsPulldownMenu = false
            };

            cmdSite.AddCommand(cmdItem);

            return(new List <CommandSite> {
                cmdSite
            });
        }
Example #38
0
        public IEnumerable <CommandSite> CommandSites()
        {
            CommandItem ThinClientUrlCmd = new CommandItem(
                "Autodesk.ADN.PermaLink", "View in Thin Client...")
            {
                NavigationTypes = new SelectionTypeId[] {
                    SelectionTypeId.File,
                    SelectionTypeId.FileVersion,
                    SelectionTypeId.Folder
                },
                MultiSelectEnabled = false
            };

            ThinClientUrlCmd.Execute += ThinClientUrlCmd_Execute;
            CommandSite permaLinkFileContextSite = new CommandSite(
                "Autodesk.ADN.PermaLinkFileContext", "PermaLinkFileContext")
            {
                DeployAsPulldownMenu = false,
                Location             = CommandSiteLocation.FileContextMenu
            };

            permaLinkFileContextSite.AddCommand(ThinClientUrlCmd);

            CommandSite permaLinkFolderContextSite = new CommandSite(
                "Autodesk.ADN.PermaLinkFolderContext", "PermaLinkFolderContext")
            {
                DeployAsPulldownMenu = false,
                Location             = CommandSiteLocation.FolderContextMenu
            };

            permaLinkFolderContextSite.AddCommand(ThinClientUrlCmd);

            List <CommandSite> sites = new List <CommandSite>();

            sites.Add(permaLinkFileContextSite);
            sites.Add(permaLinkFolderContextSite);

            return(sites);
        }
Example #39
0
        /// <summary>
        /// Add a simple executable search entry with multiple actions that can be searched
        /// for by its <paramref name="name"/> and its <paramref name="descripton"/>.
        /// </summary>
        /// <param name="name">Name displayed on the top left. Always visible.</param>
        /// <param name="actions">List of actions shown in the search box when this item is selected.</param>
        /// <param name="descripton">Description displayed on the bottem left. Not visible when collapsed.</param>
        /// <param name="iconPath">Path to an image file. Used like a game icon on the left.</param>
        /// <returns>The <see cref="CommandItem"/> that was added. Can be used to remove it.</returns>
        public static CommandItem AddCommand(string name, IList <CommandAction> actions, string descripton = null, string iconPath = null)
        {
            var    assembly     = Assembly.GetCallingAssembly();
            string assemblyName = assembly?.GetName()?.Name ?? "Null";

            assemblyName = assemblyName.Replace("_", " ");;
            var key = $"{assemblyName}_{name}";

            if (!registeredAssemblies.Contains(assemblyName))
            {
                registeredAssemblies.Add(assemblyName);
            }
            var item = new CommandItem(name, actions, descripton, iconPath);

            var source = GetOrCreateSource(assemblyName);

            if (!source.entries.ContainsKey(key))
            {
                source.entries.Add(key, item);
            }
            return(source.entries[key] as CommandItem);
        }
Example #40
0
        public void UpdateOrders(Item[] itemArray, CommandItem commandItem, ScheduleItem scheduleItem)
        {
            Sitecore.Diagnostics.Log.Info("Starting update...", this);
            var schedule = new ActiveCommerce.SitecoreX.ScheduledTasks.ExtendedScheduleItem(scheduleItem);

            using (new SecurityDisabler())
            {
                using (new ShopContextSwitcher(schedule.SiteContext, schedule.Database))
                {
                    //otherwise, if we have a preview cookie in place, we can't get to the orders root item
                    using (new ItemFilteringDisabler())
                    {
                        var startStatus = schedule.Arguments["startStatus"];

                        //to get an appropriately typed OrderStatus, to set on an order
                        var endStatus = Sitecore.Ecommerce.Context.Entity.Resolve <OrderStatus>(schedule.Arguments["endStatus"]);

                        DoUpdate(startStatus, endStatus);
                    }
                }
            }
        }
Example #41
0
        private void GenerateCommandItem(TextWriter writer, CommandItem item)
        {
            writer.WriteLine("                   // COMMANDITEMINFO");

            writer.WriteLine("    /* {0:X4} */     0x00,",
                             offset);
            offset += 1;

            writer.Write("    /* {0:X4} */     0x{1:X2}, ",
                         offset,
                         item.Title.Length);
            int byteCount = 1;

            foreach (char ch in item.Title)
            {
                if (byteCount == 0)
                {
                    writer.Write("                   ");
                }
                writer.Write("'{0}', ", ch);
                byteCount++;
                if (byteCount == 8)
                {
                    writer.WriteLine();
                    byteCount = 0;
                }
            }
            if (byteCount != 0)
            {
                writer.WriteLine();
            }
            offset += item.Title.Length + 1;

            writer.WriteLine("    /* {0:X4} */     {1}, ",
                             offset,
                             item.MenuId);
            offset += 1;
        }
        /// <summary>
        /// Start point of the command
        /// </summary>
        /// <param name="items">Passed items</param>
        /// <param name="command">Passed command</param>
        /// <param name="schedule">Passed schedule item</param>
        public void Run(Item[] items, CommandItem command, ScheduleItem schedule)
        {
            Log.Info("Scheduled Publish: started", this);

            _scheduledPublishRepo = new ScheduledPublishRepo();

            Stopwatch commandStopwatch = new Stopwatch();
            commandStopwatch.Start();

            //Publish all scheduled for the last hour
            DateTime publishToDate = DateTime.Now;
            DateTime publishFromDate = publishToDate.AddHours(-1);
            PublishSchedules(publishFromDate, publishToDate);

            //Alerts for failed schedules 2 hours ago
            DateTime alertToDate = publishFromDate.AddHours(-1).AddSeconds(-1);
            DateTime alertFromDate = publishFromDate.AddHours(-2);
            AlertForFailedSchedules(alertFromDate, alertToDate);

            _scheduledPublishRepo.CleanBucket();
            commandStopwatch.Stop();
            Log.Info("Scheduled Publish: Total Run " + commandStopwatch.ElapsedMilliseconds, this);
        }
Example #43
0
        public void Run(Item[] items, CommandItem command, ScheduleItem schedule)
        {
            var importCommand = new ImportCommandItem(command.InnerItem);
            Log.Info(
                "EzImporter.Tasks.Import.Run() Starting Import: "
                + " fileName=" + importCommand.FileName
                + " lang=" + importCommand.TargetLanguage
                + " location=" + importCommand.ImportLocationId
                + " importMap=" + importCommand.ImportMapId
                + " database=" + importCommand.Database.Name
                + " csvDelimiter=" + importCommand.CsvDelimiter
                + " ExistingItemHandling=" + importCommand.ExistingItemHandling
                + " InvalidLinkHandling=" + importCommand.InvalidLinkHandling
                + " MultipleValuesImportSeparator=" + importCommand.MultipleValuesImportSeparator
                + " TreePathValuesImportSeparator=" + importCommand.TreePathValuesImportSeparator, this);

            var options = Factory.GetDefaultImportOptions();
            if (importCommand.CsvDelimiter != null)
            {
                options.CsvDelimiter = new[] {importCommand.CsvDelimiter};
            }
            if (importCommand.ExistingItemHandling != null)
            {
                options.ExistingItemHandling = (ExistingItemHandling)
                    Enum.Parse(typeof (ExistingItemHandling), importCommand.ExistingItemHandling);
            }
            if (importCommand.InvalidLinkHandling != null)
            {
                options.InvalidLinkHandling = (InvalidLinkHandling)
                    Enum.Parse(typeof (InvalidLinkHandling), importCommand.InvalidLinkHandling);
            }
            if (importCommand.MultipleValuesImportSeparator != null)
            {
                options.MultipleValuesImportSeparator = importCommand.MultipleValuesImportSeparator;
            }
            if (importCommand.TreePathValuesImportSeparator != null)
            {
                options.TreePathValuesImportSeparator = importCommand.TreePathValuesImportSeparator;
            }
            options.FirstRowAsColumnNames = importCommand.FirstRowAsColumnNames;
            if (string.IsNullOrWhiteSpace(importCommand.FileName))
            {
                Log.Error(
                    "EzImporter.Tasks.Import.Run() - Import Error: File not specified",
                    this);
                return;
            }
            string fileName;
            if (File.Exists(importCommand.FileName))
            {
                fileName = importCommand.FileName;
            }
            else
            {
                fileName = HostingEnvironment.MapPath(importCommand.FileName);
                if (!File.Exists(fileName))
                {
                    Log.Error(
                        "EzImporter.Tasks.Import.Run() - Import Error: File not found (" + importCommand.FileName + ")",
                        this);
                    return;
                }
            }
            var extension = GetFileExtension(fileName);
            if (extension == null)
            {
                Log.Error(
                    "EzImporter.Tasks.Import.Run() - Import Error: Unknown file extension (" + importCommand.FileName +
                    ")", this);
                return;
            }
            var stream = new StreamReader(fileName);
            var args = new ImportItemsArgs
            {
                Database = importCommand.ImportDatabase,
                FileExtension = extension,
                FileStream = stream.BaseStream,
                RootItemId = importCommand.ImportLocationId,
                TargetLanguage = importCommand.TargetLanguage,
                Map = Map.Factory.BuildMapInfo(importCommand.ImportMapId),
                ImportOptions = options
            };
            try
            {
                CorePipeline.Run("importItems", args);
                Log.Info("EzImporter.Tasks.Import.Run() Import Finished " + args.Statistics, this);
            }
            catch (Exception ex)
            {
                Log.Error("EzImporter.Tasks.Import.Run() - Import Error: " + ex, this);
                throw;
            }
        }
        public void Run(Item[] items, CommandItem command, ScheduleItem schedule)
        {
            lock (_sync)
            {
                if (_IsRunning)
                    return;

                _IsRunning = true;
                this.CommandItem = command;
            }

            var disableIndexing = this.DisableIndexing && Sitecore.Configuration.Settings.Indexing.Enabled;

            try
            {
                // Get the root
                var root = this.RootItem;
                Assert.ArgumentNotNull(root, "RootItem");

                if (disableIndexing)
                {
                    Log.Info("Temporarily disable indexing...", this);
                    Sitecore.Configuration.Settings.Indexing.Enabled = false;
                }

                Log.Info(string.Format("Start prune search from root item: {0}", root.Paths.Path), this);
                ProcessItemTree(root);
            }
            catch (Exception ex)
            {
                Log.Error("VersionPruner exception", ex, this);
                throw;
            }
            finally
            {
                _IsRunning = false;
                if (disableIndexing)
                {
                    Sitecore.Diagnostics.Log.Info("Re-enabled indexing...", this);
                    Sitecore.Configuration.Settings.Indexing.Enabled = true;
                }
            }
        }
Example #45
0
		public override bool Merge(CommandItem newitem) {
			SelectionMovedOrResizedStroke newitemx = newitem as SelectionMovedOrResizedStroke;
			// Ensure items are of the same type.
			if (newitemx == null ||
					newitemx._editingOperationCount != _editingOperationCount ||
					!StrokeCollectionsAreEqual(newitemx._selection, _selection)) {
				return false;
			}
			// Keep former oldrect, latter newrect.
			_newrect = newitemx._newrect;
			return true;
		}
 public void RunJob(Item[] itemArray, CommandItem commandItem, ScheduleItem scheduledItem)
 {
     try
     {
         if (scheduledItem != null)
         {
             var itemIds = scheduledItem[ItemsFieldName];
             if (!String.IsNullOrEmpty(itemIds))
             {
                 var dataSourceCache = new Dictionary<string, string>();
                 var idList = itemIds.Split('|');
                 if (idList.Any())
                 {
                     foreach (var id in idList)
                     {
                         if (ID.IsID(id))
                         {
                             var dataSyncItem = scheduledItem.Database.GetItem(new ID(id));
                             try
                             {
                                 if (dataSyncItem != null)
                                 {
                                     var startedAt = DateTime.Now;
                                     LevelLogger logger = Manager.CreateLogger(dataSyncItem);
                                     logger.AddKey(Utility.Constants.DataSyncItemId, dataSyncItem.ID.ToString());
                                     logger.AddData(Utility.Constants.DataSyncItem, dataSyncItem);
                                     logger.AddData(Logger.Log.Constants.Identifier, dataSyncItem.Name);
                                     var dataSyncManager = new DataSyncManager();
                                     var dataSyncObject = dataSyncManager.InstantiateDataMap(dataSyncItem, ref logger) as XmlDataMap;
                                     if (dataSyncObject != null)
                                     {
                                         dataSyncObject.DataSourceCache = dataSourceCache;
                                         dataSyncObject.Process();
                                     }
                                     var finishededAt = DateTime.Now;
                                     logger.AddData(Logger.Log.Constants.StartTime, startedAt);
                                     logger.AddData(Logger.Log.Constants.EndTime, finishededAt);
                                     var exporter = Manager.CreateOutputHandler(dataSyncItem, logger);
                                     var logText = exporter.Export();
                                     if (exporter != null)
                                     {
                                         if (logger != null)
                                         {
                                             try
                                             {
                                                 MailManager.SendLogReport(ref logger, exporter);
                                             }
                                             catch (Exception exception)
                                             {
                                                 Diagnostics.Log.Error(
                                                     "Failed in sending out the mail. Please see the exception message for more details. Exception:" +
                                                     exception.Message + "\r\n\r\n" + logText, typeof(DataSyncTask));
                                             }
                                             if (logger.HasErrors())
                                             {
                                                 Diagnostics.Log.Error(logText, typeof (DataSyncTask));
                                             }
                                             else
                                             {
                                                 Diagnostics.Log.Debug(logText, typeof(DataSyncTask));
                                             }
                                         }
                                         else
                                         {
                                             Diagnostics.Log.Error("The Log object was null. This should not happen." + "\r\n\r\n" + logText, typeof(DataSyncTask));
                                         }
                                     }
                                     else
                                     {
                                         Diagnostics.Log.Error("The Exporter class was null. Therefor the log was not written out.\r\n\r\n" + logText, typeof(DataSyncTask));
                                     }
                                 }
                                 else
                                 {
                                     Diagnostics.Log.Error("The Task item had Items defined in Items[] that was null. This should not happen.", typeof (DataSyncTask));
                                 }
                             }
                             catch (Exception exception)
                             {
                                 var itemId = dataSyncItem != null ? dataSyncItem.ID.ToString() : string.Empty;
                                 Diagnostics.Log.Error(
                                     Identifier +
                                     String.Format(
                                         " - An exception occured in the execution of the task in the foreach (Item dataSyncItem in itemArray) of the DataSync item: {0}. This datasync job wasn't completed. Exception: {1}",
                                         itemId, exception.Message), typeof (DataSyncTask));
                             }
                         }
                         else
                         {
                             Diagnostics.Log.Error(
                             Identifier +
                             " - The provided value wasn't a correct Sitecore id. Please add at least one id to 'Items' field of the ScheduledItem. You can also use | to seperate ids. Therefor nothing was done.",
                             typeof(DataSyncTask));
                         }
                     }
                 }
                 else
                 {
                     Diagnostics.Log.Error(
                         Identifier +
                         " - There wasn't defined any DataSync items to run. Please add at least one id to 'Items' field of the ScheduledItem. You can also use | to seperate ids. Therefor nothing was done.",
                         typeof (DataSyncTask));
                 }
             }
             else
             {
                 Diagnostics.Log.Error(
                     Identifier + " - There wasn't defined any DataSync items to run. Therefor nothing was done.",
                     typeof (DataSyncTask));
             }
         }
         else
         {
             Diagnostics.Log.Error(
                     Identifier + " - The ScheduledItem was null. Therefor nothing was done.",
                     typeof(DataSyncTask));
         }
     }
     catch (Exception exception)
     {
         Diagnostics.Log.Error(Identifier + " - An exception occured in the execution of the task.", exception);
     }
 }
Example #47
0
        private static CommandItem ParseLine(Parser parser, ref int emptyLines, ref int lineCount)
        {
            if (parser.Current != '-' || parser.Next != '-')
            {
                return null;
            }
            parser.Skip(2);
            parser.JumpWhite();
            if (parser.Current != '#')
            {
                // comment but not prolog comment
                lineCount++;
                return null;
            }

            emptyLines = 0;
            lineCount++;

            parser.Skip(1);
            string command = parser.ReadToken();
            if (command == null) return null;
            var item = new CommandItem
                {
                    LineIndex = lineCount - 1,
                    Command = command,
                };
            while (!parser.IsEof)
            {
                string token = parser.ReadToken();
                if (token == null) break;
                item.Arguments.Add(token);
            }
            return item;
        }
        private void BindCommands()
        {
            var mw = App.Current.MainWindow as MainWindow;

              var cmdTypes = _sys.GetAvailableCommands(true);

              _commands.Clear();

              foreach( Type t in cmdTypes.OrderBy(t => t.Name) ) {
            var cmd = new CommandItem();
            cmd.Type = t;
            cmd.DisplayName = string.Format("{0} ({1})", t.Name, t.Namespace);
            cmd.FullName = t.FullName;

            _commands.Add(cmd);
              }

              cbCommands.ItemsSource = _commands;
              cbCommands.DisplayMemberPath = "DisplayName";
              cbCommands.SelectedValuePath = "FullName";
              cbCommands.SelectedValue = null;
        }
        // Returns information on commands added in this extension
        //
        public IEnumerable<CommandSite> CommandSites()
        {
            // Create command item for Hello World command
            //
            List<CommandItem> menuitems = new List<CommandItem>();

            string extensionfolder = Application.ExecutablePath;
            extensionfolder = System.IO.Path.GetDirectoryName(extensionfolder);
            extensionfolder += "\\Extensions\\VaultCreateFromTemplate";
            string[] filePaths = Directory.GetFiles(extensionfolder,"*.xml");
            int numXmlfiles = 0;
            foreach (string filepath in filePaths)
            {
                //if (filepath.EndsWith(".xml")) 
                //{
                    CommandItem CmdItem = new CommandItem(System.IO.Path.GetFileName(filepath), System.IO.Path.GetFileNameWithoutExtension(filepath)) { NavigationTypes = new SelectionTypeId[] { SelectionTypeId.Folder }, MultiSelectEnabled = false };
                    CmdItem.Execute += VaultCreateFromTemplateCommandHandler;
                    menuitems.Add(CmdItem);
                    numXmlfiles++;
                //}
            }

            CommandItem VaultCreateFromTemplateCmdItem;
            CommandSite folderContextCmdSite;
            List<CommandSite> sites = new List<CommandSite>();
            if (numXmlfiles == 1)
            {
                folderContextCmdSite = new CommandSite("VaultCreateFromTemplateCommand.FolderContextMenu", "Create Folders...") { Location = CommandSiteLocation.FolderContextMenu, DeployAsPulldownMenu = false };
                //VaultCreateFromTemplateCmdItem = new CommandItem("", "Create From Template") { NavigationTypes = new SelectionTypeId[] { SelectionTypeId.Folder }, MultiSelectEnabled = false };
                //VaultCreateFromTemplateCmdItem.Execute += VaultCreateFromTemplateCommandHandler;
                //folderContextCmdSite.AddCommand(VaultCreateFromTemplateCmdItem);
                foreach (CommandItem CmdItem in menuitems)
                {
                    CommandItem NewCmdItem = new CommandItem(CmdItem.Id, "Create Folders...") { NavigationTypes = new SelectionTypeId[] { SelectionTypeId.Folder }, MultiSelectEnabled = false };
                    NewCmdItem.Execute += VaultCreateFromTemplateCommandHandler;
                    folderContextCmdSite.AddCommand(NewCmdItem);
                }
            }
            else
            {
                folderContextCmdSite = new CommandSite("VaultCreateFromTemplateCommand.FolderContextMenu", "Create Folders...") { Location = CommandSiteLocation.FolderContextMenu, DeployAsPulldownMenu = true };
                int count = 0;
                foreach (CommandItem CmdItem in menuitems)
                {
                    if (count < 10)
                    {
                        folderContextCmdSite.AddCommand(CmdItem);
                    }
                    count++;
                }
                if (menuitems.Count >= 10)
                {
                    VaultCreateFromTemplateCmdItem = new CommandItem("\\More...\\", "More ...") { NavigationTypes = new SelectionTypeId[] { SelectionTypeId.Folder }, MultiSelectEnabled = false };
                    VaultCreateFromTemplateCmdItem.Execute += VaultCreateFromTemplateCommandHandler;
                    folderContextCmdSite.AddCommand(VaultCreateFromTemplateCmdItem);
                }
            }
            sites.Add(folderContextCmdSite);
            return sites;
        }
        //        The entry point of the agent
        public void Run(Item[] itemArray, CommandItem commandItem, ScheduleItem scheduledItem)
        {
            Logger.Info(string.Format("Started on {0}", DateTime.Now), this);
            //          Association between users and items:key - user email, value - items to include in notification
            Dictionary<string, List<Item>> recipientItemsDictionary = new Dictionary<string, List<Item>>();
            try
            {
                EmailUtility emailUtility = new EmailUtility();
                var allWorkflows = WorkflowHelper.GetAllWorkflows();
                foreach (var workflow in allWorkflows)
                {
                    var worklowStates = WorkflowHelper.GetNonFinalStatesByTemplate(workflow, StateTemplateName);
                    foreach (var state in worklowStates)
                    {
                        string timeFrameString = WorkflowHelper.GetStateFieldValue(state, TimeFiledName);
                        if (string.IsNullOrEmpty(timeFrameString))
                        {
                            Logger.Warn(
                                string.Format("{0} field isn't specified for state {1}", TimeFiledName,
                                              state.DisplayName), this);
                            continue;
                        }

                        TimeSpan timeFrame = DateUtil.ParseTimeSpan(timeFrameString, TimeSpan.Zero);
                        if (timeFrame == TimeSpan.Zero)
                        {
                            Logger.Warn(
                                string.Format("{0} field isn't well formatted for state {1}", TimeFiledName,
                                              state.DisplayName), this);
                            continue;
                        }

                        Field recipientsField = WorkflowHelper.GetStateField(state, RecipientsFieldName);
                        if (recipientsField == null || string.IsNullOrEmpty(recipientsField.Value))
                        {
                            Logger.Warn(
                                string.Format("{0} field isn't specified for state {1}", RecipientsFieldName,
                                              state.DisplayName), this);
                            continue;
                        }

                        List<string> recepients = GetEmailsForUsersAndRoles(recipientsField);
                        if (recepients.Count == 0)
                        {
                            Logger.Warn(
                                string.Format("There's no users with valid email addresses to notify for state {0}",
                                              state.DisplayName), this);
                            continue;
                        }

                        var itemsInState = WorkflowHelper.GetItemsInState(workflow, state.StateID);
                        foreach (var item in  itemsInState)
                        {
                            if (WorkflowHelper.IsTimeLimitExceeded(item, workflow, timeFrame))
                            {
                                AddToResultSet(item, recipientItemsDictionary, recepients.ToArray());
                            }
                        }
                    }
                }

                ProcessResultSet(recipientItemsDictionary, emailUtility);
            }
            catch (Exception exc)
            {
                Logger.Error("Unspecified error ocurred", exc, this);
            }
            finally
            {
                Logger.Info("Stopped", this);
            }
        }
 public void RunJob(Item[] itemArray, CommandItem commandItem, ScheduleItem scheduledItem)
 {
     try
     {
         if (scheduledItem != null)
         {
             var itemIds = scheduledItem["Items"];
             if (!String.IsNullOrEmpty(itemIds))
             {
                 var idList = itemIds.Split('|');
                 if (idList.Any())
                 {
                     foreach (var id in idList)
                     {
                         if (ID.IsID(id))
                         {
                             var userSyncItem = scheduledItem.Database.GetItem(new ID(id));
                             try
                             {
                                 if (userSyncItem != null)
                                 {
                                     var startedAt = DateTime.Now.ToLongDateString();
                                     Logging logBuilder = new Logging();
                                     var userSyncManager = new UserSyncManager();
                                     userSyncManager.RunUserSyncJob(userSyncItem, ref logBuilder);
                                     var finishededAt = DateTime.Now.ToLongDateString();
                                     if (logBuilder != null)
                                     {
                                         try
                                         {
                                             MailManager.SendLogReport(ref logBuilder,
                                                                       GetUserSyncIdentifier(userSyncItem),
                                                                       userSyncItem);
                                         }
                                         catch (Exception exception)
                                         {
                                             Diagnostics.Log.Error(
                                                 GetIdentifierText(userSyncItem, startedAt, finishededAt) +
                                                 " failed in sending out the mail. Please see the exception message for more details. Exception:" + exception.Message + ". Status:\r\n" +
                                                 logBuilder.GetStatusText(), typeof(UserSyncTask));
                                         }
                                         if (logBuilder.LogBuilder != null)
                                         {
                                             if (!String.IsNullOrEmpty(logBuilder.LogBuilder.ToString()))
                                             {
                                                 Diagnostics.Log.Error(
                                                     GetIdentifierText(userSyncItem, startedAt, finishededAt) +
                                                     " failed. " +
                                                     logBuilder.LogBuilder + "\r\nStatus:\r\n" +
                                                     logBuilder.GetStatusText(),
                                                     typeof(UserSyncTask));
                                             }
                                             else
                                             {
                                                 Diagnostics.Log.Debug(
                                                     GetIdentifierText(userSyncItem, startedAt, finishededAt) +
                                                     " completed with success.\r\nStatus:\r\n" +
                                                     logBuilder.GetStatusText(),
                                                     typeof(UserSyncTask));
                                             }
                                         }
                                         else
                                         {
                                             Diagnostics.Log.Error(
                                                    GetIdentifierText(userSyncItem, startedAt, finishededAt) +
                                                    " failed. The Logging.LogBuilder object was null. " +
                                                    logBuilder + "\r\nStatus:\r\n" +
                                                    logBuilder.GetStatusText(),
                                                    typeof(UserSyncTask));
                                         }
                                     }
                                     else
                                     {
                                         Diagnostics.Log.Error(
                                             GetIdentifierText(userSyncItem, startedAt, finishededAt) +
                                             " - The Log object was null. This should not happen.",
                                             typeof(UserSyncTask));
                                     }
                                 }
                                 else
                                 {
                                     Diagnostics.Log.Error(
                                         " - The Task item had Items defined in Items[] that was null. This should not happen.",
                                         typeof(UserSyncTask));
                                 }
                             }
                             catch (Exception exception)
                             {
                                 var itemId = userSyncItem != null ? userSyncItem.ID.ToString() : string.Empty;
                                 Diagnostics.Log.Error(
                                     Identifier +
                                     String.Format(
                                         " - An exception occured in the execution of the task in the foreach (Item UserSyncItem in itemArray) of the UserSync item: {0}. This UserSync job wasn't completed. Exception: {1}",
                                         itemId, exception.Message), typeof(UserSyncTask));
                             }
                         }
                         else
                         {
                             Diagnostics.Log.Error(
                             Identifier +
                             " - The provided value wasn't a correct Sitecore id. Please add at least one id to 'Items' field of the ScheduledItem. You can also use | to seperate ids. Therefore nothing was done.",
                             typeof(UserSyncTask));
                         }
                     }
                 }
                 else
                 {
                     Diagnostics.Log.Error(
                         Identifier +
                         " - There wasn't defined any UserSync items to run. Please add at least one id to 'Items' field of the ScheduledItem. You can also use | to seperate ids. Therefore nothing was done.",
                         typeof(UserSyncTask));
                 }
             }
             else
             {
                 Diagnostics.Log.Error(
                     Identifier + " - There wasn't defined any UserSync items to run. Therefore nothing was done.",
                     typeof(UserSyncTask));
             }
         }
         else
         {
             Diagnostics.Log.Error(
                     Identifier + " - The ScheduledItem was null. Therefore nothing was done.",
                     typeof(UserSyncTask));
         }
     }
     catch (Exception exception)
     {
         Diagnostics.Log.Error(Identifier + " - An exception occured in the execution of the task.", exception);
     }
 }