/// <summary> /// Returns an enum <see cref="MacroTypes"/> based on the properties on the Macro /// </summary> /// <returns><see cref="MacroTypes"/></returns> internal static MacroTypes GetMacroType(IMacro macro) { if (string.IsNullOrEmpty(macro.XsltPath) == false) { return(MacroTypes.Xslt); } if (string.IsNullOrEmpty(macro.ScriptPath) == false) { //we need to check if the file path saved is a virtual path starting with ~/Views/MacroPartials, if so then this is //a partial view macro, not a script macro //we also check if the file exists in ~/App_Plugins/[Packagename]/Views/MacroPartials, if so then it is also a partial view. return((macro.ScriptPath.InvariantStartsWith(SystemDirectories.MvcViews + "/MacroPartials/") || (Regex.IsMatch(macro.ScriptPath, "~/App_Plugins/.+?/Views/MacroPartials", RegexOptions.Compiled | RegexOptions.IgnoreCase))) ? MacroTypes.PartialView : MacroTypes.Script); } if (string.IsNullOrEmpty(macro.ControlType) == false && macro.ControlType.InvariantContains(".ascx")) { return(MacroTypes.UserControl); } if (string.IsNullOrEmpty(macro.ControlType) == false && string.IsNullOrEmpty(macro.ControlAssembly) == false) { return(MacroTypes.CustomControl); } return(MacroTypes.Unknown); }
/// <summary> /// Saves an <see cref="IMacro"/> /// </summary> /// <param name="macro"><see cref="IMacro"/> to save</param> /// <param name="userId">Optional Id of the user deleting the macro</param> public void Save(IMacro macro, int userId = 0) { using (var uow = UowProvider.GetUnitOfWork()) { var saveEventArgs = new SaveEventArgs <IMacro>(macro); if (uow.Events.DispatchCancelable(Saving, this, saveEventArgs)) { uow.Commit(); return; } if (string.IsNullOrWhiteSpace(macro.Name)) { throw new ArgumentException("Cannot save macro with empty name."); } var repository = RepositoryFactory.CreateMacroRepository(uow); repository.AddOrUpdate(macro); saveEventArgs.CanCancel = false; uow.Events.Dispatch(Saved, this, saveEventArgs); Audit(uow, AuditType.Save, "Save Macro performed by user", userId, -1); uow.Commit(); } }
public void Can_Update_Property() { // Arrange IMacro macro = CreateMacro(); macro.Properties.Add(new MacroProperty("blah", "Blah", 0, "blah")); MacroService.Save(macro); Assert.AreNotEqual(Guid.Empty, macro.Properties[0].Key); // Act Guid currPropKey = macro.Properties[0].Key; macro.Properties[0].Alias = "new Alias"; macro.Properties[0].Name = "new Name"; macro.Properties[0].SortOrder = 1; macro.Properties[0].EditorAlias = "new"; MacroService.Save(macro); macro = MacroService.GetById(macro.Id); // Assert Assert.AreEqual(1, macro.Properties.Count); Assert.AreEqual(currPropKey, macro.Properties[0].Key); Assert.AreEqual("new Alias", macro.Properties[0].Alias); Assert.AreEqual("new Name", macro.Properties[0].Name); Assert.AreEqual(1, macro.Properties[0].SortOrder); Assert.AreEqual("new", macro.Properties[0].EditorAlias); Assert.AreEqual(currPropKey, macro.Properties[0].Key); }
public void Can_Add_And_Remove_Properties() { IMacro macro = CreateMacro(); // Adds some properties macro.Properties.Add(new MacroProperty("blah1", "Blah1", 0, "blah1")); macro.Properties.Add(new MacroProperty("blah2", "Blah2", 0, "blah2")); macro.Properties.Add(new MacroProperty("blah3", "Blah3", 0, "blah3")); macro.Properties.Add(new MacroProperty("blah4", "Blah4", 0, "blah4")); MacroService.Save(macro); IMacro result1 = MacroService.GetById(macro.Id); Assert.AreEqual(4, result1.Properties.Values.Count()); // Simulate clearing the sections foreach (IMacroProperty s in result1.Properties.Values.ToArray()) { result1.Properties.Remove(s.Alias); } // Now just re-add a couple result1.Properties.Add(new MacroProperty("blah3", "Blah3", 0, "blah3")); result1.Properties.Add(new MacroProperty("blah4", "Blah4", 0, "blah4")); MacroService.Save(result1); // Assert result1 = MacroService.GetById(result1.Id); Assert.AreEqual(2, result1.Properties.Values.Count()); }
public void Can_Perform_Update_On_Repository() { // Arrange IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act IMacro macro = repository.Get(2); macro.Name = "Hello"; macro.CacheDuration = 1234; macro.CacheByPage = true; macro.CacheByMember = true; macro.DontRender = false; macro.MacroSource = "~/newpath.cshtml"; macro.UseInEditor = true; repository.Save(macro); IMacro macroUpdated = repository.Get(2); // Assert Assert.That(macroUpdated, Is.Not.Null); Assert.That(macroUpdated.Name, Is.EqualTo("Hello")); Assert.That(macroUpdated.CacheDuration, Is.EqualTo(1234)); Assert.That(macroUpdated.CacheByPage, Is.EqualTo(true)); Assert.That(macroUpdated.CacheByMember, Is.EqualTo(true)); Assert.That(macroUpdated.DontRender, Is.EqualTo(false)); Assert.That(macroUpdated.MacroSource, Is.EqualTo("~/newpath.cshtml")); Assert.That(macroUpdated.UseInEditor, Is.EqualTo(true)); } }
public XElement Serialize(IMacro macro) { var xml = new XElement("macro"); xml.Add(new XElement("name", macro.Name)); xml.Add(new XElement("key", macro.Key)); xml.Add(new XElement("alias", macro.Alias)); xml.Add(new XElement("macroSource", macro.MacroSource)); xml.Add(new XElement("useInEditor", macro.UseInEditor.ToString())); xml.Add(new XElement("dontRender", macro.DontRender.ToString())); xml.Add(new XElement("refreshRate", macro.CacheDuration.ToString(CultureInfo.InvariantCulture))); xml.Add(new XElement("cacheByMember", macro.CacheByMember.ToString())); xml.Add(new XElement("cacheByPage", macro.CacheByPage.ToString())); var properties = new XElement("properties"); foreach (IMacroProperty property in macro.Properties) { properties.Add(new XElement( "property", new XAttribute("key", property.Key), new XAttribute("name", property.Name !), new XAttribute("alias", property.Alias), new XAttribute("sortOrder", property.SortOrder), new XAttribute("propertyType", property.EditorAlias))); } xml.Add(properties); return(xml); }
public void Can_Add_Remove_Macro_Properties() { // Arrange IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); var macro = new Macro(ShortStringHelper, "newmacro", "A new macro", "~/views/macropartials/test1.cshtml"); var prop1 = new MacroProperty("blah1", "New1", 4, "test.editor"); var prop2 = new MacroProperty("blah2", "New2", 3, "test.editor"); // add/remove a few to test the collection observable macro.Properties.Add(prop1); macro.Properties.Add(prop2); macro.Properties.Remove(prop1); macro.Properties.Remove("blah2"); macro.Properties.Add(prop2); repository.Save(macro); // Assert IMacro result = repository.Get(macro.Id); Assert.AreEqual(1, result.Properties.Values.Count()); Assert.AreEqual("blah2", result.Properties.Values.Single().Alias); } }
public void Can_Perform_Get_On_Repository() { // Arrange IScopeProvider provider = ScopeProvider; using (provider.CreateScope()) { var repository = new MacroRepository((IScopeAccessor)provider, AppCaches.Disabled, _logger, ShortStringHelper); // Act IMacro macro = repository.Get(1); // Assert Assert.That(macro, Is.Not.Null); Assert.That(macro.HasIdentity, Is.True); Assert.That(macro.Alias, Is.EqualTo("test1")); Assert.That(macro.CacheByPage, Is.EqualTo(false)); Assert.That(macro.CacheByMember, Is.EqualTo(false)); Assert.That(macro.DontRender, Is.EqualTo(true)); Assert.That(macro.Name, Is.EqualTo("Test1")); Assert.That(macro.CacheDuration, Is.EqualTo(0)); Assert.That(macro.MacroSource, Is.EqualTo("~/views/macropartials/test1.cshtml")); Assert.That(macro.UseInEditor, Is.EqualTo(false)); } }
/// <summary> /// This will insert new, remove, or re-order scopes. /// </summary> /// <param name="macro">The current macro.</param> /// <param name="capturedScopes">The list of captured scopes.</param> /// <param name="content">The wiki content being parsed.</param> /// <returns>A new list of augmented scopes.</returns> public virtual IList<Scope> Augment(IMacro macro, IList<Scope> capturedScopes, string content) { IList<Scope> augmentedScopes = new List<Scope>(); for (int i = 0; (i + 1) < capturedScopes.Count; i++) { Scope current = capturedScopes[i]; Scope peek = capturedScopes[i + 1]; if (EnsureBlockStarted(i, augmentedScopes, current)) continue; if (EnsureStartingNewBlockWithEndingRow(augmentedScopes, current, peek, content) || EnsureStartingNewBlock(augmentedScopes, current, peek) || EnsureEndingRow(augmentedScopes, current, peek, content)) { i++; continue; } augmentedScopes.Add(current); } EnsureLastScope(capturedScopes, augmentedScopes, content); return augmentedScopes; }
public MacroDto BuildDto(IMacro entity) { var dto = new MacroDto() { Alias = entity.Alias, CacheByPage = entity.CacheByPage, CachePersonalized = entity.CacheByMember, DontRender = entity.DontRender, Name = entity.Name, Python = entity.ScriptPath, RefreshRate = entity.CacheDuration, ScriptAssembly = entity.ControlAssembly, ScriptType = entity.ControlType, UseInEditor = entity.UseInEditor, Xslt = entity.XsltPath, MacroPropertyDtos = BuildPropertyDtos(entity) }; if (entity.HasIdentity) { dto.Id = int.Parse(entity.Id.ToString(CultureInfo.InvariantCulture)); } return(dto); }
/// <summary> /// This will insert new, remove, or re-order scopes. /// </summary> /// <param name="macro">The current macro.</param> /// <param name="capturedScopes">The list of captured scopes.</param> /// <param name="content">The wiki content being parsed.</param> /// <returns>A new list of augmented scopes.</returns> public IList <Scope> Augment(IMacro macro, IList <Scope> capturedScopes, string content) { var augmentedScopes = new List <Scope>(capturedScopes.Count); int insertAt = 0; for (int i = 0; i < capturedScopes.Count; i = i + 2) { Scope begin = capturedScopes[i]; Scope end = capturedScopes[i + 1]; string beginContent = content.Substring(begin.Index, begin.Length); int depth = Utility.CountChars(':', beginContent); for (int j = 0; j < depth; j++) { augmentedScopes.Insert(insertAt, begin); augmentedScopes.Add(end); } insertAt = augmentedScopes.Count; } return(augmentedScopes); }
/// <summary> /// Saves an <see cref="IMacro"/> /// </summary> /// <param name="macro"><see cref="IMacro"/> to save</param> /// <param name="userId">Optional Id of the user deleting the macro</param> public void Save(IMacro macro, int userId = Cms.Core.Constants.Security.SuperUserId) { using (ICoreScope scope = ScopeProvider.CreateCoreScope()) { EventMessages eventMessages = EventMessagesFactory.Get(); var savingNotification = new MacroSavingNotification(macro, eventMessages); if (scope.Notifications.PublishCancelable(savingNotification)) { scope.Complete(); return; } if (string.IsNullOrWhiteSpace(macro.Name)) { throw new ArgumentException("Cannot save macro with empty name."); } _macroRepository.Save(macro); scope.Notifications.Publish(new MacroSavedNotification(macro, eventMessages).WithStateFrom(savingNotification)); Audit(AuditType.Save, userId, -1); scope.Complete(); } }
public MacroPlayer(IMacro macro, WaitHandle stoppedEvent, IElementPlayerClient client) : base(stoppedEvent, client) { m_Macro = macro; State = MacroPlayerState.NotStarted; m_ConditionEvent = new AutoResetEvent(false); }
/// <summary> /// This will insert new, remove, or re-order scopes. /// </summary> /// <param name="macro">The current macro.</param> /// <param name="capturedScopes">The list of captured scopes.</param> /// <param name="content">The wiki content being parsed.</param> /// <returns>A new list of augmented scopes.</returns> public virtual IList <Scope> Augment(IMacro macro, IList <Scope> capturedScopes, string content) { IList <Scope> augmentedScopes = new List <Scope>(); for (int i = 0; (i + 1) < capturedScopes.Count; i++) { Scope current = capturedScopes[i]; Scope peek = capturedScopes[i + 1]; if (EnsureBlockStarted(i, augmentedScopes, current)) { continue; } if (EnsureStartingNewBlockWithEndingRow(augmentedScopes, current, peek, content) || EnsureStartingNewBlock(augmentedScopes, current, peek) || EnsureEndingRow(augmentedScopes, current, peek, content)) { i++; continue; } augmentedScopes.Add(current); } EnsureLastScope(capturedScopes, augmentedScopes, content); return(augmentedScopes); }
public AddMacroCommandAction(IMacro macro, IMacroCommand command) { m_Macro = macro; m_MacroElement = macro.AddElement(command); m_Index = macro.GetElements().Count - 1; macro.RemoveElement(m_MacroElement.Id); }
private static void Parse(string wikiContent, IMacro macro, CompiledMacro compiledMacro, IScopeAugmenter augmenter, Action <IList <Scope> > parseHandler) { Match regexMatch = compiledMacro.Regex.Match(wikiContent); if (!regexMatch.Success) { return; } IList <Scope> capturedScopes = new List <Scope>(); while (regexMatch.Success) { string matchedContent = wikiContent.Substring(regexMatch.Index, regexMatch.Length); if (!string.IsNullOrEmpty(matchedContent)) { capturedScopes = GetCapturedMatches(regexMatch, compiledMacro, capturedScopes, compiledMacro.Regex); } regexMatch = regexMatch.NextMatch(); } if (augmenter != null && capturedScopes.Count > 0) { capturedScopes = augmenter.Augment(macro, capturedScopes, wikiContent); } if (capturedScopes.Count > 0) { parseHandler(capturedScopes); } }
public static IMacro GetReader() { if (Instance == null) Instance = new MacroData(); return Instance; }
/// <summary> /// Creates Macro Source /// </summary> /// <param name="macro">The Macro</param> /// <param name="createDate">The Create Date</param> /// <param name="externalSourceCode">The External Source Code</param> /// <param name="acceleratorName">The Accelerator</param> /// <param name="interval">The Interval</param> /// <param name="mode">The Mode</param> /// <param name="playSeconds">The Play Seconds</param> /// <param name="playTimes">The PLay Times</param> /// <param name="source">The Macro Source</param> public IExternalMacroSource CreateExternalMacroSource(IMacro macro, DateTime createDate, string externalSourceCode, string acceleratorName, string interval, string mode, string playSeconds, string playTimes, string source) { try { if (macro == null) { throw new ArgumentNullException(); } string sql = $" INSERT INTO {SQLiteDataContract.ExternalMacroSource.TABLE_NAME} ( " + $" {SQLiteDataContract.ExternalMacroSource.COLUMN_MACRO_ID_NAME}, " + $" {SQLiteDataContract.ExternalMacroSource.COLUMN_CREATE_DATE_NAME}, " + $" {SQLiteDataContract.ExternalMacroSource.COLUMN_EXTERNAL_SOURCE_CODE_NAME}, " + $" {SQLiteDataContract.ExternalMacroSource.COLUMN_ACCELERATOR_NAME}, " + $" {SQLiteDataContract.ExternalMacroSource.COLUMN_INTERVAL_NAME}, " + $" {SQLiteDataContract.ExternalMacroSource.COLUMN_MODE_NAME}, " + $" {SQLiteDataContract.ExternalMacroSource.COLUMN_PLAY_SECONDS_NAME}, " + $" {SQLiteDataContract.ExternalMacroSource.COLUMN_REPEAT_TIMES_NAME}, " + $" {SQLiteDataContract.ExternalMacroSource.COLUMN_MACRO_SOURCE_NAME} " + $" ) VALUES ( " + $" @macroID, " + $" @createDate, " + $" @externalSourceCode, " + $" @acceleratorName, " + $" @interval, " + $" @mode, " + $" @playSeconds, " + $" @repeatTimes, " + $" @macroSource " + $" ); "; using (var connection = CreateConnection()) { connection.Open(); using (var command = CreateCommand(connection, CommandType.Text, sql)) { command.Parameters.Add(CreateParameter(DbType.Int64, "@macroID", macro.ID)); command.Parameters.Add(CreateParameter(DbType.DateTime, "@createDate", createDate)); command.Parameters.Add(CreateParameter(DbType.String, "@externalSourceCode", externalSourceCode)); command.Parameters.Add(CreateParameter(DbType.String, "@acceleratorName", acceleratorName)); command.Parameters.Add(CreateParameter(DbType.String, "@interval", interval)); command.Parameters.Add(CreateParameter(DbType.String, "@mode", mode)); command.Parameters.Add(CreateParameter(DbType.String, "@playSeconds", playSeconds)); command.Parameters.Add(CreateParameter(DbType.String, "@playTimes", playTimes)); command.Parameters.Add(CreateParameter(DbType.String, "@macroSource", source)); int recordsAffected = command.ExecuteNonQuery(); logger.Info($"Created MacroSource - {recordsAffected} records affected"); long externalMacroSourceID = connection.GetLastInsertedID(); return(GetExternalMacroSourceByID(externalMacroSourceID).FirstOrDefault()); } } } catch (Exception caught) { logger.Error("Unexpected Error Creating MacroSource", caught); throw; } }
/// <summary> /// Delete Macro /// </summary> /// <param name="macro">The Macro</param> public void DeleteMacro(IMacro macro) { try { if (macro == null) { throw new ArgumentNullException("macro"); } string sql = // This deletes the MacroSoruce $" DELETE FROM {SQLServerDataContract.ExternalMacroSource.TABLE_NAME} " + $" WHERE {SQLServerDataContract.ExternalMacroSource.COLUMN_MACRO_ID_NAME} = @macroID; " + // And the Macro. The source shouldn't exist without the header.. you know? $" DELETE FROM {SQLServerDataContract.Macros.TABLE_NAME} " + $" WHERE {SQLServerDataContract.Macros.COLUMN_ID_NAME} = @id; "; using (var connection = CreateConnection()) { connection.Open(); using (var command = CreateCommand(connection, CommandType.Text, sql)) { command.Parameters.Add(CreateParameter(DbType.Int64, "@id", macro.ID)); int recordsAffected = command.ExecuteNonQuery(); logger.Info($"Deleted Macro - {recordsAffected} records affected"); } } } catch (Exception caught) { logger.Error("Unexpected Error Deleting Macro", caught); throw; } }
public XElement Serialize(IMacro macro) { var xml = new XElement("macro"); xml.Add(new XElement("name", macro.Name)); xml.Add(new XElement("alias", macro.Alias)); xml.Add(new XElement("scriptType", macro.ControlType)); xml.Add(new XElement("scriptAssembly", macro.ControlAssembly)); xml.Add(new XElement("scriptingFile", macro.ScriptPath)); xml.Add(new XElement("xslt", macro.XsltPath)); xml.Add(new XElement("useInEditor", macro.UseInEditor.ToString())); xml.Add(new XElement("dontRender", macro.DontRender.ToString())); xml.Add(new XElement("refreshRate", macro.CacheDuration.ToString(CultureInfo.InvariantCulture))); xml.Add(new XElement("cacheByMember", macro.CacheByMember.ToString())); xml.Add(new XElement("cacheByPage", macro.CacheByPage.ToString())); var properties = new XElement("properties"); foreach (var property in macro.Properties) { properties.Add(new XElement("property", new XAttribute("name", property.Name), new XAttribute("alias", property.Alias), new XAttribute("sortOrder", property.SortOrder), new XAttribute("propertyType", property.EditorAlias))); } xml.Add(properties); return(xml); }
public static IStyledMacro ToStyled(this IMacro macro) { if (macro.IsStyled()) { return((IStyledMacro)macro); } return(null); }
public static void RemoveMacroCache(this DistributedCache dc, IMacro macro) { if (macro == null) { return; } dc.RefreshByJson(DistributedCache.MacroCacheRefresherGuid, MacroCacheRefresher.SerializeToJsonPayload(macro)); }
public static void RemoveMacroCache(this DistributedCache dc, IMacro macro) { if (macro == null) { return; } dc.RefreshByJson(MacroCacheRefresher.UniqueId, MacroCacheRefresher.Serialize(macro)); }
/// <summary> /// Gets the entity identifier of the entity. /// </summary> /// <param name="entity">The entity.</param> /// <returns>The entity identifier of the entity.</returns> public static GuidUdi GetUdi(this IMacro entity) { if (entity == null) { throw new ArgumentNullException("entity"); } return(new GuidUdi(Constants.UdiEntityType.Macro, entity.Key).EnsureClosed()); }
///////////////////////////////////////////////////////////////////////////// public virtual IMacro Create( string name, IMacro macro, object instance, bool clone ) { // ****** // // illegal // throw new Exception( "Builtin macro instances can not be copied" ); }
public static bool IsStyled(this IMacro macro) { if (macro is IStyledMacro) { return(true); } return(false); }
public void AddMacro(IMacro macro, string name, int paramNum) { if (!Macros.ContainsKey(name)) { Macros[name] = new Dictionary <int, IMacro>(); } Macros[name][paramNum] = macro; }
/// <summary> /// This changes the macro type to a PartialViewMacro if the SelectedPartialView txt box has a value. /// This then also updates the file path saved for the partial view to be the full virtual path, not just the file name. /// </summary> /// <param name="macro"> </param> /// <param name="macroCachePeriod"></param> /// <param name="macroAssemblyValue"></param> /// <param name="macroTypeValue"></param> protected override void SetMacroValuesFromPostBack(IMacro macro, int macroCachePeriod, string macroAssemblyValue, string macroTypeValue) { base.SetMacroValuesFromPostBack(macro, macroCachePeriod, macroAssemblyValue, macroTypeValue); if (!SelectedPartialView.Text.IsNullOrWhiteSpace()) { macro.ScriptPath = SelectedPartialView.Text; } }
public bool Equals(IMacro other) { if (other is DefineCollectionOptimized.UserDefinedReplacer) { return(this.Equals(other)); } return(false); }
public void Cannot_Save_Macro_With_Empty_Name() { // Arrange IMacro macro = CreateMacro(name: string.Empty); // Act & Assert Assert.Throws <ArgumentException>(() => MacroService.Save(macro)); }
public static void SaveToDisk(IMacro item) { if (item != null) { XElement node = _engine.Macro.Export(item); uSyncIO.SaveXmlToDisk(node, "Macro", item.Alias); } }
public void Can_Get_By_Alias() { // Act IMacro macro = MacroService.GetByAlias("test1"); // Assert Assert.IsNotNull(macro); Assert.AreEqual("Test1", macro.Name); }
private static CompiledMacro CompileMacro(IMacro macro) { Regex regex; IList <string> captures; CompileRules(macro.Rules, out regex, out captures); return(new CompiledMacro(macro.Id, regex, captures)); }
/// <summary> /// This ensures that the SelectedPartialView txt box value is set correctly when the m_macro object's /// ScriptingFile property contains a full virtual path beginning with the MacroPartials path /// </summary> /// <param name="macro"> </param> /// <param name="macroAssemblyValue"></param> /// <param name="macroTypeValue"></param> protected override void PopulateFieldsOnLoad(IMacro macro, string macroAssemblyValue, string macroTypeValue) { base.PopulateFieldsOnLoad(macro, macroAssemblyValue, macroTypeValue); //check if the ScriptingFile property contains the MacroPartials path if (macro.ScriptPath.IsNullOrWhiteSpace() == false && (macro.ScriptPath.StartsWith(SystemDirectories.MvcViews + "/MacroPartials/") || (Regex.IsMatch(macro.ScriptPath, "~/App_Plugins/.+?/Views/MacroPartials", RegexOptions.Compiled)))) { macroPython.Text = ""; SelectedPartialView.Text = macro.ScriptPath; } }
/// <summary> /// Will compile a new <see cref="IMacro"/> or return a previously cached <see cref="CompiledMacro"/>. /// </summary> /// <param name="macro">The macro to compile.</param> /// <returns>The compiled macro.</returns> public virtual CompiledMacro Compile(IMacro macro) { Guard.NotNull(macro, "macro"); Guard.NotNullOrEmpty(macro.Id, "macro", "The macro identifier must not be null or empty."); try { // for performance sake, // we'll initially use only a read lock compileLock.EnterReadLock(); CompiledMacro compiledMacro; if (compiledMacros.TryGetValue(macro.Id, out compiledMacro)) return compiledMacro; } finally { compileLock.ExitReadLock(); } // this is assuming the compiled macro was not found // and will attempt to compile it. compileLock.EnterUpgradeableReadLock(); try { if (compiledMacros.ContainsKey(macro.Id)) return compiledMacros[macro.Id]; compileLock.EnterWriteLock(); try { if (compiledMacros.ContainsKey(macro.Id)) return compiledMacros[macro.Id]; Guard.NotNullOrEmpty(macro.Rules, "macro", "The macro rules must not be null or empty."); CompiledMacro compiledMacro = CompileMacro(macro); compiledMacros[macro.Id] = compiledMacro; return compiledMacro; } finally { compileLock.ExitWriteLock(); } } finally { compileLock.ExitUpgradeableReadLock(); } }
public void ProcessMacroBegin( int id, IMacro macro, IMacroArguments macroArgs, bool postProcess ) { if( lastDoneId != lastBeginId ) { // // macros are being called recursivly // sb.AppendLine(); } sbIndent(); sb.AppendFormat( "{0}\n", macro.Name ); lastBeginId = id; ++callDepth; }
/// <summary> /// constructor /// </summary> public VM_Presentation() { InitializeComponent(); local("VM_Presentation_" + Thread.CurrentThread.CurrentCulture + ".xml"); PluginManager.OqatToggleView += this.onToggleView; PluginManager.videoLoad += this.onVideoLoad; //init macro macro = PluginManager.pluginManager.getPlugin<IMacro>("Macro"); this._custom = new List<IPresentation>(); this.gridPlayer1.Children.Add(playerProc.propertyView); this.gridPlayer2.Children.Add(playerRef.propertyView); this.otherPanel.Children.Add(diagram.propertyView); this.gridMacro.Children.Add(macro.propertyView); }
///////////////////////////////////////////////////////////////////////////// public string ProcessForLoop( IMacro target, int start, int end, int increment, object [] extraArgs ) { // ****** if( 0 == increment ) { ThreadContext.MacroError( "#forloop increment value ({0}) must not be zero.", increment ); } else if( increment > 0 && end < start ) { ThreadContext.MacroWarning( "#forloop end value is less than start value (start: {0} end: {1} increment: {2}).", start, end, increment ); } else if( increment < 0 && start < end ) { ThreadContext.MacroWarning( "#forloop start value is less than end value (start: {0} end: {1} increment: {2}).", start, end, increment ); } // ****** StringBuilder sb = new StringBuilder(); // ****** object [] argsToMacro = new object[3 + extraArgs.Length ]; AddExtraArgs( 3, argsToMacro, extraArgs ); // ****** MacroExpression expression = ETB.CreateMacroCallExpression( target, argsToMacro ); // ****** argsToMacro[ 1 ] = end; argsToMacro[ 2 ] = increment; for( int counter = start; ; counter += increment ) { if( increment > 0 && counter > end ) { break; } else if( increment < 0 && counter < end ) { break; } // ****** // // `index', `lastIndex', `increment' [, extras ...] // argsToMacro[ 0 ] = counter; sb.Append( mp.InvokeMacro(target, expression, true) ); } // ****** return sb.ToString(); }
/// <summary> /// This will insert new, remove, or re-order scopes. /// </summary> /// <param name="macro">The current macro.</param> /// <param name="capturedScopes">The list of captured scopes.</param> /// <param name="content">The wiki content being parsed.</param> /// <returns>A new list of augmented scopes.</returns> public IList<Scope> Augment(IMacro macro, IList<Scope> capturedScopes, string content) { IList<Scope> newScopes = new List<Scope>(); string firstScopeContent = content.Substring(capturedScopes[0].Index, capturedScopes[0].Length); char depthChar = GetDepthChar(firstScopeContent); int startLevel = Utility.CountChars(depthChar, firstScopeContent); AugmentRecursively(content, capturedScopes, newScopes, 0, startLevel, startLevel, depthChar); // add the ending block scope as it was intentionally skipped Scope lastScope = capturedScopes[capturedScopes.Count - 1]; // add the last scope as it was explicitly excluded newScopes.Add(new Scope(GetEndScope(newScopes), lastScope.Index, lastScope.Length)); return newScopes; }
///////////////////////////////////////////////////////////////////////////// public void ProcessMacroDone( int id, IMacro macro, bool postProcessed, bool diverted, object macroResult, object finalResult ) { --callDepth; lastDoneId = id; // ****** string result = string.Empty; if( null != finalResult ) { result = finalResult.ToString(); if( result.Length > 64 ) { result = result.Substring( 0, 64 ) + " ..."; } result = result.Replace( "\n", " " ); } // ****** sbIndent(); sb.AppendFormat( "{0} result: {1}\n", macro.Name, result ); sb.AppendLine(); }
public void Initialize() { shimContext = ShimsContext.Create(); var project = new ShimProject(); project.NameGet = () => "TestProject"; ShimQueryItem.AllInstances.ProjectGet = (q) => project; var definition = new ShimQueryDefinition(); projectMacroMock = A.Fake<IMacro>(); A.CallTo(() => projectMacroMock.Name).Returns("Project"); A.CallTo(() => projectMacroMock.GetValue(A<QueryDefinition>.Ignored)).Returns("\"TestProject\""); userMacroMock = A.Fake<IMacro>(); A.CallTo(() => userMacroMock.Name).Returns("Me"); A.CallTo(() => userMacroMock.GetValue(A<QueryDefinition>.Ignored)).Returns("\"Iñaki Elcoro\""); parserWithMacros = new MacroParser(new IMacro[] { projectMacroMock, userMacroMock }); }
///////////////////////////////////////////////////////////////////////////// public string ForeachObjectMacro( IMacro target, object objToEnumerate, object [] extraArgs ) { // ****** int itemsCount; IEnumerable items = GetIterableObject( objToEnumerate, out itemsCount ); // ****** StringBuilder sb = new StringBuilder(); // ****** object [] argsToMacro = new object[ 5 + extraArgs.Length ]; AddExtraArgs( 5, argsToMacro, extraArgs ); // ****** MacroExpression expression = ETB.CreateMacroCallExpression( target, argsToMacro ); // ****** int itemsLastIndex = itemsCount > 0 ? itemsCount - 1 : -1; int index = 0; foreach( object item in items ) { // // list: `value', `index', `lastIndex', `count', `type' // argsToMacro[ 0 ] = item; argsToMacro[ 1 ] = index++; argsToMacro[ 2 ] = itemsLastIndex; argsToMacro[ 3 ] = itemsCount; argsToMacro[ 4 ] = item.GetType(); // ****** sb.Append( mp.InvokeMacro( target, expression, true) ); } // ****** return sb.ToString(); }
/// <summary> /// This will insert new, remove, or re-order scopes. /// </summary> /// <param name="macro">The current macro.</param> /// <param name="capturedScopes">The list of captured scopes.</param> /// <param name="content">The wiki content being parsed.</param> /// <returns>A new list of augmented scopes.</returns> public IList<Scope> Augment(IMacro macro, IList<Scope> capturedScopes, string content) { var augmentedScopes = new List<Scope>(capturedScopes.Count); int insertAt = 0; for (int i = 0; i < capturedScopes.Count; i = i + 2) { Scope begin = capturedScopes[i]; Scope end = capturedScopes[i + 1]; string beginContent = content.Substring(begin.Index, begin.Length); int depth = Utility.CountChars(':', beginContent); for (int j = 0; j < depth; j++) { augmentedScopes.Insert(insertAt, begin); augmentedScopes.Add(end); } insertAt = augmentedScopes.Count; } return augmentedScopes; }
/// <summary> /// Returns an enum <see cref="MacroTypes"/> based on the properties on the Macro /// </summary> /// <returns><see cref="MacroTypes"/></returns> internal static MacroTypes GetMacroType(IMacro macro) { if (string.IsNullOrEmpty(macro.XsltPath) == false) return MacroTypes.Xslt; if (string.IsNullOrEmpty(macro.ScriptPath) == false) { //we need to check if the file path saved is a virtual path starting with ~/Views/MacroPartials, if so then this is //a partial view macro, not a script macro //we also check if the file exists in ~/App_Plugins/[Packagename]/Views/MacroPartials, if so then it is also a partial view. return (macro.ScriptPath.InvariantStartsWith(SystemDirectories.MvcViews + "/MacroPartials/") || (Regex.IsMatch(macro.ScriptPath, "~/App_Plugins/.+?/Views/MacroPartials", RegexOptions.Compiled | RegexOptions.IgnoreCase))) ? MacroTypes.PartialView : MacroTypes.Script; } if (string.IsNullOrEmpty(macro.ControlType) == false && macro.ControlType.InvariantContains(".ascx")) return MacroTypes.UserControl; if (string.IsNullOrEmpty(macro.ControlType) == false && string.IsNullOrEmpty(macro.ControlAssembly) == false) return MacroTypes.CustomControl; return MacroTypes.Unknown; }
///////////////////////////////////////////////////////////////////////////// public IMacro Create( string name, IMacro macro, object instance, bool clone ) { return mp.CreateObjectMacro( name, macro.MacroObject ); }
private static void Parse(string wikiContent, IMacro macro, CompiledMacro compiledMacro, IScopeAugmenter augmenter, Action<IList<Scope>> parseHandler) { Match regexMatch = compiledMacro.Regex.Match(wikiContent); if (!regexMatch.Success) return; IList<Scope> capturedScopes = new List<Scope>(); while (regexMatch.Success) { string matchedContent = wikiContent.Substring(regexMatch.Index, regexMatch.Length); if (!string.IsNullOrEmpty(matchedContent)) capturedScopes = GetCapturedMatches(regexMatch, compiledMacro, capturedScopes, compiledMacro.Regex); regexMatch = regexMatch.NextMatch(); } if (augmenter != null && capturedScopes.Count > 0) capturedScopes = augmenter.Augment(macro, capturedScopes, wikiContent); if (capturedScopes.Count > 0) parseHandler(capturedScopes); }
///////////////////////////////////////////////////////////////////////////// // // (#Deflist `macroName' ) // ///////////////////////////////////////////////////////////////////////////// public override object Evaluate( IMacro macro, IMacroArguments macroArgs ) { // ****** var args = GetMacroArgsAsTuples( macroArgs.Expression ) as NmpTuple<string, bool>; string macroName = args.Item1; bool trimLines = args.Item2; // ****** if( string.IsNullOrEmpty(macroName) ) { ThreadContext.MacroError( "attempt to define or pushdef a macro without a name" ); } // ****** // // parse text into NmpArray instance // var list = new NmpStringList( macroArgs.BlockText, trimLines ); // ****** // // create the new macro // IMacro newMacro = mp.AddObjectMacro( macroName, list ); // ****** return string.Empty; }
///////////////////////////////////////////////////////////////////////////// public virtual object Evaluate( IMacro macro, IMacroArguments macroArgs ) { // ****** var oee = new ExpressionEvaluator( mp ); return oee.Evaluate( macro, macroArgs.Expression ); }
/// <summary> /// Deletes an <see cref="IMacro"/> /// </summary> /// <param name="macro"><see cref="IMacro"/> to delete</param> /// <param name="userId">Optional id of the user deleting the macro</param> public void Delete(IMacro macro, int userId = 0) { if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs<IMacro>(macro), this)) return; var uow = _uowProvider.GetUnitOfWork(); using (var repository = _repositoryFactory.CreateMacroRepository(uow)) { repository.Delete(macro); uow.Commit(); Deleted.RaiseEvent(new DeleteEventArgs<IMacro>(macro, false), this); } Audit.Add(AuditTypes.Delete, "Delete Macro performed by user", userId, -1); }
///////////////////////////////////////////////////////////////////////////// public static MacroExpression CreateMacroCallExpression( IMacro macro, object [] args ) { // ****** if( null == macro ) { throw new ArgumentNullException( "macro" ); } // ****** var argList = new ArgumentList( null == args ? new object [0] : args ); var list = new MacroExpression( new NmpStringList() ); // ****** if( MacroType.Builtin == macro.MacroType || MacroType.Text == macro.MacroType ) { list.Add( new MethodCallExpression( macro.Name, argList) ); } else { // // its an object, if it's not a MethodInvoker instance or a delegate // it will error when the invocation fails // list.Add( new UnnamedMemberAccessExpression(macro.Name) ); list.Add( new UnnamedMethodCallExpression(argList) ); } // ****** return list; }
public bool Equals(IMacro other) { return this.GetType() == other.GetType(); }
///////////////////////////////////////////////////////////////////////////// public object Evaluate( IMacro macro, Expression exp ) { return Evaluate( macro.MacroObject, exp ); }
/// <summary> /// Removes the cache amongst servers for a macro item /// </summary> /// <param name="dc"></param> /// <param name="macro"></param> public static void RemoveMacroCache(this DistributedCache dc, IMacro macro) { if (macro != null) { dc.RefreshByJson(new Guid(DistributedCache.MacroCacheRefresherId), MacroCacheRefresher.SerializeToJsonPayload(macro)); } }
///////////////////////////////////////////////////////////////////////////// public override object Evaluate( IMacro macro, IMacroArguments macroArgs ) { // ****** if( 0 == macroArgs.BlockText.Length ) { return string.Empty; } // ****** string text = string.Empty; // // run the contents of the block through the scanner // text = macroArgs.BlockText; int hash = text.GetHashCode(); var scanner = mp.Get<IScanner>(); for( int i = 0; i < 128; i++ ) { text = scanner.Scanner( text, string.Format( "ExpandoBlock_{0}", i ) ); int newHash = text.GetHashCode(); if( hash == newHash ) { ///ThreadContext.WriteLine( "exit eval block on iteration {0}", i ); break; } hash = newHash; } // ****** return text; }
private static bool MacroHasProperty(IMacro macroObject, string propertyAlias) { return macroObject.Properties.Any(mp => mp.Alias.ToLower() == propertyAlias); }
private static CompiledMacro CompileMacro(IMacro macro) { Regex regex; IList<string> captures; CompileRules(macro.Rules, out regex, out captures); return new CompiledMacro(macro.Id, regex, captures); }
///////////////////////////////////////////////////////////////////////////// public MacroArguments( IMacro macro, IInput input, MacroExpression macroExp, NmpStringList specialArgs = null, string blockText = "" ) { // ****** if( null == input ) { throw new ArgumentNullException( "input" ); } Input = input; // ****** Expression = macroExp; // ****** Options = new MacroOptions( macro.MacroProcessor, macro.Flags, macroExp.MacroInstructions ); // ****** SpecialArgs = null == specialArgs ? new NmpStringList() : specialArgs; BlockText = blockText; }
///////////////////////////////////////////////////////////////////////////// private void DumpDefFormat( StringBuilder sb, IMacro macro ) { // ****** string text = string.Empty; //StringBuilder sb = new StringBuilder(); // ****** if( MacroType.Text == macro.MacroType ) { text = macro.MacroText; } else if( MacroType.Builtin == macro.MacroType ) { text = string.Format( "Builting macro: {0}", macro.Name ); } else { object obj = macro.MacroObject; if( null == obj ) { text = "null macro object"; } else { text = obj.ToString(); } } sb.AppendLine(); sb.AppendLine( "*****************************************************************************" ); sb.AppendFormat( "dumpdef \"{0}\", MacroType is {1}: (begins two lines down)\n\n", macro.Name, macro.MacroType ); // sb.AppendLine( "*****************************************************************************" ); // sb.AppendLine( "-----------------------------------------------------------------------------" ); sb.AppendLine( text ); sb.AppendLine( "*****************************************************************************" ); // return sb; }
public bool Equals(IMacro other) { return other.GetType() == typeof(Switch); }