Tag: C#

  • Google Analytics Measurement Protocol – Track Events C#

    Recently I had a project that required to track events happening within the business layer and could not be tracked using JavaScript from the client. To do this a helper class was required in order to communicate with Google Analytics and track those extra events. Below you will find that class that can be used to do Page Tracking, Event Tracking, Ecommerce Tracking, Social Interactions and Exception Tracking within your C# code without requiring any JavaScript or any other script.

    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Web;
    
    namespace Spyriadis.net
    {
        public class GoogleTracker
        {
            private string googleURL = "http://www.google-analytics.com/collect";
            private string googleVersion = "1";
            private string googleTrackingID = "UA-XXXX-Y";
            private string googleClientID = "555";
    
            public GoogleTracker(string trackingID)
            {
                this.googleTrackingID = trackingID;
            }
    
            public void trackEvent(string category, string action, string label, string value)
            {
                Hashtable ht = baseValues();
    
                ht.Add("t", "event");                   // Event hit type
                ht.Add("ec", category);                 // Event Category. Required.
                ht.Add("ea", action);                   // Event Action. Required.
                if (label != null) ht.Add("el", label); // Event label.
                if (value != null) ht.Add("ev", value); // Event value.
    
                postData(ht);
            }
            public void trackPage(string hostname, string page, string title)
            {
                Hashtable ht = baseValues();
    
                ht.Add("t", "pageview");                // Pageview hit type.
                ht.Add("dh", hostname);                 // Document hostname.
                ht.Add("dp", page);                     // Page.
                ht.Add("dt", title);                    // Title.
    
                postData(ht);
            }
    
            public void ecommerceTransaction(string id, string affiliation, string revenue, string shipping, string tax, string currency)
            {
                Hashtable ht = baseValues();
    
                ht.Add("t", "transaction");       // Transaction hit type.
                ht.Add("ti", id);                 // transaction ID.            Required.
                ht.Add("ta", affiliation);        // Transaction affiliation.
                ht.Add("tr", revenue);            // Transaction revenue.
                ht.Add("ts", shipping);           // Transaction shipping.
                ht.Add("tt", tax);                // Transaction tax.
                ht.Add("cu", currency);           // Currency code.
    
                postData(ht);
            }
            public void ecommerceItem(string id, string name, string price, string quantity, string code, string category, string currency)
            {
                Hashtable ht = baseValues();
    
                ht.Add("t", "item");              // Item hit type.
                ht.Add("ti", id);                 // transaction ID.            Required.
                ht.Add("in", name);               // Item name.                 Required.
                ht.Add("ip", price);              // Item price.
                ht.Add("iq", quantity);           // Item quantity.
                ht.Add("ic", code);               // Item code / SKU.
                ht.Add("iv", category);           // Item variation / category.
                ht.Add("cu", currency);           // Currency code.
    
                postData(ht);
            }
    
            public void trackSocial(string action, string network, string target)
            {
                Hashtable ht = baseValues();
    
                ht.Add("t", "social");                // Social hit type.
                ht.Add("dh", action);                 // Social Action.         Required.
                ht.Add("dp", network);                // Social Network.        Required.
                ht.Add("dt", target);                 // Social Target.         Required.
    
                postData(ht);
            }
    
            public void trackException(string description, bool fatal)
            {
                Hashtable ht = baseValues();
    
                ht.Add("t", "exception");             // Exception hit type.
                ht.Add("dh", description);            // Exception description.         Required.
                ht.Add("dp", fatal ? "1" : "0");      // Exception is fatal?            Required.
    
                postData(ht);
            }
    
            private Hashtable baseValues()
            {
                Hashtable ht = new Hashtable();
                ht.Add("v", googleVersion);         // Version.
                ht.Add("tid", googleTrackingID);    // Tracking ID / Web property / Property ID.
                ht.Add("cid", googleClientID);      // Anonymous Client ID.
                return ht;
            }
            private bool postData(Hashtable values)
            {
                string data = "";
                foreach (var key in values.Keys)
                {
                    if (data != "") data += "&";
                    if (values[key] != null) data += key.ToString() + "=" + HttpUtility.UrlEncode(values[key].ToString());
                }
    
                using (var client = new WebClient())
                {
                    var result = client.UploadString(googleURL, "POST", data);
                }
    
                return true;
            }
        }
    }

    All you need to do afterwards initialize the class using the code below:

    Spyriadis.net.GoogleTracker ga = new Spyriadis.net.GoogleTracker("UA-XXXXXXX-X");

    And then you can use all the functions by Google as described here. For example to track an event you use:

    ga.trackEvent("Category", "Action", "label", "value");

    You can pass null values for all the non-required fields.

  • Convert UTF-8 string To ASCII using C#

    Ever wanted to convert a string from UTF-8 to ASCII in order to use it in a text file or to post it on another on another website? Below you will find a static function that you can use from anyware in your Visual Studio solution to convert a string from UTF-8 to ASCII. It takes as a parameter the UTF-8 string and return the same string in ASCII.

    public static string UTF8toASCII(string text)
    {
    	System.Text.Encoding utf8 = System.Text.Encoding.UTF8;
    	Byte[] encodedBytes = utf8.GetBytes(text);
    	Byte[] convertedBytes =
    			Encoding.Convert(Encoding.UTF8, Encoding.ASCII, encodedBytes);
    	System.Text.Encoding ascii = System.Text.Encoding.ASCII;
    
    	return ascii.GetString(convertedBytes);
    }
    
  • LINQ to SQL Get DateTime from Sql Server (getDate)

    Ever wanted to get the current time and date from the SQL Server to avoid different times between yous server and the clients (for example having a centralized application running on many countries) ?

    Using LINQ to SQL there is no way to get the time from the database build in the class. What you need to do is write your own code as the example below:

        using System.Data.Linq;
        using System.Data.Linq.Mapping;
        using System.Data;
        using System.Collections.Generic;
        using System.Reflection;
        using System.Linq;
        using System.Linq.Expressions;
        using System.ComponentModel;
        using System;
    
        partial class dbGTOnlineDataContext
        {
            [Function(Name = "GetDate", IsComposable = true)]
            public DateTime GetSystemDate()
            {
                MethodInfo mi = MethodBase.GetCurrentMethod() as MethodInfo;
                return (DateTime)this.ExecuteMethodCall(this, mi, new object[] { }).ReturnValue;
            }
        }
    

    Then anywhere in your code you can simple use the code below to get the time from the SQL Server database:

    myDatabaseDataContext db = new myDatabaseDataContext();
    DateTime dtNow = db.GetSystemDate();
    
  • Crystal Reports & Framework 4 (Could not load file or assembly crdb_adoplus.dll)

    If you upgrade your project to .NET Framework 4 or for any reason you get a mysterious error like the one below:

    “Could not load file or assembly ‘file:///C:\Program Files\SAP BusinessObjects\SAP BusinessObjects Enterprise XI 4.0\win32_x86\dotnet1\crdb_adoplus.dll’ or one of its dependencies. The system cannot find the file specified.”

    Try inserting the code below at your app.config or web.config file:

    <startup useLegacyV2RuntimeActivationPolicy="true">
            <supportedRuntime version="v4.0"/>
    </startup>
    It seems that microsoft changed the binding procedure and this setting changes that.