public DefaultProcessingEngine(IShellContextFactory shellContextFactory, Func<IOrchardHost> orchardHost) { _shellContextFactory = shellContextFactory; _orchardHost = orchardHost; _entries = new ContextState<IList<Entry>>("DefaultProcessingEngine.Entries", () => new List<Entry>()); }
public DefaultProcessingEngine(IShellContextFactory shellContextFactory, Func<ICoeveryHost> coeveryHost) { _shellContextFactory = shellContextFactory; _coeveryHost = coeveryHost; _entries = new ContextState<IList<Entry>>("DefaultProcessingEngine.Entries", () => new List<Entry>()); }
public DefaultLifetimeScopeAccessor(ILifetimeScope rootContainer) { Guard.ArgumentNotNull(() => rootContainer); //rootContainer.ChildLifetimeScopeBeginning += OnScopeBeginning; this._rootContainer = rootContainer; this._state = new ContextState<ILifetimeScope>("CustomLifetimeScopeProvider.WorkScope"); }
public DefaultHost(IExtensionLoaderCoordinator extensionLoaderCoordinator, ICacheManager cacheManager, IHostLocalRestart hostLocalRestart, IExtensionMonitoringCoordinator extensionMonitoringCoordinator, IShellSettingsManager shellSettingsManager, IShellContextFactory shellContextFactory) { _extensionLoaderCoordinator = extensionLoaderCoordinator; _cacheManager = cacheManager; _hostLocalRestart = hostLocalRestart; _extensionMonitoringCoordinator = extensionMonitoringCoordinator; _shellSettingsManager = shellSettingsManager; _shellContextFactory = shellContextFactory; _tenantsToRestart = new ContextState<IList<ShellSettings>>("DefaultHost.TenantsToRestart", () => new List<ShellSettings>()); Logger = NullLogger.Instance; }
private async Task HandleStopAsync() { _state = ContextState.Stopping; //this is intentional await InvokeUserMessageAsync(Stopping.Instance); if (_children != null) { foreach (var child in _children) { child.Stop(); } } await TryRestartOrTerminateAsync(); }
protected void btnAdd_ServerClick(object sender, EventArgs e) { _repository = new EmployeeRepository(); ContextState contextStateOb = _repository.AddEducationalQualification(txtEducationalQualificationName.Value); if (contextStateOb.State) { Response.Write("Employee has been added sucssefly."); } else { Response.Write(contextStateOb.ErrorMessage); } }
public object Construct(ObjectReferenceContext context) { ContextState contextState = context.SaveState(); bool fieldHasValue = ContainingClass().SeekToField(context, this); try { return(((IObjectConstructor)_translator).OnInstantiate(context.Container(), fieldHasValue ? Read(context) : null)); } finally { context.RestoreState(contextState); } }
public void TrackMatch(MatchInfo match) { if (this.contextState == ContextState.CollectPost) { this.UpdateQueue(); } this.matchInfo = match; if (this.postContext > 0) { this.contextState = ContextState.CollectPost; } else { this.UpdateQueue(); } }
//Last and final termination step private async Task FinalizeStopAsync() { ProcessRegistry.Instance.Remove(Self); //This is intentional await InvokeUserMessageAsync(Stopped.Instance); DisposeActorIfDisposable(); //Notify watchers _extras?.Watchers.SendSystemNessage(Terminated.From(Self)); //Notify parent Parent?.SendSystemMessage(Terminated.From(Self)); _state = ContextState.Stopped; }
protected void btnAdd_ServerClick(object sender, EventArgs e) { _repository = new EmployeeRepository(); ContextState contextStateOb = _repository.AddEmployee(txtNationalID.Value, txtName.Value, txtBirthDate.Value, txtAddress.Value, txtPhoneNumber.Value, txtPhoto.Value, txtHireDate.Value, txtJoinDate.Value, employeeEducationList.Value, txtSubscriptionFee.Value, subscriptionFeeYears.Value); if (contextStateOb.State) { //Response.Write("Employee has been added sucssefly."); Response.Redirect("~/Views/Employee/list.aspx"); } else { Response.Write(contextStateOb.ErrorMessage); } }
public Doc FindDocumentById(Guid docId, IContext context) { ContextState prev = this; while (prev != null) { if (prev is IDocumentContextState) { var document = ((IDocumentContextState)prev).GetDocument(context); if (document != null && document.Id == docId) { return(document); } } prev = prev.Previous; } return(null); }
void _chat_LoginOKEvent(Vha.Net.Chat chat, EventArgs e) { // Prevent duplicate events if (this._state == ContextState.Connected) { return; } // Update state ContextState previousState = this._state; this._state = ContextState.Connected; // This tastes like more this._chat.AutoReconnect = true; // Notify state change if (this.StateEvent != null) { this.StateEvent(this, new StateEventArgs(this._state, previousState)); } }
public override bool Equals(object obj) { if (obj == this) { return(true); } ContextState other = obj as ContextState; if (other == null) { return(false); } return(this.ContextWordEnd == other.ContextWordEnd && this.RepeatWordEnd == other.RepeatWordEnd && this.RepeatCount == other.RepeatCount && base.Equals(other)); }
public void ActivateAspects(UnmarshallingContext context) { BooleanByRef schemaUpdateDetected = new BooleanByRef(); ContextState savedState = context.SaveState(); ITraverseAspectCommand command = new _MarshallingInfoTraverseAspectCommand_63(context , schemaUpdateDetected, EnsureFieldList(context)); // TODO: cant the aspect handle it itself? // Probably no because old aspect versions might not be able // to handle null... TraverseAllAspects(context, command); if (schemaUpdateDetected.value) { context.RestoreState(savedState); command = new _MarshallingInfoTraverseAspectCommand_94(context, EnsureFieldList(context )); TraverseAllAspects(context, command); } }
public ActionContext( string contextGroupName = "default", [CallerMemberName] string name = null, ActionContextSettings settings = null, IEnumerable <ISanitizer> logSanitizers = null) { _stopwatch = new Stopwatch(); _stopwatch.Start(); _parent = _namedContexts.GetOrAdd(contextGroupName, new AsyncLocal <ActionContext>()).Value; _namedContexts[contextGroupName].Value = this; ContextName = name; ContextGroupName = contextGroupName; if (IsRoot) { Settings = settings ?? new ActionContextSettings(); Depth = 0; State = new ContextState(logSanitizers); Logger = new ContextLogger(this); } else { Settings = _parent.Settings; Depth = _parent.Depth + 1; State = _parent.State; Logger = _parent.Logger; Logger.TrySetContext(this); } var shouldSuppressStartMessage = !IsRoot && Settings.SuppressChildContextStartMessages; var shouldAlwaysShowStart = Settings.EnableContextStartMessage && !shouldSuppressStartMessage; Logger.Log(Settings.ContextStartMessageLevel, $"Context {ContextName} has started.", !shouldAlwaysShowStart); Loaded?.Invoke(this); }
private void OnActivePageStateChanged(ContextState state) { if (active_page == null || !pane_pages.ContainsKey(active_page)) { return; } if (state == ContextState.NotLoaded) { notebook.CurrentPage = notebook.PageNum(no_active); } else if (state == ContextState.Loading) { notebook.CurrentPage = notebook.PageNum(loading); } else if (state == ContextState.Loaded) { notebook.CurrentPage = notebook.PageNum(pane_pages[active_page]); } }
private void SetCCowIcon(ContextState state) { switch (state) { case ContextState.Broken: pictureBoxCcowStatus.Image = Resources.Broken; //pictureBoxCcowStatus.ToolTipText = "Broken"; break; case ContextState.Changing: pictureBoxCcowStatus.Image = Resources.Changing; //toolStripStatusLabelConnection.ToolTipText = "Changing"; break; case ContextState.Linked: pictureBoxCcowStatus.Image = Resources.Linked; //toolStripStatusLabelConnection.ToolTipText = "Linked"; break; } }
static API() { PluginManager = new PluginManager(); UiElements = new ContextUiElements(); State = new ContextState(); Content = new XnaContent(); FrameDrawer = new FrameDrawer(); PluginConfig = new PluginConfig( new DirectoryInfo( Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Demoder.PlanetMapViewer") ) ); XmlCache = new XmlCacheWrapper( new DirectoryInfo( Path.Combine( Demoder.Common.Misc.MyTemporaryDirectory, "XmlCache"))); }
private void DoStart() { LoadConfiguration(); LoadLayout(); DownHandler = new RawKeyEventHandler(KListener_KeyDown); UpHandler = new RawKeyEventHandler(KListener_KeyUp); Context = new ContextState { LastCombinationKeys = new List <KeyPressInfo>(), NextUpKeyToIgnore = null }; KListener = new KeyboardListener(); KListener.KeyDown += DownHandler; KListener.KeyUp += UpHandler; if (Settings.UseScrollLock && !IsActive) { Activate(); } }
public DefaultOrchardHost( IShellContextFactory shellContextFactory, IRunningShellTable runningShellTable, IProcessingEngine processingEngine, IExtensionLoaderCoordinator extensionLoaderCoordinator, IExtensionMonitoringCoordinator extensionMonitoringCoordinator, ICacheManager cacheManager, IShellSettingsManager shellSettingsManager, IHostLocalRestart hostLocalRestart) { _shellContextFactory = shellContextFactory; _extensionLoaderCoordinator = extensionLoaderCoordinator; _extensionMonitoringCoordinator = extensionMonitoringCoordinator; _cacheManager = cacheManager; _runningShellTable = runningShellTable; _hostLocalRestart = hostLocalRestart; _processingEngine = processingEngine; _shellSettingsManager = shellSettingsManager; Logger = NullLogger.Instance; _tenantsToRestart = new ContextState <IList <ShellSettings> >("DefaultOrchardHost.TenantsToRestart", () => new List <ShellSettings>()); }
public ActionResult SendFile() { try { var process = Check <RunProcess>(); if (process.ProcessContext != null) { ContextState prev = process; if (process.ProcessContext.DownloadFiles != null && process.ProcessContext.DownloadFiles.Count > 0) { var downloadFile = process.ProcessContext.DownloadFiles[0]; /* * // CANCELLED:TODO Добавить переход на следующее действие в текущем процессе * // Set(process.Previous); // ?? * * var ext = Path.GetExtension(downloadFile.FileName); * return File(downloadFile.Data, "application/" + ext, downloadFile.FileName);*/ return(RedirectTo(new SendFile(this, prev, downloadFile.FileName, downloadFile.Data))); } var fileName = process.ProcessContext.TemplateFileName ?? "UnnamedFile" + DateTime.Today.ToString("yyyy-mm-dd"); /*var wm = GetWorkflowProxy(); * process.Continue(wm.Proxy); * if (process.ProcessContext != null && process.ProcessContext.State == WorkflowRuntimeState.Finish) * prev = process.Previous;*/ return(RedirectTo(new SendFile(this, prev, fileName))); } return(ThrowException(Process.ProcessContextNotFound)); } catch (Exception e) { return(RedirectTo(new ExceptionState(this, e.Message))); } }
public DefaultOrchardHost( IShellSettingsManager shellSettingsManager, IShellContextFactory shellContextFactory, IRunningShellTable runningShellTable, IProcessingEngine processingEngine, IExtensionLoaderCoordinator extensionLoaderCoordinator, IExtensionMonitoringCoordinator extensionMonitoringCoordinator, ICacheManager cacheManager, IHostLocalRestart hostLocalRestart ) { _shellSettingsManager = shellSettingsManager; _shellContextFactory = shellContextFactory; _runningShellTable = runningShellTable; _processingEngine = processingEngine; _extensionLoaderCoordinator = extensionLoaderCoordinator; _extensionMonitoringCoordinator = extensionMonitoringCoordinator; _cacheManager = cacheManager; _hostLocalRestart = hostLocalRestart; _tenantsToRestart = new ContextState<IList<ShellSettings>>("DefaultOrchardHost.TenantsToRestart", () => new List<ShellSettings>()); T = NullLocalizer.Instance; Logger = NullLogger.Instance; }
public ActionResult RunProcess(Guid id, Guid menuId) { ContextState state = Find <RunProcess>(); if (state != null) { return(RedirectTo( new AskForm(this, Resources.Home.ConfirmProcessTerminationToStartOther /*"Вы уверены, что хотите прервать процесс(ы) и запустить другой процесс?"*/, new ContextAction("Home", "ForceToRunProcess", new { id, menuId }), null))); } try { state = FindCheck <MainForm>(); Set(state); return(RedirectToAction("Run", "Process", new { id, docId = (Guid?)null, menuId })); } catch (Exception e) { return(ThrowException(e)); } }
public ActionResult ShowFilterList(Guid id, Guid docStateId, Guid menuId) { try { ContextState state = Find <RunProcess>(); if (state != null) { return(RedirectTo( new AskForm(this, Resources.Home.ConfirmProcessTerminationToOpenForm /*"Вы уверены, что хотите прервать процесс(ы) и открыть форму?"*/, new ContextAction("Home", "ForceToShowFilterList", new { id, docStateId, menuId }), null))); } state = FindCheck <MainForm>(); Set(state); return(RedirectToAction("ShowFilterList", "Form", new { id, docStateId, menuId, noLoad = true })); } catch (Exception e) { return(ThrowException(e)); } }
/// <summary> /// Starts the context. Note: You can only call this method once per Context. /// </summary> public void Start() { AssertState(ContextState.Created); lock (_contextMutex) { AssertState(ContextState.Created); injectionProviders.Add(new ContextInjectionProvider()); injectionProviders.Add(new ComponentInjectionProvider()); componentLifecycleProcessors.Add(new NotifyingComponentLifecycleProcessor()); State = ContextState.Starting; foreach (ComponentDescriptor descriptor in descriptorTypeCache.Values) { GetInstance(descriptor); } State = ContextState.Started; } }
/// <summary> /// Switches the right click menu state, enabling/disabling the right buttons matching that state /// </summary> /// <param name="newState">The new state detemining what buttons are active/disabled</param> public void SwitchState(ContextState newState) { state = newState; //Start by disabling all buttons but disablig their interactibility foreach (Button button in allButtons) { button.interactable = false; } //Now only active the buttons that should be active in this new state foreach (StateButtons stateButtons in buttonsAvailableOnState) { if (state == stateButtons.state) { foreach (Button button in stateButtons.activeButtons) { button.interactable = true; } return; } } }
public void saveState() { mLastState = mState; }
public void Handle(IComparable version, IProjectChangeDescription projectChange, ContextState state, IProjectLogger logger) { Requires.NotNull(version, nameof(version)); Requires.NotNull(projectChange, nameof(projectChange)); Requires.NotNull(logger, nameof(logger)); VerifyInitialized(); if (projectChange.Difference.ChangedProperties.Contains(ConfigurationGeneral.MSBuildProjectFullPathProperty) && projectChange.After.Properties.TryGetValue(ConfigurationGeneral.MSBuildProjectFullPathProperty, out string projectFilePath)) { string displayName = GetDisplayName(projectFilePath); logger.WriteLine("DisplayName: {0}", displayName); logger.WriteLine("ProjectFilePath: {0}", projectFilePath); Context.ProjectFilePath = projectFilePath; Context.DisplayName = displayName; } }
public void Handle(IComparable version, BuildOptions added, BuildOptions removed, ContextState state, IProjectDiagnosticOutputService logger) { Requires.NotNull(version, nameof(version)); Requires.NotNull(added, nameof(added)); Requires.NotNull(removed, nameof(removed)); Requires.NotNull(logger, nameof(logger)); VerifyInitialized(); foreach (Lazy <Action <string, BuildOptions, BuildOptions>, IOrderPrecedenceMetadataView> value in CommandLineNotifications) { value.Value(Context.BinOutputPath, added, removed); } }
public NewDocForm(IContext context, ContextState previous, Guid formId) : base(context, previous, formId) { // _docManager = context.GetDocManager(); // _presentationManager = context.GetPresentationManager(); }
private void ctxDelete_Click(object sender, System.EventArgs e) { nodeToOperateList = GetOperateNode(objSender); if (nodeToOperateList == null) return; DeleteNode(nodeToOperateList); ctxState = ContextState.CTX_READY; }
static API() { State = new ContextState(); }
/// <summary> /// Disposes the request. If required, a disposition frame is sent to /// the peer to acknowledge the message. /// </summary> /// <param name="deliveryState">The delivery state to send.</param> protected void Dispose(DeliveryState deliveryState) { this.Link.DisposeMessage(this.Message, deliveryState, true); this.state = ContextState.Completed; }
public void Handle(IComparable version, BuildOptions added, BuildOptions removed, ContextState state, IProjectLogger logger) { Requires.NotNull(version, nameof(version)); Requires.NotNull(added, nameof(added)); Requires.NotNull(removed, nameof(removed)); Requires.NotNull(logger, nameof(logger)); VerifyInitialized(); foreach (CommandLineSourceFile additionalFile in removed.AdditionalFiles) { string fullPath = _project.MakeRooted(additionalFile.Path); RemoveFromContextIfPresent(fullPath, logger); } foreach (CommandLineSourceFile additionalFile in added.AdditionalFiles) { string fullPath = _project.MakeRooted(additionalFile.Path); AddToContextIfNotPresent(fullPath, state.IsActiveEditorContext, logger); } }
public ShowMessage(IContext context, ContextState previous, string message, IList <UserAction> userActions = null) : base(context, previous) { Message = message; UserActions = userActions; }
public ShowSelectForm(IContext context, ContextState previous, Guid formId, IList <BizControl> controls, IList <UserAction> userActions = null) : base(context, previous, formId, controls, userActions) { }
public InvalidContextStateException(ContextState expectedState, ContextState currentState) : base("Expected: " + expectedState + ", but current state is: " + currentState) { }
private void OnActivePageStateChanged (ContextState state) { if (active_page == null || !pane_pages.ContainsKey (active_page)) { return; } if (state == ContextState.NotLoaded) notebook.CurrentPage = notebook.PageNum (no_active); else if (state == ContextState.Loading) notebook.CurrentPage = notebook.PageNum (loading); else if (state == ContextState.Loaded) notebook.CurrentPage = notebook.PageNum (pane_pages[active_page]); }
/// <summary> /// Initializes a context object. /// </summary> /// <param name="link">The link where the message was received.</param> /// <param name="message">The received message.</param> protected Context(ListenerLink link, Message message) { this.Link = link; this.Message = message; this.state = ContextState.Active; }
internal void SetState(ContextState state) { State = state; }
private static string Scripted(string code, ContextState state, bool isAtomic) { if(state == ContextState.None) { code = "{{" + code + "}}"; } else if(!isAtomic) { DekiScriptExpression expr = SafeParse(code); if((expr == null) || (expr is DekiScriptBinary) || (expr is DekiScriptTernary)) { code = "(" + code + ")"; } } return code; }
private void IncarnateActor() { _state = ContextState.Alive; Actor = _props.Producer(); }
private void ctxCut_Click(object sender, System.EventArgs e) { //Save the node that currently clicked to cut nodeToOperateList = GetOperateNode(objSender); //Not null is required if (nodeToOperateList == null) return; //Change state ctxState = ContextState.CTX_CUT; }
public void restoreState() { mState = mLastState; mLastState = new ContextState(); }
public void SetState(ContextState state) { State = state; }
private void ctxPaste_Click(object sender, System.EventArgs e) { if (nodeToOperateList == null) return; //Get node to operate AIONode [] destNodes = ((AIONode[])GetOperateNode(objSender)); if (destNodes == null) { if (objSender.Equals(listView1)) //Neu ListView khong select { destNodes = ((AIONode[])GetOperateNode(treeView1)); //Sau khi lay o tree, destNode luon la mot thu muc } else return; } else if (destNodes[0].data.isFile) { //Change destNode to current category in treeView destNodes = ((AIONode[])GetOperateNode(treeView1)); if (destNodes == null) return; } if (destNodes.Length > 1) { MessageBox.Show("Paste into " + destNodes[0].data.Name); } AIONode destNode = destNodes[0]; //Loop through operate node for (int i = 0;i<nodeToOperateList.Length;i++) { AIONode nodeToOperate = nodeToOperateList[i]; //Checking if (!tree.IsValidMoveCopy(nodeToOperate, destNode)) { //continue; return; } if (nodeToOperate.data.isFile == false && nodeToOperate.container == null) { CreateContainerNode(nodeToOperate); } } switch (ctxState) { case ContextState.CTX_CUT: MoveNode(nodeToOperateList, destNode); break; case ContextState.CTX_COPY: CopyNode(nodeToOperateList, destNode); break; } //Change the state to READY when done ctxState = ContextState.CTX_READY; }
private static void Convert(Site site, XDoc doc, bool isTemplate, XmlNode node, ContextState state, XmlNamespaceManager ns) { List<XmlNode> list = new List<XmlNode>(); foreach(XmlNode child in node.ChildNodes) { list.Add(child); } ContextState original = state; bool firstChild = true; foreach(XmlNode child in list) { // only first arguments can be expressions if(original == ContextState.FirstExpressionThenArgument) { if(!firstChild) { state = ContextState.Argument; } else { state = ContextState.Expression; } } firstChild = false; // determine what kinf of child element this is XDoc current = doc[child]; if((child.NodeType == XmlNodeType.Element) && (child.NamespaceURI == "#mediawiki")) { switch(child.LocalName) { case "internal": { // check if this element contains elements that would prevent it from being an internal link if(current.AtPath(".//m:link | .//m:internal | .//m:external", ns).IsEmpty) { Convert(site, doc, isTemplate, child, ContextState.Argument, ns); StringBuilder code = new StringBuilder(); code.Append("mediawiki.internal").Append("("); code.Append(AsArgument(child)); if(!string.IsNullOrEmpty(site.Language)) { code.Append(", ").Append(DekiScriptString.QuoteString(site.Language)); } code.Append(")"); current.Replace(Scripted(code.ToString(), state, true)); } else { Convert(site, doc, isTemplate, child, state, ns); if(state == ContextState.Argument) { current.AddBefore("'[['"); current.AddAfter("']]'"); } else { current.AddBefore("[["); current.AddAfter("]]"); } current.ReplaceWithNodes(current); } } break; case "external": { // check if this element contains elements that would prevent it from being an external link if(current.AtPath(".//m:link | .//m:internal | .//m:external", ns).IsEmpty) { Convert(site, doc, isTemplate, child, ContextState.Argument, ns); StringBuilder code = new StringBuilder(); code.Append("mediawiki.external").Append("("); code.Append(AsArgument(child)); code.Append(")"); current.Replace(Scripted(code.ToString(), state, true)); } else { Convert(site, doc, isTemplate, child, state, ns); if(state == ContextState.Argument) { current.AddBefore("'['"); current.AddAfter("']'"); } else { current.AddBefore("["); current.AddAfter("]"); } current.ReplaceWithNodes(current); } } break; case "link": Convert(site, doc, isTemplate, child, state, ns); switch(current["@type"].AsText) { case "internal": current.Replace(new XDoc("a").Attr("href", current["@href"].AsText).AddNodes(current)); break; case "external": current.Replace(new XDoc("a").Attr("class", "external").Attr("href", current["@href"].AsText).AddNodes(current)); break; case "external-free": if(state == ContextState.None) { current.Replace(current["@href"].AsText); } else { current.Replace(QuoteString(current["@href"].AsText)); } break; case "external-ref": current.Replace(new XDoc("a").Attr("class", "external").Attr("href", current["@href"].AsText)); break; default: // no idea what this link is, let's replace with a text version of itself current.Replace(child.OuterXml); break; } break; case "image": current.Replace(new XDoc("img").Attr("src", current["@href"].AsText).Attr("alt", current["@alt"].AsText).Attr("align", current["@align"].AsText)); break; case "comment": Convert(site, doc, isTemplate, child, state, ns); current.Replace(new XDoc("span").Attr("class", "comment").AddNodes(current)); break; case "nowiki": current.Replace(new XDoc("span").Attr("class", "plain").AddNodes(current)); break; case "extension": // TODO: should the behavior be different depending on 'state'? Convert(site, doc, isTemplate, child, state, ns); if (!current["@value"].IsEmpty) { current.Replace("{{" + current["@value"].AsText + "}}"); } else { switch (current["@function"].AsText) { case "math": current.Replace(new XDoc("pre").Attr("class", "script").Attr("function", "math.formula").Value(current.AsText)); break; case "kbd": case "abbr": case "object": current.Rename(current["@function"].AsText.ToLowerInvariant()); current.RemoveAttr("function"); break; case "rss": { StringBuilder code = new StringBuilder(); string[] rssParams = current.Contents.Split('|'); code.Append("ajaxrss{"); code.AppendFormat(" feed: '{0}' ", rssParams[0]); for (int i = 1; i < rssParams.Length; i++) { string rssParam = rssParams[i].Trim(); int index = rssParam.IndexOf('='); if (index >= 0) { code.AppendFormat(", {0}: {1}", rssParam.Substring(0, index), QuoteString(rssParam.Substring(index + 1))); } else { code.AppendFormat(", {0}: true", rssParam); } } code.Append(" }"); current.Replace(new XDoc("span").Attr("class", "script").Value(code.ToString())); } break; case "title-override": case "breadcrumbs": current.Remove(); break; default: current.Replace(child.OuterXml); break; } } break; case "magic": { string code = null; switch(current["@name"].AsText) { case "CONTENTLANGUAGE": code = "site.language"; break; case "CURRENTDAY": code = "date.format(date.now, '%d')"; break; case "CURRENTDAY2": code = "date.format(date.now, 'dd')"; break; case "CURRENTDAYNAME": code = "date.dayname(date.now)"; break; case "CURRENTDOW": code = "date.dayofweek(date.now)"; break; case "CURRENTMONTH": code = "date.month(date.now)"; break; case "CURRENTMONTHABBREV": code = "date.format(date.now, 'MMM')"; break; case "CURRENTMONTHNAME": code = "date.monthname(date.now)"; break; case "CURRENTTIME": code = "date.time(date.now)"; break; case "CURRENTHOUR": code = "date.format(date.now, 'HH')"; break; case "CURRENTWEEK": code = "date.week(date.now)"; break; case "CURRENTYEAR": code = "date.year(date.now)"; break; case "CURRENTTIMESTAMP": code = "date.format(date.now, 'yyyyMMddHHmmss')"; break; case "PAGENAME": case "PAGENAMEE": code = "page.unprefixedpath"; break; case "NUMBEROFARTICLES": code = "site.pagecount"; break; case "NUMBEROFUSERS": code = "site.usercount"; break; case "NAMESPACE": code = "page.namespace"; break; case "REVISIONDAY": code = "date.format(page.date, '%d')"; break; case "REVISIONDAY2": code = "date.format(page.date, 'dd')"; break; case "REVISIONMONTH": code = "date.month(page.date)"; break; case "REVISIONYEAR": code = "date.year(page.date)"; break; case "REVISIONTIMESTAMP": code = "date.format(page.date, 'yyyyMMddHHmmss')"; break; case "SITENAME": code = "site.name"; break; case "SERVER": code = "site.uri"; break; case "SERVERNAME": code = "site.host"; break; default: // unrecognized magic word - use the mediawiki magicword extension code = String.Format("mediawiki.variable('{0}')", DekiScriptString.EscapeString(current["@name"].AsText)); break; } current.Replace(Scripted(code, state, true)); } break; case "interwiki": { string code = String.Format("mediawiki.interwiki('{0}', '{1}', '{2}')", DekiScriptString.EscapeString(child.Attributes["prefix"].Value), DekiScriptString.EscapeString(child.Attributes["path"].Value + (((XmlElement)child).HasAttribute("fragment") ? ("#" + child.Attributes["fragment"].Value) : string.Empty)), DekiScriptString.EscapeString(child.InnerText)); current.Replace(Scripted(code, state, true)); break; } case "function": { Convert(site, doc, isTemplate, child, ContextState.Argument, ns); StringBuilder code = new StringBuilder(); bool withLang = false; switch (current["@name"].AsText) { case "formatnum": { code.Append("num.format"); // add one more parameter XmlElement arg = child.OwnerDocument.CreateElement("arg", "#mediawiki"); arg.AppendChild(child.OwnerDocument.CreateTextNode(QuoteString("N"))); child.AppendChild(arg); } break; case "fullurl": code.Append("wiki.uri"); break; case "lc": code.Append("string.tolower"); break; case "lcfirst": code.Append("string.tolowerfirst"); break; case "padleft": code.Append("string.padleft"); break; case "padright": code.Append("string.padright"); break; case "uc": code.Append("string.toupper"); break; case "ucfirst": code.Append("string.toupperfirst"); break; case "urlencode": code.Append("web.uriencode"); break; case "int": code.Append("wiki.page"); break; case "localurl": case "localurle": withLang = true; code.Append(At("mediawiki", current["@name"].AsText)); break; default: code.Append(At("mediawiki", current["@name"].AsText)); break; } // append parameters code.Append("("); if (withLang) { code.Append(null == site.Language ? "_" : DekiScriptString.QuoteString(site.Language)); } bool first = true && !withLang; foreach(XDoc arg in current.AtPath("m:arg", ns)) { if(!first) { code.Append(", "); } first = false; code.Append(AsArgument(arg.AsXmlNode)); } code.Append(")"); current.Replace(Scripted(code.ToString(), state, true)); } break; case "expression": { StringBuilder code = new StringBuilder(); switch(current["@name"].AsText) { case "#expr": Convert(site, doc, isTemplate, child, ContextState.Expression, ns); code.Append(AsExpression(current.AtPath("m:arg", ns).AsXmlNode)); break; case "#if": { Convert(site, doc, isTemplate, child, ContextState.Argument, ns); code.Append("string.trim("); code.Append(AsArgument(current.AtPath("m:arg[1]", ns).AsXmlNode)); code.Append(") !== '' ? "); code.Append(WebHtml(current.AtPath("m:arg[2]", ns).AsXmlNode)); code.Append(" : "); code.Append(WebHtml(current.AtPath("m:arg[3]", ns).AsXmlNode)); } break; case "#ifeq": { Convert(site, doc, isTemplate, child, ContextState.Argument, ns); code.Append(AsArgument(current.AtPath("m:arg[1]", ns).AsXmlNode)); code.Append(" == "); code.Append(AsArgument(current.AtPath("m:arg[2]", ns).AsXmlNode)); code.Append(" ? "); code.Append(WebHtml(current.AtPath("m:arg[3]", ns).AsXmlNode)); code.Append(" : "); code.Append(WebHtml(current.AtPath("m:arg[4]", ns).AsXmlNode)); } break; case "#ifexpr": { Convert(site, doc, isTemplate, child, ContextState.FirstExpressionThenArgument, ns); code.Append(AsExpression(current.AtPath("m:arg[1]", ns).AsXmlNode)); code.Append(" ? "); code.Append(WebHtml(current.AtPath("m:arg[2]", ns).AsXmlNode)); code.Append(" : "); code.Append(WebHtml(current.AtPath("m:arg[3]", ns).AsXmlNode)); } break; case "#ifexist": { bool simple; Convert(site, doc, isTemplate, child, ContextState.Argument, ns); code.Append("wiki.pageexists("); string title = AsPathArgument(site, current.AtPath("m:arg[1]", ns), false, out simple); code.Append(simple ? ("'" + title + "'") : title); code.Append(") ? "); code.Append(WebHtml(current.AtPath("m:arg[2]", ns).AsXmlNode)); code.Append(" : "); code.Append(WebHtml(current.AtPath("m:arg[3]", ns).AsXmlNode)); } break; case "#switch": case "#time": case "#rel2abs": case "#titleparts": case "#iferror": // TODO (steveb): missing code, falling through to default case default: code.Append(At("mediawiki", current["@name"].AsText)); // append parameters code.Append("("); bool first = true; foreach(XDoc arg in current.AtPath("m:arg", ns)) { if(!first) { code.Append(", "); } first = false; code.Append(AsArgument(arg.AsXmlNode)); } code.Append(")"); break; } current.Replace(Scripted(code.ToString(), state, false)); } break; case "template": { Convert(site, doc, isTemplate, child, ContextState.Argument, ns); StringBuilder code = new StringBuilder(); // check if we need to decode the page name bool simpleTitle; bool simpleArgs; string title = AsPathArgument(site, current.AtPath("m:name", ns), true, out simpleTitle); XDoc args = current.AtPath("m:arg", ns); string argCode = AppendTemplateArguments(args, out simpleArgs); // append parameters if(simpleTitle && simpleArgs) { code.Append("template."); code.Append(title.Substring(1, title.Length - 2)); if(string.IsNullOrEmpty(argCode)) { code.Append("()"); } else if(argCode.StartsWith("[") && argCode.EndsWith("]")) { code.Append("(" + argCode.Substring(2, argCode.Length - 4) + ")"); } else { code.Append(argCode); } } else { code.Append("wiki.template").Append("("); code.Append(title); if(!string.IsNullOrEmpty(argCode)) { code.Append(", "); code.Append(argCode); } code.Append(")"); } current.Replace(Scripted(code.ToString(), state, true)); } break; case "arg": Convert(site, doc, isTemplate, child, state, ns); break; case "name": Convert(site, doc, isTemplate, child, state, ns); break; case "ref": { if(isTemplate || (state != ContextState.None)) { Convert(site, doc, isTemplate, child, state, ns); string code; int? index = current["@index"].AsInt; if(index != null) { code = "$" + (index.Value - 1); } else { code = "$" + current["@name"].AsText; } switch(state) { case ContextState.None: if(current["@alt"].IsEmpty) { current.Replace(Scripted("web.html(" + code + ")", state, true)); } else { current.Replace(Scripted("web.html(" + code + " ?? " + AsArgument(current.AsXmlNode) + ")", state, true)); } break; default: if(current["@alt"].IsEmpty) { current.Replace(Scripted(code, state, true)); } else { current.Replace(Scripted(code + " ?? " + AsArgument(current.AsXmlNode), state, false)); } break; } } else { string code = current["@index"].AsText ?? current["@name"].AsText; if(!current["@alt"].IsEmpty) { code += "|" + current["@alt"].AsText; } current.Replace(new XDoc("span").Attr("class", "plain").Value("{{{" + code + "}}}")); } } break; } } else if(child.NodeType == XmlNodeType.Element) { Convert(site, doc, isTemplate, child, state, ns); // loop over attribute nodes foreach(XDoc attribute in current.AtPath("@m:*", ns)) { XDoc code = XDocFactory.From("<code xmlns:mediawiki=\"#mediawiki\">" + attribute.Contents + "</code>", MimeType.XML); Convert(site, code, isTemplate, code.AsXmlNode, ContextState.Argument, ns); attribute.Parent.Attr(attribute.Name, "{{" + AsArgument(code.AsXmlNode) + "}}"); attribute.Remove(); } } else { Convert(site, doc, isTemplate, child, state, ns); if((state == ContextState.Argument) && ((child.NodeType == XmlNodeType.Text) || (child.NodeType == XmlNodeType.Whitespace) || (child.NodeType == XmlNodeType.SignificantWhitespace))) { if(!string.IsNullOrEmpty(child.Value)) { double value; if(double.TryParse(child.Value, out value)) { current.Replace(child.Value); } else { current.Replace(QuoteString(child.Value)); } } else { current.Remove(); } } } } }