Crystal Reports PrintToPrinter throws exception after a time working fine - c#

We have a WPF application that, among other things, prints reports approximately every two minutes using async sintax. The report is made using SAP Crystal Reports, version for Microsoft Visual Studio 13.0.15.1840. The computer in which application has been developed has also SAP Crystal Reports runtime engine 64-bit 13.0.15.1840. Below is the code for async code:
private async void StartAsyncOperation()
{
while (true)
{
try
{
if (_isActive)
{
await Task.Run(() =>
{
PrintTravelSheet();
});
await Task.Delay(_delayPrinterTime);
}
else break;
}
catch (Exception e)
{
SendWarningAlerts(string.Format("Error!!! You should be worried! \n {0}", e));
}
}
}
The application is deployed to a computer with Windows Server 2012 with SAP Crystal Reports runtime 64-bit 13.0.8.1216. Below is the code used by PrintTravelSheet for printing:
try
{//_hojaViajera is my Crystal Report
_hojaViajera = new HojaViajera();
InitializeTravelSheet(printerConfig, tracking, configBits);
System.Drawing.Printing.PrinterSettings printerSettings = new System.Drawing.Printing.PrinterSettings();
printerSettings.PrinterName = printerConfig.PrinterName;
_hojaViajera.PrintToPrinter(printerSettings, new System.Drawing.Printing.PageSettings(), false);
}
catch (Exception ex)
{
//here I send emails with error log
}
finally
{
_hojaViajera.Close();
_hojaViajera.Dispose();
}
Usually the application works fine for two weeks or a little more, but after that time the thread that handles printing operations crashes and I receive the following exception:
** **Message Error: CrystalDecisions.CrystalReports.Engine.InternalException: There are not enough free System Resources to perform this operation.
Error formatting Field Object.
Error in File temp_1d4e04c2-7dc4-4896-a347-edc086582c07 {BFFFC1AF-E765-4FF0-BBEC-02929B533486}.rpt:
Low system resources.. ---> System.Runtime.InteropServices.COMException: There are not enough free System Resources to perform this operation.
Error formatting Field Object.
Error in File temp_1d4e04c2-7dc4-4896-a347-edc086582c07 {BFFFC1AF-E765-4FF0-BBEC-02929B533486}.rpt:
Low system resources..
at CrystalDecisions.ReportAppServer.Controllers.ReportSourceClass.GetPage(PageRequestContext pPageRequestContext)
at CrystalDecisions.ReportSource.EromReportSourceBase.GetPage(PageRequestContext pageReqContext)
--- End of inner exception stack trace ---
at CrystalDecisions.ReportAppServer.ConvertDotNetToErom.ThrowDotNetException(Exception e)
at CrystalDecisions.ReportSource.EromReportSourceBase.HandleException(Exception exception)
at CrystalDecisions.ReportSource.EromReportSourceBase.GetPage(PageRequestContext pageReqContext)
at CrystalDecisions.CrystalReports.Engine.FormatEngine.QueryPageSettingsEventHandler(Object sender, QueryPageSettingsEventArgs e)
at System.Drawing.Printing.PrintDocument.OnQueryPageSettings(QueryPageSettingsEventArgs e)
at System.Drawing.Printing.PrintDocument._OnQueryPageSettings(QueryPageSettingsEventArgs e)
at System.Drawing.Printing.PrintController.PrintLoop(PrintDocument document)
at System.Drawing.Printing.PrintController.Print(PrintDocument document)
at System.Drawing.Printing.PrintDocument.Print()
at CrystalDecisions.CrystalReports.Engine.FormatEngine.PrintToPrinter(PrinterSettings printerSettings, PageSettings pageSettings, PrintLayoutSettings layoutSettings, Boolean reformatReportPageSettings)
at CrystalDecisions.CrystalReports.Engine.ReportDocument.PrintToPrinter(PrinterSettings printerSettings, PageSettings pageSettings, PrintLayoutSettings layoutSettings, Boolean reformatReportPageSettings)
at CrystalDecisions.CrystalReports.Engine.ReportDocument.PrintToPrinter(PrinterSettings printerSettings, PageSettings pageSettings, Boolean reformatReportPageSettings)**
**
Then I just close the application and start over again and all comes back to normal. So far I have not been able to reproduce the error on my machine or even on the server. Any help or workaround is welcome.

Related

Function ...Workbooks.Open() is failed while opening .xla and .xla addins of excel through c# - HRESULT: 0x80010105 (RPC_E_SERVERFAULT)

I wrote a code in c# in Visual studio and I open excels, run macro and close the excel
I do it in cycles (in a loop and delay between every cycle)
sometimes the function failes and sometimes it works
The error message I got:
"The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT))"
Please can someone help me ???
public void Open()
{
try
{
ExcelApp.Workbooks.Open(#"C:\Program Files (x86)\REFPROP\REFPROP.XLA");
ExcelApp.Workbooks.Open(#"C:\Program Files (x86)\REFPROP\REFPROP_Ribbon.xlam");
foreach (Excel.AddIn item in ExcelApp.AddIns)
{
if (item.Name.Equals("REFPROP.XLA") || item.Name.Equals("REFPROP_Ribbon.xlam"))
{
item.Installed = false;
item.Installed = true;
}
}
Thread.Sleep(3000);
//so then opening excel workbooks:
ExcelBook = ExcelApp.Workbooks.Open(ExcelPath);
Opened = true;
Thread.Sleep(3000);
ExcelApp.Workbooks.Open(#"C:\Program Files (x86)\REFPROP\REFPROP.XLA");
ExcelApp.Workbooks.Open(#"C:\Program Files (x86)\REFPROP\REFPROP_Ribbon.xlam");
foreach (Excel.AddIn item in ExcelApp.AddIns)
{
if (item.Name.Equals("REFPROP.XLA") || item.Name.Equals("REFPROP_Ribbon.xlam"))
{
item.Installed = false;
item.Installed = true;
}
}
Thread.Sleep(3000);
}
catch (Exception e)
{
throw;
}
}
There can be multiple reasons why you are getting that exception at runtime.
First, I'd suggest releasing underlying COM objects in the code and do not rely on the GC. Use the Marshal.ReleaseComObject method for that and then set the object to null.
Second, try to set the calculation mode to manual.
Third, make sure that the file doesn't require admin privileges.
You may find a similar thread helpful, see Excel interop The server threw an exception. (Exception from HRESULT: 0x80010105 (RPC_E_SERVERFAULT)).

C# error propagating up the stack when it should not

I'm encountering an issue where a service is exiting on errors that should never propagate up.
I built a microservice manager (.NET as the local environment doesnt support .NET Core and some of its native microservice abilities)
Built in VS2019 targeting .NET 4.5.2 (I know, but this is the world we live in)
For the microservice manager, it is built and installed as a windows service. Entry looks like this (#if/#else was for testing locally, it is working as intended when registered as a windows service)
Program.cs (Entry point)
` static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#if DEBUG
Scheduler myScheduler = new Scheduler();
myScheduler.OnDebug();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Scheduler()
};
ServiceBase.Run(ServicesToRun);
#endif
}
}`
Scheduler.cs
//(confidential code hidden)
`private static readonly Configuration config = Newtonsoft.Json.JsonConvert.DeserializeObject<Configuration>(
File.ReadAllText(configFilePath)
);
public Scheduler()
{
//InitializeComponent(); //windows service, doesnt need UI components initialized
}
public void OnDebug()
{
OnStart(null); //triggers when developing locally
}
protected override async void OnStart(string[] args)
{
try
{
logger.Log($#"Service manager starting...");
logger.Log($#"Finding external services... {config.services.Count} services found.");
foreach (var service in config.services)
{
try
{
if (service.disabled)
{
logger.Log(
$#"Skipping {service.name}: disabled=true in Data Transport Service's appSettings.json file");
continue;
}
logger.Queue($#"Starting: {service.name}...");
string serviceLocation = service.useRelativePath
? Path.Combine(assemblyLocation, service.path)
: service.path;
var svc = Assembly.LoadFrom(serviceLocation);
var assemblyType = svc.GetType($#"{svc.GetName().Name}.Program");
var methodInfo = assemblyType.GetMethod("Main");
var instanceObject = Activator.CreateInstance(assemblyType, new object[0]);
methodInfo.Invoke(instanceObject, new object[0]);
logger.Queue(" Running").Send("");
}
catch (TargetInvocationException ex)
{
logger.Queue(" Failed").Send("");
logger.Log("an error occurred", LOG.LEVEL.CRITICAL, ex);
}
catch (Exception ex)
{
logger.Queue(" Failed").Send("");
logger.Log("an error occurred", LOG.LEVEL.CRITICAL, ex);
}
}
logger.Log("Finished loading services.");
}
catch (Exception ex)
{
logger.Log($#"Critical error encountered", LOG.LEVEL.CRITICAL, ex);
}
}
Microservice:
public [Confidential]()
{
if (currentProfile == null)
{
var errMsg =
$#"Service not loaded, Profile not found, check appSettings.currentProfile: '{config.currentProfile}'";
logger.Log(errMsg,severity: LOG.LEVEL.CRITICAL);
throw new SettingsPropertyNotFoundException(errMsg);
}
if (currentProfile.disabled)
{
var errMsg = $#"Service not loaded: {config.serviceName}, Service's appSettings.currentProfile.disabled=true";
logger.Log(errMsg,LOG.LEVEL.WARN);
throw new ArgumentException(errMsg);
}
logger.Log($#"Loading: '{config.serviceName}' with following configuration:{Environment.NewLine}{JsonConvert.SerializeObject(currentProfile,Formatting.Indented)}");
logger.Queue($#"Encrypting config file passwords...");
bool updateConfig = false;
foreach (var kafkaSource in config.dataTargets)
{
if (!kafkaSource.password.IsEncrypted())
{
updateConfig = true;
logger.Queue($#"%tabEncrypting: {kafkaSource.name}");
kafkaSource.password = kafkaSource.password.Encrypt();
}
else
{
logger.Queue($#"%tabAlready encrypted: {kafkaSource.name}");
}
}
logger.Send(Environment.NewLine);
if (updateConfig)
{
File.WriteAllText(
configFilePath,
Newtonsoft.Json.JsonConvert.SerializeObject(config));
}
var _source = config.dataSources.FirstOrDefault(x=>x.name==currentProfile.dataSource);
var _target = config.dataTargets.FirstOrDefault(x => x.name == currentProfile.dataTarget);
source = new Connectors.Sql(logger,
_source?.name,
_source?.connectionString,
_source.pollingInterval,
_source.maxRowsPerSelect,
_source.maxRowsPerUpdate);
target = new Connectors.KafkaProducer(logger)
{
bootstrapServers = _target?.bootstrapServers,
name = _target?.name,
password = _target?.password.Decrypt(),
sslCaLocation = Path.Combine(assemblyLocation,_target?.sslCaLocation),
topic = _target?.topic,
username = _target?.username
};
Start();
}
public void Start()
{
Timer timer = new Timer();
try
{
logger.Log($#"SQL polling interval: {source.pollingInterval} seconds");
timer.Interval = source.pollingInterval * 1000;
timer.Elapsed += new ElapsedEventHandler(this.OnTimer);
timer.Start();
if (currentProfile.executeOnStartup)
Run();
}
catch (Exception ex)
{
var sb = new StringBuilder();
sb.AppendLine($#"Critical error encountered loading external service: {config.serviceName}.");
if (!timer.Enabled)
sb.AppendLine($#"service unloaded - Schedule not started!");
else
sb.AppendLine($#"service appears to be loaded and running on schedule.");
logger.Log(sb.ToString(), LOG.LEVEL.CRITICAL, ex);
}
}
public void OnTimer(object sender, ElapsedEventArgs e)
{
try
{
Run();
}
catch (Exception ex)
{
logger.Log($#"Critical error during scheduled run on service: {config.serviceName}.", LOG.LEVEL.CRITICAL, ex);
}
}
public async void Run()
{
//Get new alarm events from SQL source
logger.Queue("Looking for new alarms...");
var rows = await GetNewEvents();`
The exception occurred during the GetNewEvents method, which attempted to open a SqlConnection to a SQL server that was unavailable due to network issues, that method intentionally throws an exception, which should throw up to OnTimer, where it gets caught, logged, and the timer keeps running. During development/testing, I used invalid credentials, bad connection string, etc and simulated this type of error and it worked as expected, logged the error, kept running. For some reason recently, that error is not caught in OnTimer, it propagates up, where it should be caught by Start (but isn't), after that it should be caught by the parent service manager which is entirely wrapped in a try/catch with no throw's, and above that (because their could be multiple microservices managed by that service) the entry point to the service manager is wrapped in try/catch with no throws, all for isolation from microservice errors. For some reason though, now, the error from a VERY downstream application is propagating all the way up.
Typically, this code runs 24/7 no issues, the microservice it is loading from the config file launches and runs fine. The entry into that specific microservice starts with a try {...} catch (Exception ex) {...} block.
The concept is to have a microservice manager than can launch a number of microservices without having to install all of them as windows services, and have some level of configuration driven by a config file that dictates how the main service runs.
The microservice represented here opens a SQL connection, reads data, performs business logic, publishes results to Kafka, it does this on a polling interval dictated by the config file contained in the microservice. As stated above, its ran for months without issue.
Recently, I noticed the main microservice manager service was not running on the windows server, I investigated the Server Application Logs and found a "Runtime Error" that essentially stated the microservice, while attempting to connect to sql, failed (network issue) and caused the entire microservice manager to exit. To my understanding, they way I'm launching the microservice should isolate it from the main service manager app. Additionally, the main service manager app is wrapped in a very generic try catch block. The entry point to the micro service itself is wrapped in a try catch, and almost every component in the microservice is wrapped in try / catch per business need. The scenario that faulted (cant connect to sql) intentionally throws an error for logging purposes, but should be caught by the immediate parent try/catch, which does not propagate or re-throw, only logs the error to a txt file and the windows server app log.
How is it that this exception is bubbling up through isolation points and causing the main service to fault and exit? I tested this extensively during development and prior to release, this exact scenario being unable to connect to sql, and it generated the correct log entry, and tried again on the next polling cycle as expected.
I haven't tried any other approaches as yet, as I feel they would be band-aid fixes as best as I dont understand why the original design is suddenly failing. The server hasn't changed, no patching/security updates/etc.
From the server Application Log:
Application: DataTransportService.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Exception
at Connectors.SqlHelper.DbHelper+d__13`1[[System.__Canon, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]].MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
at IntelligentAlarms.IntelligentAlarm+d__14.MoveNext()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(System.Threading.Tasks.Task)
at IntelligentAlarms.IntelligentAlarm+d__12.MoveNext()
at System.Runtime.CompilerServices.AsyncMethodBuilderCore+<>c.b__6_1(System.Object)
at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(System.Object)
at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean)
at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch()
at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()

Xamarin forms operating camera gives empty exception

I'm working on a mobile Android app using Xamarin Forms and Visual Studio.
I'm using the CrossMedia Plugin to be able to take or select photo's in my mobile app. At first I had problems with the initialize and that issue appeared to be caused by the wrong Android SDK I was targeting. After I updated the SDK and updated all the packages I was able to get the 'select a photo' option working, but using the camera still doesn't work, and I can't figure out what is causing this.
I've got the following method;
private async void TakeAPhoto(object sender, EventArgs e)
{
try
{
await CrossMedia.Current.Initialize();
}
catch (Exception exception)
{
await DisplayAlert("ERROR", "Error initializing camera!", "Ok");
}
var cameraStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera);
var storageStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage);
if (cameraStatus != PermissionStatus.Granted || storageStatus != PermissionStatus.Granted)
{
var results = await CrossPermissions.Current.RequestPermissionsAsync(new[] { Permission.Camera, Permission.Storage });
cameraStatus = results[Permission.Camera];
storageStatus = results[Permission.Storage];
}
if (!CrossMedia.Current.IsCameraAvailable || !CrossMedia.Current.IsTakePhotoSupported)
{
await DisplayAlert("No camera", "No camera available", "Ok");
return;
}
if (cameraStatus == PermissionStatus.Granted && storageStatus == PermissionStatus.Granted)
{
MediaFile file;
try
{
//Exception occurs in this code.
file = await CrossMedia.Current.TakePhotoAsync(new StoreCameraMediaOptions
{
//Specify Store to Album OR Directory, not both
Directory = "App_Images",
Name = "Test.jpg"
});
}
catch (Exception exception)
{
//I've got a break point here which is being hit, but the exception is (null)
throw;
}
if (file == null)
return;
//TODO: Store image to azure.
}
else
{
await DisplayAlert("Permissions Denied", "Unable to take photos.", "OK");
//On iOS you may want to send your user to the settings screen.
//CrossPermissions.Current.OpenAppSettings();
}
}
However, when I'm running the code I'm getting an empty exception, it just says '(null)';
The debug window of Visual Studio gives me a lot of information, but the only real exception I see here is an 'InvocationException';
InspectorDebugSession(0): HandleTargetEvent: TargetHitBreakpoint
InspectorDebugSession(0): StateChange: EntryPointBreakpointRegistered -> EntryPointBreakpointHit
InspectorDebugSession(0): AgentBridge.InjectAssembly: /mnt/shell/emulated/0/Android/data/MyFirstAppPackage.MyFirstAppPackage/files/.__override__/inspector-temp/Xamarin.Interactive.dll
InspectorDebugSession(0): AgentBridge.InjectAssembly: Mono.Debugger.Soft.InvocationException: Exception of type 'Mono.Debugger.Soft.InvocationException' was thrown.
at Mono.Debugger.Soft.InvocationsAPI.EndInvokeMethodInternalWithResultImpl(IAsyncResult asyncResult)
at Xamarin.Interactive.IdeSupport.AgentBridge.InjectAssembly(String agentAssemblyPath) in C:\d\lanes\4699\fec6f88f\source\xamarinvs\External\inspector-ide-integration\Xamarin.Interactive.IdeSupport\AgentBridge.cs:line 55
at Xamarin.Interactive.IdeSupport.InspectorDebuggerSession.<HandleTargetEvent>b__26_0(Object <p0>) in C:\d\lanes\4699\fec6f88f\source\xamarinvs\External\inspector-ide-integration\Xamarin.Interactive.IdeSupport\InspectorDebuggerSession.cs:line 242
InspectorDebugSession(0): StateChange: EntryPointBreakpointHit -> Error
InspectorDebugSession(0): Disposed
I've been busy for quite some time to try and figure this out, but I'm completely stuck on this at the moment. I've also tried remote debugging by attaching a Samsung Galaxy S4 Mini to my computer, but it gives me the same error. What am I doing wrong here?
I got this issue resolved by simply selecting the proper Android version to compile on. The plugin documentation says the compile version of android needs to be set to Android 6.0, I had it set to 7.0 because I thought this was possible. But it's not.
Also the target android version was set to a higher version. Setting these both to Android 6.0 fixed the issue.
For more information see the documentation here.

The server is not operational exception freezes my windows service

In our intranet we got a windows service with 2 timers in it. First one works each 5 minutes and get Active Directory users list and update Database with it, second works each hour and do some other stuff.
Sometime maintenance work on network starts, and service inner logic catch exception and write it to log. It is always the same one - The server is not operational. After it both timer seems to stop working, but service got status - started, and nothing happend any more.
Exception handling look like this:
void UserSyncTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
try
{
new ADUsersSync().Sync();
}
catch(Exception exc) {
Log.ErrorFormat("UserSyncTimer_Elapsed: Exception {0}", exc);
}
}
And there is main try catch block inside Sync function:
public void Sync()
{
try
{
DirectoryEntry Ldap = new DirectoryEntry("LDAP://OU=Users,OU=MOS1,OU=CCE,DC=portal,DC=ru");
DirectorySearcher searcher = new DirectorySearcher(Ldap);
searcher.Filter = "(&(objectClass=user)(objectCategory=Person)(memberOf:1.2.840.113556.1.4.1941:=CN=All Users,OU=DL,OU=Groups,DC=portal,DC=ru)) ";
SearchResultCollection _s = searcher.FindAll();
foreach (SearchResult sr in _s)
{
//... some code ..
}
}
catch (Exception e)
{
Log.DebugFormat("ADUsersSync Debug: in main catch and exception: {0}", e.Message);
Log.Error(e);
}
}
Logs looks like this:
2014-08-31 14:12:49,956 [10] DEBUG PortalService.BLL.ADUsersSync - ADUsersSync Debug: in main catch and exception: The server is not operational.
2014-08-31 14:12:49,966 [10] ERROR PortalService.BLL.ADUsersSync - System.Runtime.InteropServices.COMException (0x8007203A): The server is not operational.
at System.DirectoryServices.SearchResultCollection.ResultsEnumerator.MoveNext()
at PortalService.BLL.ADUsersSync.Sync()
2014-08-31 14:17:50,169 [5] DEBUG PortalService.BLL.ADUsersSync - ADUsersSync Debug: in main catch and exception: The server is not operational.
2014-08-31 14:17:50,170 [5] ERROR PortalService.BLL.ADUsersSync - System.Runtime.InteropServices.COMException (0x8007203A): The server is not operational.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
at System.DirectoryServices.DirectorySearcher.FindAll()
at TNTPortalService.BLL.ADUsersSync.Sync()
What can i do to prevent service from freezing?
Also there was memory leak because of not disposing SearchResultCollection, and it consume 1.5GB RAM on server. Wayting for the next fial to make deep check with company it support.

Exception on call hangup for landline phone

I am developing software for landline phones and full-duplex voice modems using C# and TAPI 3 library. Call answering is working fine but call hangup is throwing an exception. I did a lot of search to find solution but I could not. Following are the errors:
Exception is occurring on calling method ici.ReleaseUserUserInfo();
{"This implementation doesn't take advises (Exception from HRESULT:
0x80040003 (OLE_E_ADVISENOTSUPPORTED))"} System.Exception
{System.Runtime.InteropServices.COMException}"
My goal is to save recorded calls. One interesting thing is that if, before call hangup, I close the application, it successfully saves the recorded call.
My code:
private void BtnAnswer_Click(object sender, EventArgs e)
{
IEnumCall ec = ia[line].EnumerateCalls();
uint arg = 0;
ITCallInfo ici;
ITTerminal recordTerminal;//NY test record
try
{
ec.Next(1, out ici, ref arg);
ITBasicCallControl2 bc = (TAPI3Lib.ITBasicCallControl2)ici;
recordTerminal = bc.RequestTerminal(TapiConstants.CLSID_String_FileRecordingTerminal,
TapiConstants.TAPIMEDIATYPE_MULTITRACK,
TAPI3Lib.TERMINAL_DIRECTION.TD_RENDER);
ITMediaControl mediacontrol = (ITMediaControl)recordTerminal;
ITMediaRecord mediarecord = (ITMediaRecord)recordTerminal;
mediarecord.FileName = "a.wav";
bc.SelectTerminalOnCall(recordTerminal);
bc.Answer();
mediacontrol.Start();
}
catch (Exception exp)
{
MessageBox.Show("There may not be any calls to answer! \n\n" + exp.ToString(), "TAPI3");
}
}
private void BtnHang_Click(object sender, EventArgs e)
{
IEnumCall ec = ia[line].EnumerateCalls();
uint arg = 0;
ITCallInfo ici;
try
{
ec.Next(1, out ici, ref arg);
ITBasicCallControl bc = (ITBasicCallControl)ici;
bc.Disconnect(DISCONNECT_CODE.DC_NORMAL);
ici.ReleaseUserUserInfo();
}
catch (Exception exp)
{
MessageBox.Show("No call to disconnect!", "TAPI3");
}
}
I believe that the error code you're seeing is actually TAPI_E_NOTSUPPORTED!
According to the MSDN documentation for ITCallInfo::ReleaseUserUserInfo:
The ReleaseUserUserInfo method informs the service provider that the application has processed the user-user information obtained from the ITCallInfo::GetCallInfoBuffer method, called with the CIB_USERUSERINFO member of CALLINFO_BUFFER, and subsequently received user-user information can now be written.
Hwoever, User-user information is specific to the ISDN Q.931 standard and not all service providers support it.
Unless you specifically want to exchange this information between your client and the remote end, it is probably sufficient to simply delete the offending line of code, as it is otherwise both unused and unsupported.

Categories