title: Reliably identifying and tracking Asterisk calls using C# and Aster.NET
body: <p>I have been building a WinForms desktop application using C# that interfaces with Asterisk using Aster.NET (formerly/forked from Asterisk.NET). We're having real trouble reliably identifying and tracking calls that are related to an individual extension/user.</p>
  
  <p>The problem we're having is due to the unpredictable/fuzzy nature of the events fired/triggered by Asterisk, with them being massively variable depending on how the call is routed before it hits an extension. </p>
  
  <p>For example, the event sequence/format is different when: a call hits an IVR before getting blind transferred; if a call hits an IVR before it is attended transferred; if a call goes direct to the user's extension. </p>
  
  <p>This is further hampered by the way that Asterisk tracks each side of the call using a different Unique ID (e.g. the incoming side of the call has a different UID than the received side of the call). Whilst we've managed to account for that in the (subsequently ugly!) code, we're still hitting issues with accounting for the different routing paths the call can take.</p>
  
  <p>As such, I'm looking for any advice on how we can do the following:</p>
  
  <ol>
  <li>Reliably identify an incoming call to a user's extension 
  <ul>
  <li>We need to be able to identify the extension being called and the originating caller ID (after either a blind or attended transfer and direct call from external)</li>
  <li>Reliably track the Unique ID for that incoming call as it's used to link to the call recording</li>
  </ul></li>
  <li>Reliably identify an outgoing call from a user's extension
  <ul>
  <li>With the same caveats as above in mind</li>
  </ul></li>
  </ol>
  
  <p>As it stands at the minute we have an extremely complex chain of event handlers that operate differently dependent on the 'current state' of the app. </p>
  
  <p>To give one example: if we detect a NewStateEvent with a ChannelState of 6 ('Up'), we check if there is an ongoing call in process <em>and</em> that the UIDs match, and if so then the current call has been answered. If the UIDs don't match, but other factors do (e.g. channel, connectedlinenum, etc), then we pick this up as being the 'other side' of the call (i.e. the receiving or incoming side). </p>
  
  <p>I'm not sure if the problem lies with the API or with AMI - but whichever it is it's causing us some real headaches.</p>
  
  <p>Any advice greatly appreciated.</p>