Search code examples
c#asp.netgoogle-analyticsgoogle-analytics-api

using Google analytic version 3 in ASP.NET C#


I am working on a website a part of that is about site stat and i want to get data from Google Analytic API, now it works fine in my localhost but when i upload it to my server it shows error :

[CryptographicException: An internal error occurred.
]
   System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) +33
   System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromFile(String fileName, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx) +0
   System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags) +218
   System.Security.Cryptography.X509Certificates.X509Certificate..ctor(String fileName, String password, X509KeyStorageFlags keyStorageFlags) +65
   System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName, String password, X509KeyStorageFlags keyStorageFlags) +61
   PortalCore.Classes.GAHelper.Credential(String accemail, String certname) +119
   PortalCore.Admin.Stat.SetValues() +629
   PortalCore.Admin.Stat.Page_Load(Object sender, EventArgs e) +5
   System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
   System.Web.UI.Control.OnLoad(EventArgs e) +92
   System.Web.UI.Control.LoadRecursive() +54
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772

my codes :

string startdate = installeddate.ToString("yyyy-MM-dd"); //installeddate from My DB it's fine

//Creditional:
var creditional = GAHelper.Credential(GAHelper.GetGaData().CreditionalEmail,GAHelper.GetGaData().CertificationKey);
//Creating AnalyticsService object:
var service = GAHelper.CreateAlanlytcsObject(creditional);

//ProfileID:
string profileid = "XXXXXXXX";

//Getting data:
var newvisits = GAHelper.GetGaResults(service, profileid, startdate, DateTime.Now.ToString("yyyy-MM-dd"),"ga:newVisits");

// Getting results:
if (newvisits != null && newvisits.Rows != null)
                    {
                        ltNewVisits.Text = newvisits.Rows[0][0];
                    }

and my helper class : GAHelper.cs

public ServiceAccountCredential Credential(string accemail, string certname)
        {
            var certificate = new X509Certificate2(HttpContext.Current.Server.MapPath("~/Certifications/" + certname), "notasecret",X509KeyStorageFlags.Exportable);


                ServiceAccountCredential credential = new ServiceAccountCredential(
                   new ServiceAccountCredential.Initializer(accemail)
                   {
                       Scopes = new[] { AnalyticsService.Scope.Analytics.ToLower() }
                   }.FromCertificate(certificate));
                return credential;

        }

public AnalyticsService CreateAlanlytcsObject(ServiceAccountCredential credential)
        {
                var service = new AnalyticsService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "IranPortal",
                });
                return service;
        }

public GaData GetGaResults(AnalyticsService service, string profileid,string startdate,string enddate,string metrics)
        {
                return service.Data.Ga.Get("ga:" + profileid, startdate, enddate, metrics).Execute();

        }

Thank you guys.


Solution

  • I found solution, i should change my Credential to this :

    var certificate = 
        new X509Certificate2
        (HttpContext.Current.Server.MapPath("~/Certifications/" + certname), 
        "notasecret", 
        X509KeyStorageFlags.MachineKeySet |
        X509KeyStorageFlags.PersistKeySet | 
        X509KeyStorageFlags.Exportable);
    
    
    ServiceAccountCredential credential = new ServiceAccountCredential(
        new ServiceAccountCredential.Initializer(accemail)
        {
            Scopes = new[] { AnalyticsService.Scope.Analytics.ToLower() }
        }.FromCertificate(certificate));
    
    return credential;