Knowledge Base

Find answers to common questions about Cloudmersive products and services.



Best Practices for Logging Cloudmersive Advanced Virus Scan API Results to Application Insights
5/1/2023 - Cloudmersive Support


In this example, we call the Cloudmersive Advanced Virus Scan API and then log the results into Azure Application Insights as a Custom Event. The key properties from the Cloudmersive advanced scan response are added into the Azure Application Insights custom event, making it easy to search, filter or analyze these later.

using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.ApplicationInsights;
using Microsoft.ApplicationInsights.DataContracts;
using Cloudmersive.APIClient.NET.VirusScan.Api;
using Cloudmersive.APIClient.NET.VirusScan.Client;
using Cloudmersive.APIClient.NET.VirusScan.Model;

public class VirusScanLogger
{
    private readonly TelemetryClient _telemetryClient;
    private const string ApiKey = "YOUR_CLOUDMERSIVE_API_KEY";
    private const string AppInsightsKey = "YOUR_APP_INSIGHTS_INSTRUMENTATION_KEY";

    public VirusScanLogger()
    {
        _telemetryClient = new TelemetryClient
        {
            InstrumentationKey = AppInsightsKey
        };

        Configuration.Default.AddApiKey("Apikey", ApiKey);
    }

    public void ScanAndLog(byte[] byteArray, string fileName)
    {
        var scanResult = ScanFileAdvanced(byteArray, fileName);

        LogToAppInsights(scanResult);
    }

    private VirusScanAdvancedResult ScanFileAdvanced(byte[] byteArray, string fileName)
    {
        var apiInstance = new ScanApi();
        var inputFile = new StreamWithLength(stream: new MemoryStream(byteArray), fileName: fileName);
        
        try
        {
            // Perform advanced virus scan
            var result = apiInstance.ScanFileAdvanced(inputFile);
            return result;
        }
        catch (Exception e)
        {
            Console.WriteLine("Exception when calling ScanApi.ScanFileAdvanced: " + e.Message);
            return null;
        }
    }

    private void LogToAppInsights(VirusScanAdvancedResult scanResult)
    {
        var telemetryProperties = new Dictionary<string, string>();

        if (scanResult != null)
        {
            var properties = scanResult.GetType().GetProperties();
            foreach (var property in properties)
            {
                if (property.GetValue(scanResult) != null)
                {
                    telemetryProperties.Add(property.Name, property.GetValue(scanResult).ToString());
                }
            }
        }

        _telemetryClient.TrackEvent("VirusScanEvent", telemetryProperties);

        // Immediately send the event
        _telemetryClient.Flush();
    }

}

800 free API calls/month, with no expiration

Get started now! or Sign in with Google

Questions? We'll be your guide.

Contact Sales