public void Test_Execute() { IIntrusionDetector detector = Esapi.IntrusionDetector; string url = Guid.NewGuid().ToString(); RedirectAction action = new RedirectAction(url); // Set context MockHttpContext.InitializeCurrentContext(); SurrogateWebPage page = new SurrogateWebPage(); HttpContext.Current.Handler = page; // Block try { Assert.AreNotEqual(HttpContext.Current.Request.RawUrl, action.Url); action.Execute(ActionArgs.Empty); Assert.Fail("Request not terminated"); } catch (Exception exp) { // FIXME : so far there is no other way to test the redirect except to check // the stack of the exception. Ideally we should be able to mock the request // redirect itself Assert.IsTrue(exp.StackTrace.Contains("at System.Web.HttpResponse.Redirect(String url, Boolean endResponse)")); } }
/// <summary> /// Parses the node. /// </summary> /// <param name="node">The node to parse.</param> /// <param name="config">The rewriter configuration.</param> /// <returns>The parsed action, or null if no action parsed.</returns> public override IRewriteAction Parse(XmlNode node, object config) { if (node == null) { throw new ArgumentNullException("node"); } var toNode = node.Attributes.GetNamedItem(Constants.AttrTo); if (toNode == null) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.AttributeRequired, Constants.AttrTo), node); } var permanent = true; var permanentNode = node.Attributes.GetNamedItem(Constants.AttrPermanent); if (permanentNode != null) { permanent = Convert.ToBoolean(permanentNode.Value); } var action = new RedirectAction(toNode.Value, permanent); this.ParseConditions(node, action.Conditions, false, config); return(action); }
//------------------------------------------------------------------------------------------------------------- void TransferCall(string DialedNumber) { if (RINGENABLED != false) { // Now send Redirect action RedirectAction ra = new RedirectAction(); ra.Channel = AsteriskPhoneAgentForm.CHANNEL_REMOTE; //ra.ExtraChannel = AsteriskPhoneAgentForm.; ra.Context = ORIGINATE_CONTEXT; ra.Exten = DialedNumber; ra.Priority = 1; try { ManagerResponse mr = manager.SendAction(ra, 10000); Log("Transfer Call" + "\n\tResponse:" + mr.Response + "\n\tMessage:" + mr.Message ); } catch (Exception ex) { Log(ex.Message); } } }
/// <summary> /// Parses the node. /// </summary> /// <param name="node">The node to parse.</param> /// <param name="config">The rewriter configuration.</param> /// <returns>The parsed action, or null if no action parsed.</returns> public override IRewriteAction Parse(XmlNode node, RewriterConfiguration config) { if (node == null) { throw new ArgumentNullException("node"); } string to = node.GetRequiredAttribute(Constants.AttrTo, true); bool permanent = true; XmlNode permanentNode = node.Attributes.GetNamedItem(Constants.AttrPermanent); if (permanentNode != null) { if (!bool.TryParse(permanentNode.Value, out permanent)) { throw new ConfigurationErrorsException(MessageProvider.FormatString(Message.InvalidBooleanAttribute, Constants.AttrPermanent), node); } } RedirectAction action = new RedirectAction(to, permanent); ParseConditions(node, action.Conditions, false, config); return(action); }
public void Test_Create() { string url = Guid.NewGuid().ToString(); RedirectAction action = new RedirectAction(url); Assert.AreEqual(action.Url, url); }
public void Execute_WithNullContext_Throws() { // Arrange RedirectAction action = new RedirectAction("/", true); IRewriteContext context = null; // Act/Assert ExceptionAssert.Throws<ArgumentNullException>(() => action.Execute(context)); }
public void Execute_WithNullContext_Throws() { // Arrange RedirectAction action = new RedirectAction("/", true); IRewriteContext context = null; // Act/Assert ExceptionAssert.Throws <ArgumentNullException>(() => action.Execute(context)); }
public void IsMatch_WhenNoConditions_ReturnsTrue() { // Arrange RedirectAction action = new RedirectAction("/", true); IRewriteContext context = new MockRewriteContext(); // Act bool match = action.IsMatch(context); // Assert Assert.IsTrue(match); }
public bool Transfer(string callid, string caller, string destination) { RedirectAction ra = new RedirectAction(); ra.Channel = caller; ra.Context = Properties.Settings.Default.DefaultContext; ra.Priority = 1; ra.Exten = destination; ManagerResponse mr = _manager.SendAction(ra, 10000); return(mr.IsSuccess()); }
public void IsMatch_WhenSingleConditionDoesNotMatch_ReturnsFalse() { // Arrange RedirectAction action = new RedirectAction("/", true); IRewriteContext context = new MockRewriteContext(); action.Conditions.Add(new MockRewriteCondition(false)); // Act bool match = action.IsMatch(context); // Assert Assert.IsFalse(match); }
public void IsMatch_WhenMixedConditions_ReturnsFalse() { // Arrange RedirectAction action = new RedirectAction("/", true); IRewriteContext context = new MockRewriteContext(); action.Conditions.Add(new MockRewriteCondition(true)); action.Conditions.Add(new MockRewriteCondition(false)); // Act bool match = action.IsMatch(context); // Assert Assert.IsFalse(match); }
public async static Task TransferChannel(ManagerConnection ami, string channel, string destination) { await Task.Run(() => { RedirectAction r = new RedirectAction() { Channel = channel, Exten = destination, Context = "bbs-pabx", Priority = 1 }; var res = (ami.SendAction(r)); res.Dump(); }); }
/// <summary> /// Parses the node. /// </summary> /// <param name="node">The node to parse.</param> /// <param name="config">The rewriter configuration.</param> /// <returns>The parsed action, or null if no action parsed.</returns> public override IRewriteAction Parse(XmlNode node, IRewriterConfiguration config) { if (node == null) { throw new ArgumentNullException(nameof(node)); } var to = node.GetRequiredAttribute(Constants.AttrTo, true); var permanent = node.GetBooleanAttribute(Constants.AttrPermanent) ?? true; var action = new RedirectAction(to, permanent); this.ParseConditions(node, action.Conditions, false, config); return(action); }
public void Execute_WhenTemporary_SetsStatusCodeAndLocation_ReturnsStopProcessing() { // Arrange string location = "/NewLocation"; bool permanent = false; RedirectAction action = new RedirectAction(location, permanent); action.Conditions.Add(new MockRewriteCondition(true)); IRewriteContext context = new MockRewriteContext(); // Act RewriteProcessing result = action.Execute(context); // Assert Assert.AreEqual(RewriteProcessing.StopProcessing, result); Assert.AreEqual(HttpStatusCode.Found, context.StatusCode); Assert.AreEqual(location, context.Location); }
public String Transferir(String Canal, String Otra) { String OtroCanal = Canal; RedirectAction o = new RedirectAction(); o.Channel = OtroCanal; o.Context = "from-internal"; o.Exten = Otra; o.Priority = 1; if (StatusExtension(Otra) == 0) { ManagerResponse response = Conn.SendAction(o, 30000); return(response.Message); } else { throw new Exception("La Extensión no está disponible para transferir"); } }
public static bool RedirectCall(ManagerConnection ami, string destination, string channel = null) { try { RedirectAction r = new RedirectAction() { Channel = channel, Exten = destination, Context = "bbs-pabx", Priority = 1 }; r.Dump(); var res = (ami.SendAction(r)); return(res.IsSuccess()); } catch { MessageBox.Show("Failed to transfer call, sorry for any inconveniences.", "Call Transfer Failed", MessageBoxButton.OK, MessageBoxImage.Error); return(false); } }
public void Redirect(string location) { RedirectAction redirectAction = new RedirectAction(location); actions.Add(redirectAction); }
private static void checkManagerAPI() { manager = new ManagerConnection(ASTERISK_HOST, ASTERISK_PORT, ASTERISK_LOGINNAME, ASTERISK_LOGINPWD); // Register user event class manager.RegisterUserEventClass(typeof(UserAgentLoginEvent)); // Add or Remove events manager.UserEvents += new UserEventHandler(dam_UserEvents); // Dont't display this event manager.NewExten += new NewExtenEventHandler(manager_IgnoreEvent); // Display all other manager.UnhandledEvent += new ManagerEventHandler(dam_Events); // +++ Only to debug purpose manager.FireAllEvents = true; // manager.DefaultEventTimeout = 0; // manager.DefaultResponseTimeout = 0; manager.PingInterval = 0; // +++ try { manager.Login(); // Login only (fast) Console.WriteLine("Asterisk version : " + manager.Version); } catch (Exception ex) { Console.WriteLine(ex); Console.ReadLine(); manager.Logoff(); return; } { Console.WriteLine("\nGetConfig action"); ManagerResponse response = manager.SendAction(new GetConfigAction("manager.conf")); if (response.IsSuccess()) { GetConfigResponse responseConfig = (GetConfigResponse)response; foreach (int key in responseConfig.Categories.Keys) { Console.WriteLine(string.Format("{0}:{1}", key, responseConfig.Categories[key])); foreach (int keyLine in responseConfig.Lines(key).Keys) { Console.WriteLine(string.Format("\t{0}:{1}", keyLine, responseConfig.Lines(key)[keyLine])); } } } else { Console.WriteLine(response); } } { Console.WriteLine("\nUpdateConfig action"); UpdateConfigAction config = new UpdateConfigAction("manager.conf", "manager.conf"); config.AddCommand(UpdateConfigAction.ACTION_NEWCAT, "testadmin"); config.AddCommand(UpdateConfigAction.ACTION_APPEND, "testadmin", "secret", "blabla"); ManagerResponse response = manager.SendAction(config); Console.WriteLine(response); } // Originate call example Console.WriteLine("\nPress ENTER key to originate call.\n" + "Start phone (or connect) or make a call to see events.\n" + "After all events press a key to originate call."); Console.ReadLine(); OriginateAction oc = new OriginateAction(); oc.Context = ORIGINATE_CONTEXT; oc.Priority = "1"; oc.Channel = ORIGINATE_CHANNEL; oc.CallerId = ORIGINATE_CALLERID; oc.Exten = ORIGINATE_EXTEN; oc.Timeout = ORIGINATE_TIMEOUT; // oc.Variable = "VAR1=abc|VAR2=def"; // oc.SetVariable("VAR3", "ghi"); ManagerResponse originateResponse = manager.SendAction(oc, oc.Timeout); Console.WriteLine("Response:"); Console.WriteLine(originateResponse); Console.WriteLine("Press ENTER key to next test."); Console.ReadLine(); // // Display result of Show Queues command // { CommandAction command = new CommandAction(); CommandResponse response = new CommandResponse(); if (manager.AsteriskVersion == AsteriskVersion.ASTERISK_1_6) { command.Command = "queue show"; } else { command.Command = "show queues"; } try { response = (CommandResponse)manager.SendAction(command); Console.WriteLine("Result of " + command.Command); foreach (string str in response.Result) { Console.WriteLine("\t" + str); } } catch (Exception err) { Console.WriteLine("Response error: " + err); } Console.WriteLine("Press ENTER to next test or CTRL-C to exit."); Console.ReadLine(); } // // Display Queues and Members // ResponseEvents re; try { re = manager.SendEventGeneratingAction(new QueueStatusAction()); } catch (EventTimeoutException e) { // this happens with Asterisk 1.0.x as it doesn't send a QueueStatusCompleteEvent re = e.PartialResult; } foreach (ManagerEvent e in re.Events) { if (e is QueueParamsEvent) { QueueParamsEvent qe = (QueueParamsEvent)e; Console.WriteLine("QueueParamsEvent" + "\n\tQueue:\t\t" + qe.Queue + "\n\tServiceLevel:\t" + qe.ServiceLevel); } else if (e is QueueMemberEvent) { QueueMemberEvent qme = (QueueMemberEvent)e; Console.WriteLine("QueueMemberEvent" + "\n\tQueue:\t\t" + qme.Queue + "\n\tLocation:\t" + qme.Location); } else if (e is QueueEntryEvent) { QueueEntryEvent qee = (QueueEntryEvent)e; Console.WriteLine("QueueEntryEvent" + "\n\tQueue:\t\t" + qee.Queue + "\n\tChannel:\t" + qee.Channel + "\n\tPosition:\t" + qee.Position); } } Console.WriteLine("Press ENTER to next test or CTRL-C to exit."); Console.ReadLine(); // // To test create 3 extensions: // 1 - SIP/4012 w/o voicemail (with eyeBeam softphone) // 2 - IAX2/4008 w/o voicemail (with iaxComm softphone) // 3 - SIP/4010 w/ voicemal but no phone connect // RedirectCall: call from IAX2/4008 to SIP/4012 // Don't answer on SIP/4012 and call must redirect to SIP/4010 (to voicemail really) // Dial event used to define redirect channel Console.WriteLine("Redirect Call from " + ORIGINATE_CHANNEL + " to " + ORIGINATE_EXTRA_CHANNEL + " or press ESC."); // Wait for Dial Event from ORIGINATE_CHANNEL DialEventHandler de = new DialEventHandler(dam_Dial); manager.Dial += de; while (transferChannel == null) { System.Threading.Thread.Sleep(100); if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape) { break; } } manager.Dial -= de; // Now send Redirect action RedirectAction ra = new RedirectAction(); ra.Channel = transferChannel; ra.ExtraChannel = ORIGINATE_EXTRA_CHANNEL; ra.Context = ORIGINATE_CONTEXT; ra.Exten = ORIGINATE_EXTRA_EXTEN; ra.Priority = 1; try { ManagerResponse mr = manager.SendAction(ra, 10000); Console.WriteLine("Transfer Call" + "\n\tResponse:" + mr.Response + "\n\tMessage:" + mr.Message ); } catch (Exception ex) { Console.WriteLine(ex.Message); } // Monitor call. // Call from IA2/4008 to SIP/4012 // Link event used to define monitor channel Console.WriteLine("Monitor call. Please call " + ORIGINATE_CHANNEL + " and answer or press ESC."); // Wait for Link event LinkEventHandler le = new LinkEventHandler(dam_Link); manager.Link += le; while (monitorChannel == null) { System.Threading.Thread.Sleep(100); if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape) { break; } } manager.Link -= le; // Now send Monitor action MonitorAction ma = new MonitorAction(); ma.Channel = monitorChannel; ma.File = "voicefile"; ma.Format = "gsm"; ma.Mix = true; try { ManagerResponse mr = manager.SendAction(ma, 10000); Console.WriteLine("Monitor Call" + "\n\tResponse:" + mr.Response); } catch (Exception ex) { Console.WriteLine(ex.Message); } manager.Logoff(); }
private void ParseUrlAction(XElement urlAction, UrlRewriteRuleBuilder builder, bool stopProcessing) { var actionType = ParseEnum(urlAction, RewriteTags.Type, ActionType.None); UrlAction action; switch (actionType) { case ActionType.None: action = new NoneAction(stopProcessing ? RuleResult.SkipRemainingRules : RuleResult.ContinueRules); break; case ActionType.Rewrite: case ActionType.Redirect: var url = string.Empty; if (urlAction.Attribute(RewriteTags.Url) != null) { url = urlAction.Attribute(RewriteTags.Url).Value; if (string.IsNullOrEmpty(url)) { throw new InvalidUrlRewriteFormatException(urlAction, "Url attribute cannot contain an empty string"); } } var urlPattern = _inputParser.ParseInputString(url, builder.UriMatchPart); var appendQuery = ParseBool(urlAction, RewriteTags.AppendQueryString, defaultValue: true); if (actionType == ActionType.Rewrite) { action = new RewriteAction(stopProcessing ? RuleResult.SkipRemainingRules : RuleResult.ContinueRules, urlPattern, appendQuery); } else { var redirectType = ParseEnum(urlAction, RewriteTags.RedirectType, RedirectType.Permanent); action = new RedirectAction((int)redirectType, urlPattern, appendQuery); } break; case ActionType.AbortRequest: action = new AbortAction(); break; case ActionType.CustomResponse: int statusCode; if (!int.TryParse(urlAction.Attribute(RewriteTags.StatusCode)?.Value, out statusCode)) { throw new InvalidUrlRewriteFormatException(urlAction, "A valid status code is required"); } if (statusCode < 200 || statusCode > 999) { throw new NotSupportedException("Status codes must be between 200 and 999 (inclusive)"); } if (!string.IsNullOrEmpty(urlAction.Attribute(RewriteTags.SubStatusCode)?.Value)) { throw new NotSupportedException("Substatus codes are not supported"); } var statusReason = urlAction.Attribute(RewriteTags.StatusReason)?.Value; var statusDescription = urlAction.Attribute(RewriteTags.StatusDescription)?.Value; action = new CustomResponseAction(statusCode) { StatusReason = statusReason, StatusDescription = statusDescription }; break; default: throw new NotSupportedException($"The action type {actionType} wasn't recognized"); } builder.AddUrlAction(action); }
public override void Redirect(string location, bool permanent) { RedirectAction?.Invoke(location, permanent); }