Campaigns & Traffic Sources in Google Analytics API using ASP.NET MVC

In this article, I’m explaining how to get traffic sources in your program. Here I’m creating an mvc application that return the traffic sources. I’m also explain the concept campaigns and traffic sources.


Users arrive at your website or application through a variety of sources, including search engines, social networks, advertising campaigns, and more. By using Google Analytics to measure these campaigns and traffic sources, you can improve your marketing efforts and user experiences.

With the help of google analytics we show the traffic sources in your program with the help of references.

In Google Analytics, the search engines, social networks, ad campaigns, and different sources that send users to your property are conjointly referred to as campaigns and traffic sources. The method by that campaign and traffic supply information is distributed to Google Analytics and inhabited in reports contains a few steps:


Collection are values sent to Google analytics in the Campaigns and Traffic Sources using the tracking code. The tracking code or SDKs use following fields when sending campaign and traffic source data:

1. Campaign Source: Campaign Source sets the dimension in reports.

2. Campaign Medium: Campaign medium sets the medium dimension in reports.

3. Campaign Name: Campaign name sets the content dimension in reports.

4. Campaign Content: Campaign Content sets the content dimension in reports.

5. Campaign Term: Sets the term dimension in reports.

6. Document Location: Sets dimensions when custom campaign (utm) parameters are embedded.

7. Document Referrer: Describes the referring source and may set dimensions when no other campaign or traffic source fields have been set. 


Process are the collection used the final report dimension process logic. During the processing campaign and traffic sources are proceed many levels:

Custom Campaign

A session is processed as the custom campaign. The Custom campaign parameter are embedded in the document location.

Search Engine Organic Referrals

The processing search engine organic that means by default search engine referrals in your reports. Which search engine come in the by default which referrals show data according to comparing the hostname and query parameter of document referral fields.

Search Engine Paid Referrals

Search engine Paid referrals will be processed as a paid search referral that means when custom campaigns or AdWords/ Double Clicks IDs are used then ad’s destination url are sent to Google Analytics in the document location field.

Social Network Referrals

In the social network referrals are processed by the comparing the hostname set in the document referrer field to a list of known social networks.

Direct Traffic

In the direct traffic processed when the when no referrals source is available. 


The reporting is the facility to report the different ways and it returns the data in the dimension and metrics. There are following dimensions and metrics that contain the information:

1.      Dimension

There are many dimension to get the information of the traffic sources:

  •       ga:source: What is the source of referrals.
  •       ga:medium: What is the medium of referrals.
  •       ga:campaign: What is the campaign or AdWords or Double Click Id’s.
  •       ga:adContent: What is the ad’s content.
  •       ga:keyword: What is the keyword in the referrals.
  •       ga:socialNetwork: which social network in the referrals.
  •       ga:referralPath: what is the referral path in the campaign & traffic sources
  •       ga:hasSocialReferralPath: What is the campaign or AdWords or Double Click Id’s. 
2.      Metrics

The one metrics for the free AdWords or Double click campaign and more metrics

in the paid AdWords or double Click campaign. Here give the one metrics for the

campaign and traffic sources. 

·   ga:organicSearches: The number of organic searches that happened within a

session. This metric is search engine agnostic.

Let’s Move to create an example in mvc to get the traffic sources data:

In this example create the single page application that show all records in the traffic sources.

Step 1 Set up Service Account

First set up the service on the google developer’s console. The following steps to set up service account:

1.       Set up the tracking code in the web.

2.       First Create service account in the Google Developers Console.

3.       Add permission for this account in the Google analytics.

4.       Use this account.

If you need to more information then read my previous article set up the tracking code in the web and also see the Google analytics in mvc. 

Step 2 Create MVC Project

Create an MVC as named TrafficSources. Let’s create the project:

Campaigns &  Traffic Sources in Google Analytics API using ASP.NET MVC


Step 2 Install Packages

 First install all the packages and for google analytics which your program connect. There are following packages to install:

1.       Install the Dot net authentication package

2.       Install the Google apis package

3.       Install Google analytics package installed latest version. 

Step 3 Add Method for Google Analytics Traffic Sources


Add the method to access the data of google analytics and get traffic sources values that is necessary. 

public GaData GetTrafficSources()


string scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue();

string ServiceAccountUser = '';

string keyFile = @'D:\nnnnnnnnnnnnnnnnnnnnn.p12';

string keyPassword = 'notasecret';

AssertionFlowClient client = new AssertionFlowClient(

GoogleAuthenticationServer.Description, new X509Certificate2(keyFile, keyPassword, X509KeyStorageFlags.Exportable))


Scope = scope,

ServiceAccountId = ServiceAccountUser


var authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);

var service = new AnalyticsService(new BaseClientService.Initializer()


Authenticator = authenticator


string profileId = 'ga:nnnnnnnn';

string startDate = '2014-09-11';

string endDate = '2014-09-30';

string metrics = 'ga:organicSearches';

DataResource.GaResource.GetRequest request = service.Data.Ga.Get(profileId, startDate, endDate, metrics);

request.Dimensions = 'ga:source,ga:medium,ga:campaign,ga:adContent,ga:keyword,ga:socialNetwork,ga:referralPath';

GaData data = request.Execute();

return data;


Here I add the metrics and dimension for the campaign and sources.

Step 4 Add Controller

Add a controller if your new application otherwise add code inside the action make. 

GaData data =  googleAnalytics.GetTrafficSources();

            List<string> ColumnName = new List<string>();
            foreach (var h in data.ColumnHeaders)
            List<List<string>> ValueList = new List<List<string>>();
            foreach (var row in data.Rows)
              ViewBag.ColumnName = ColumnName;
            ViewBag.ValueList = ValueList;

This code get the column name which are metrics or dimensions and also it store the temporary for passing the data in the view section. 

Step 5 Add View

Add view to show the data that is get from the google analytics account for traffic and sources. Add this section in the view section.

<h1>Campaigns &  Traffic Sources</h1>     

        <table border='1'>
           foreach (var column in ViewBag.ColumnName)
           foreach (var values in ViewBag.ValueList)
               foreach(var item in values)

Show the data as formatted add the table or you can simple print data. 

Step 6 Run Application

Run Application that show the result:

Campaigns &  Traffic Sources in Google Analytics API using ASP.NET MVC

In this output show the result as:

Source: yandex

Medium: organic

Campaign: (not set) { the addwords are not set}

AdContent: (not set) { the addwords are not set}


Referral Path: (not set) { this is not cause of campaign}

Organic searches: 1

This show all as like this.

I hope that this article is helpful for you. Thanks!

Last updated:9/7/2019 12:15:00 AM


Leave Comment