Class to store all the necessery information for the game. This class is used for the analytics of the game, and for the AI of the game. It only contains getters and setters and is not continuesly running when the game is, it only gets updated with an event.
Пример #1
0
    public void LoadProfiles_SettingsIsEmpty_ShouldReturnExistentProfilesEnumerable([Content] Item item, CurrentInteraction currentInteraction, ITracker tracker, Analytics.Tracking.Profile profile)
    {
      var profileSettingItem = item.Add("profileSetting", new TemplateID(Templates.ProfilingSettings.ID));
      var profileItem = item.Add("profile", new TemplateID(ProfileItem.TemplateID));


      var provider = new ProfileProvider();

      var fakeSiteContext = new FakeSiteContext(new StringDictionary
      {
        {
          "rootPath", "/sitecore"
        },
        {
          "startItem", profileSettingItem.Paths.FullPath.Remove(0, "/sitecore".Length)
        }
      });

      fakeSiteContext.Database = item.Database;

      using (new SiteContextSwitcher(fakeSiteContext))
      {
        provider.GetSiteProfiles().Count().Should().Be(0);
      }
    }
Пример #2
0
        protected override void OnStart()
        {
            _analytics = Backend.GetService<Analytics>();
            _analytics.StartSession();

            CrossPushNotification.Current.Register();
        }
Пример #3
0
 void Start()
 {
     camera = GameObject.Find ("Main Camera Right");
     captionEl = GetComponent<TextMesh> ();
     analytics = GameObject.Find ("Analytics").GetComponent<Analytics>();
     panelRenderer = GameObject.Find ("Root").GetComponent<PanelRenderer> ();
 }
Пример #4
0
    public void LoadProfiles_SettingWithProfiles_ShouldReturnExistentProfilesEnumerable(Db db, CurrentInteraction currentInteraction, ITracker tracker, Analytics.Tracking.Profile profile)
    {
      var profileItem = new DbItem("profile", ID.NewID, new TemplateID(ProfileItem.TemplateID));
      db.Add(profileItem);
      var profileSettingItem = new DbItem("profileSetting", ID.NewID, new TemplateID(Templates.ProfilingSettings.ID))
                               {
                                 {Templates.ProfilingSettings.Fields.SiteProfiles, profileItem.ID.ToString()}
                               };
      db.Add(profileSettingItem);

      var provider = new ProfileProvider();

      var fakeSiteContext = new FakeSiteContext(new StringDictionary
                                                {
                                                  {"rootPath", "/sitecore"},
                                                  {"startItem", profileSettingItem.FullPath.Remove(0, "/sitecore".Length)}
                                                })
                            {
                              Database = db.Database
                            };


      using (new SiteContextSwitcher(fakeSiteContext))
      {
        var siteProfiles = provider.GetSiteProfiles();
        siteProfiles.Count().Should().Be(1);
      }
    }
Пример #5
0
    void Start()
    {
        FAVORITES_FILE = Application.persistentDataPath + Path.DirectorySeparatorChar + "Favorites";

        camera = GameObject.Find ("Main Camera Right");
        captionEl = GetComponent<TextMesh> ();
        analytics = GameObject.Find ("Analytics").GetComponent<Analytics>();
        panelRenderer = GameObject.Find ("Root").GetComponent<PanelRenderer> ();
    }
Пример #6
0
        public MainPage()
        {
            InitializeComponent();

            // Set the data context of the listbox control to the sample data
            DataContext = App.ViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            CompositionTarget.Rendering += new EventHandler(GameLoop);

            _analytics = new Analytics();
        }
Пример #7
0
        public void CanTrackEventTwiceOnProvider()
        {
            var provider = A.Fake<IAnalyticsProvider>();
            var analytics = new Analytics();
            analytics.Subscribe(provider);

            analytics.TrackEvent(A.Dummy<string>());
            analytics.TrackEvent(A.Dummy<string>());

            A.CallTo(() => provider.TrackEvent(A<string>._)).MustHaveHappened(Repeated.Exactly.Twice);
        }
Пример #8
0
        public void CanTrackException()
        {
            var provider = A.Fake<IAnalyticsProvider>();
            var analytics = new Analytics();
            analytics.Subscribe(provider);

            analytics.TrackException(A.Dummy<Exception>());

            A.CallTo(() => provider.TrackException(A<Exception>._)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => provider.TrackEvent(A<string>._)).MustNotHaveHappened();
            A.CallTo(() => provider.TrackScreen(A<string>._)).MustNotHaveHappened();
        }
Пример #9
0
		public App()
		{
			Analytics = new Analytics();
			//base.Startup += Application_Startup;
			base.Startup += new WeakEventHandler<StartupEventHandler, StartupEventArgs>(Application_Startup, null/*e => base.Startup -= e*/);
			base.Exit += Application_Exit;
			base.UnhandledException += Application_UnhandledException;
			base.CheckAndDownloadUpdateCompleted += Application_UpdateCompleted;
			InitializeComponent();

			base.CheckAndDownloadUpdateAsync();
			Test();
		}
Пример #10
0
        public void CanRegisterMultipleSubscribers()
        {
            var p1 = A.Fake<IAnalyticsProvider>();
            var p2 = A.Fake<IAnalyticsProvider>();

            var analytics = new Analytics();
            analytics.Subscribe(p1);
            analytics.Subscribe(p2);

            analytics.TrackEvent(A.Dummy<string>());

            A.CallTo(() => p1.TrackEvent(A<string>._)).MustHaveHappened(Repeated.Exactly.Once);
            A.CallTo(() => p2.TrackEvent(A<string>._)).MustHaveHappened(Repeated.Exactly.Once);
        }
Пример #11
0
        public void CanTrackEventNTimesOnProvider()
        {
            var provider = A.Fake<IAnalyticsProvider>();
            var analytics = new Analytics();
            analytics.Subscribe(provider);

            var count = new Random().Next(1000);

            for (int i = 0; i < count; i++)
            {
                analytics.TrackEvent(A.Dummy<string>());
            }

            Console.WriteLine("Executed '{0}' times", count);
            A.CallTo(() => provider.TrackEvent(A<string>._)).MustHaveHappened(Repeated.Exactly.Times(count));
        }
Пример #12
0
        /// <summary>
        /// Installs the specific version of an ASI to the specified target
        /// </summary>
        /// <param name="modVersion"></param>
        /// <param name="target"></param>
        /// <param name="forceSource">Null to let application choose the source, true to force online, false to force local cache. This parameter is used for testing</param>
        /// <returns></returns>
        public static bool InstallASIToTarget(ASIModVersion asi, GameTarget target, bool?forceSource = null)
        {
            if (asi.Game != target.Game)
            {
                throw new Exception($@"ASI {asi.Name} cannot be installed to game {target.Game}");
            }
            Log.Information($@"Processing ASI installation request: {asi.Name} v{asi.Version} -> {target.TargetPath}");
            string destinationFilename  = $@"{asi.InstalledPrefix}-v{asi.Version}.asi";
            string cachedPath           = Path.Combine(CachedASIsFolder, destinationFilename);
            string destinationDirectory = MEDirectories.ASIPath(target);

            if (!Directory.Exists(destinationDirectory))
            {
                Log.Information(@"Creating ASI directory in game: " + destinationDirectory);
                Directory.CreateDirectory(destinationDirectory);
            }
            string finalPath = Path.Combine(destinationDirectory, destinationFilename);

            // Delete existing ASIs from the same group to ensure we don't install the same mod
            var  existingSameGroupMods            = target.GetInstalledASIs().OfType <KnownInstalledASIMod>().Where(x => x.AssociatedManifestItem.OwningMod == asi.OwningMod).ToList();
            bool hasExistingVersionOfModInstalled = false;

            if (existingSameGroupMods.Any())
            {
                foreach (var v in existingSameGroupMods)
                {
                    if (v.Hash == asi.Hash && !forceSource.HasValue && !hasExistingVersionOfModInstalled) //If we are forcing a source, we should always install. Delete duplicates past the first one
                    {
                        Log.Information($@"{v.AssociatedManifestItem.Name} is already installed. We will not remove the existing correct installed ASI for this install request");
                        hasExistingVersionOfModInstalled = true;
                        continue; //Don't delete this one. We are already installed. There is no reason to install it again.
                    }
                    Log.Information($@"Deleting existing ASI from same group: {v.InstalledPath}");
                    v.Uninstall();
                }
            }

            if (hasExistingVersionOfModInstalled && !forceSource.HasValue) //Let app decide
            {
                return(true);                                              // This asi was "Installed" (because it was already installed).
            }

            // Install the ASI
            if (forceSource == null || forceSource.Value == false)
            {
                Debug.WriteLine("Hit me");
            }
            string md5;
            bool   useLocal = forceSource.HasValue && !forceSource.Value; // false (forceLocal)

            if (!useLocal && !forceSource.HasValue)
            {
                useLocal = File.Exists(cachedPath);
            }
            if (useLocal)
            {
                //Check hash first
                md5 = Utilities.CalculateMD5(cachedPath);
                if (md5 == asi.Hash)
                {
                    Log.Information($@"Copying ASI from cached library to destination: {cachedPath} -> {finalPath}");

                    File.Copy(cachedPath, finalPath, true);
                    Log.Information($@"Installed ASI to {finalPath}");
                    Analytics.TrackEvent(@"Installed ASI", new Dictionary <string, string>()
                    {
                        { @"Filename", Path.GetFileNameWithoutExtension(finalPath) }
                    });
                    return(true);
                }
            }

            if (!forceSource.HasValue || forceSource.Value)
            {
                WebRequest request = WebRequest.Create(asi.DownloadLink);
                Log.Information(@"Fetching remote ASI from server");
                try
                {
                    using WebResponse response = request.GetResponse();
                    var memoryStream = new MemoryStream();
                    response.GetResponseStream().CopyTo(memoryStream);
                    //MD5 check on file for security
                    md5 = Utilities.CalculateMD5(memoryStream);
                    if (md5 != asi.Hash)
                    {
                        //ERROR!
                        Log.Error(@"Downloaded ASI did not match the manifest! It has the wrong hash.");
                        return(false);
                    }

                    Log.Information(@"Fetched remote ASI from server. Installing ASI to " + finalPath);
                    memoryStream.WriteToFile(finalPath);
                    Log.Information(@"ASI successfully installed.");
                    Analytics.TrackEvent(@"Installed ASI", new Dictionary <string, string>()
                    {
                        { @"Filename", Path.GetFileNameWithoutExtension(finalPath) }
                    });

                    //Cache ASI
                    if (!Directory.Exists(CachedASIsFolder))
                    {
                        Log.Information(@"Creating cached ASIs folder");
                        Directory.CreateDirectory(CachedASIsFolder);
                    }

                    Log.Information(@"Caching ASI to local ASI library: " + cachedPath);
                    memoryStream.WriteToFile(cachedPath);
                    return(true);
                }
                catch (Exception e)
                {
                    Log.Error($@"Error downloading ASI from {asi.DownloadLink}: {e.Message}");
                }
            }

            // We could not install the ASI
            return(false);
        }
 public void SendAnalytics(string EventName, AnalyticParameter[] parameters = null)
 {
     Analytics.CustomEvent(EventName, parameters.GetAsKeyValuePairs());
 }
Пример #14
0
 public static void TrackEvent(string trackIdentifier, IDictionary <string, string> table = null) =>
 Analytics.TrackEvent(trackIdentifier, table);
        public void OnClick(Window mainWindow, Instance instance)
        {
            Analytics.TrackEvent("OpenHosts");

            WindowHelper.ShowDialog(new HostsDialog(), mainWindow);
        }
Пример #16
0
    void Awake()
    {
        //Debug.Log("AnalyticsTesting Awake()");

        // prevent additional Analytics objects being created on level reloads
        if (instance)
        {
            DestroyImmediate(this.gameObject);
            return;
        }
        instance = this;
        DontDestroyOnLoad(gameObject);

        string clientID = "";
        const string clientIdPrefKey = "GoogleUniversalAnalytics_clientID";
        // If you want to force a new client ID for temporary testing,
        // uncomment following line for a single run:
        //////// PlayerPrefs.DeleteKey(clientIdPrefKey);
        // (remember to disable it again)

        if (PlayerPrefs.HasKey(clientIdPrefKey))
            clientID = PlayerPrefs.GetString(clientIdPrefKey);
        if (clientID.Length < 8 || !PlayerPrefs.HasKey(clientIdPrefKey))
        {
            // Need to generate unique & anonymous client ID for analytics.
            #if UNITY_ANDROID
            // Don't use SystemInfo.deviceUniqueIdentifier on Android,
            // as it would add requirement of READ_PHONE_STATE permission.
            // So we only use self-generated timestamp + random value.
            //Debug.Log("Creating new Android clientID for analytics...");
            clientID = getPOSIXTime().ToString("X8") + Random.Range(0, 0x7fffffff).ToString("x8");
#else
            // On most platforms we use device unique identifier but
            // additionally shuffle a random value inside it to make
            // sure it's anonymous.
            char[] id = (Random.Range(0, 0x7fffffff).ToString("x8") + SystemInfo.deviceUniqueIdentifier).ToCharArray();
            for (int a = 0; a < 8; ++a)
            {
                char c = id[a];
                int idx = Random.Range(0, id.Length);
                id[a] = id[idx];
                id[idx] = c;
            }
            clientID = new string(id);
            #endif

            //Debug.Log("Created client id for analytics: " + clientID);
            PlayerPrefs.SetString(clientIdPrefKey, clientID);
            PlayerPrefs.Save();
        }

        //bool useStringEscaping = true; // see the docs about this
        if (gua == null)
            gua = GoogleUniversalAnalytics.Instance;
        gua.initialize(trackingID, clientID, appName, appVersion, useHTTPS);
        //gua.setStringEscaping(useStringEscaping); // see the docs about this

        if (PlayerPrefs.HasKey(disableAnalyticsByUserOptOutPrefKey))
        {
            gua.analyticsDisabled = (PlayerPrefs.GetInt(disableAnalyticsByUserOptOutPrefKey, 0) != 0);
        }

        if (!gua.analyticsDisabled)
        {
            // Start by sending a hit with some generic info, including an app
            // screen hit with the first level name, since first scene doesn't get
            // automatically call to OnLevelWasLoaded.
            gua.beginHit(GoogleUniversalAnalytics.HitType.Appview);
            gua.addApplicationVersion();
            gua.addScreenResolution(Screen.currentResolution.width, Screen.currentResolution.height);
            gua.addViewportSize(Screen.width, Screen.height);
#if !UNITY_METRO && !UNITY_WEBPLAYER && !UNITY_STANDALONE && !UNITY_3_5 && !UNITY_FLASH
            gua.addScreenColors(Handheld.use32BitDisplayBuffer ? 32 : 16);
#endif
            // Note: this adds language e.g. as "English", although Google API example has "en-us".
            gua.addUserLanguage(Application.systemLanguage.ToString());
            //gua.addCustomDimension(1, "ScreenDPI");
            //gua.addCustomMetric(1, (int)Screen.dpi);
            gua.addContentDescription(newLevelAnalyticsEventPrefix + Application.loadedLevelName);
            gua.sendHit();


            // Next, client SystemInfo statistics are submitted ONCE on the first
            // launch when internet is reachable.

            // If you make a few version upgrades and at some point want to get
            // fresh statistics of your active users, update the category string
            // below and after next update users will re-submit SystemInfo once.
            const string category = "SystemInfo_since_v001";
            const string prefKey = "GoogleUniversalAnalytics_" + category;

            // Existing pref key could be deleted with following command:
            //// PlayerPrefs.DeleteKey(prefKey);
            // Warning: Do not enable that code row here (except for single time
            //          testing). Otherwise all following single time statistics
            //          hits would be sent on each launch.

            if (Application.internetReachability != NetworkReachability.NotReachable &&
                !PlayerPrefs.HasKey(prefKey))
            {
                gua.sendEventHit(category, "ScreenDPI", ((int)Screen.dpi).ToString(), (int)Screen.dpi);

                gua.sendEventHit(category, "operatingSystem", SystemInfo.operatingSystem);
                gua.sendEventHit(category, "processorType", SystemInfo.processorType);
                gua.sendEventHit(category, "processorCount", SystemInfo.processorCount.ToString(), SystemInfo.processorCount);
                // round down to 128MB chunks for label
                gua.sendEventHit(category, "systemMemorySize", (128 * (SystemInfo.systemMemorySize / 128)).ToString(), SystemInfo.systemMemorySize);
                // round down to 16MB chunks for label
                gua.sendEventHit(category, "graphicsMemorySize", (16 * (SystemInfo.graphicsMemorySize / 16)).ToString(), SystemInfo.graphicsMemorySize);
                gua.sendEventHit(category, "graphicsDeviceName", SystemInfo.graphicsDeviceName);
                gua.sendEventHit(category, "graphicsDeviceVendor", SystemInfo.graphicsDeviceVendor);
                gua.sendEventHit(category, "graphicsDeviceID", SystemInfo.graphicsDeviceID.ToString(), SystemInfo.graphicsDeviceID);
                gua.sendEventHit(category, "graphicsDeviceVendorID", SystemInfo.graphicsDeviceVendorID.ToString(), SystemInfo.graphicsDeviceVendorID);
                gua.sendEventHit(category, "graphicsDeviceVersion", SystemInfo.graphicsDeviceVersion);
                gua.sendEventHit(category, "graphicsShaderLevel", SystemInfo.graphicsShaderLevel.ToString(), SystemInfo.graphicsShaderLevel);
                // round down to chunks for label (10-5000 MPix depending on value range)
                int pixelFillrateChunkSize = 5000;
                if (SystemInfo.graphicsPixelFillrate < 40000)
                    pixelFillrateChunkSize = 2000;
                if (SystemInfo.graphicsPixelFillrate < 10000)
                    pixelFillrateChunkSize = 1000;
                else if (SystemInfo.graphicsPixelFillrate < 4000)
                    pixelFillrateChunkSize = 500;
                else if (SystemInfo.graphicsPixelFillrate < 1300)
                    pixelFillrateChunkSize = 100;
                else if (SystemInfo.graphicsPixelFillrate < 200)
                    pixelFillrateChunkSize = 20;
                else if (SystemInfo.graphicsPixelFillrate < 100)
                    pixelFillrateChunkSize = 10;
                gua.sendEventHit(category, "graphicsPixelFillrate", (pixelFillrateChunkSize * (SystemInfo.graphicsPixelFillrate / pixelFillrateChunkSize)).ToString(), SystemInfo.graphicsPixelFillrate);
                gua.sendEventHit(category, "deviceType", SystemInfo.deviceType.ToString());
                // round down to 512 chunks for label
#if !UNITY_3_5
                gua.sendEventHit(category, "maxTextureSize", (512 * (SystemInfo.maxTextureSize / 512)).ToString(), SystemInfo.maxTextureSize);
                gua.sendEventHit(category, "supports3DTextures", SystemInfo.supports3DTextures ? "yes" : "no", SystemInfo.supports3DTextures ? 1 : 0);
                gua.sendEventHit(category, "supportsComputeShaders", SystemInfo.supportsComputeShaders ? "yes" : "no", SystemInfo.supportsComputeShaders ? 1 : 0);
                gua.sendEventHit(category, "supportsInstancing", SystemInfo.supportsInstancing ? "yes" : "no", SystemInfo.supportsInstancing ? 1 : 0);
                gua.sendEventHit(category, "npotSupport", SystemInfo.npotSupport.ToString());
#endif
                gua.sendEventHit(category, "supportsShadows", SystemInfo.supportsShadows ? "yes" : "no", SystemInfo.supportsShadows ? 1 : 0);
                gua.sendEventHit(category, "supportsRenderTextures", SystemInfo.supportsRenderTextures ? "yes" : "no", SystemInfo.supportsRenderTextures ? 1 : 0);
                gua.sendEventHit(category, "supportedRenderTargetCount", SystemInfo.supportedRenderTargetCount.ToString(), SystemInfo.supportedRenderTargetCount);

                gua.sendEventHit(category, "deviceModel", SystemInfo.deviceModel);

                gua.sendEventHit(category, "supportsAccelerometer", SystemInfo.supportsAccelerometer ? "yes" : "no", SystemInfo.supportsAccelerometer ? 1 : 0);
                gua.sendEventHit(category, "supportsGyroscope", SystemInfo.supportsGyroscope ? "yes" : "no", SystemInfo.supportsGyroscope ? 1 : 0);
                gua.sendEventHit(category, "supportsLocationService", SystemInfo.supportsLocationService ? "yes" : "no", SystemInfo.supportsLocationService ? 1 : 0);
                gua.sendEventHit(category, "supportsVibration", SystemInfo.supportsVibration ? "yes" : "no", SystemInfo.supportsVibration ? 1 : 0);
                gua.sendEventHit(category, "supportsImageEffects", SystemInfo.supportsImageEffects ? "yes" : "no", SystemInfo.supportsImageEffects ? 1 : 0);
                PlayerPrefs.SetInt(prefKey, getPOSIXTime());
                PlayerPrefs.Save();
            }

        } // !gua.analyticsDisabled
	} // Awake
Пример #17
0
    void Start()
    {
        PANORAMA_SHADER = Shader.Find ("InsideVisible");
        statusMessage = GameObject.Find ("StatusMessage").GetComponent<TextMesh>();
        monoEyePano = GameObject.Find ("monoEyePano");
        leftEyePano = GameObject.Find ("leftEyePano");
        rightEyePano = GameObject.Find ("rightEyePano");
        leftEyeImg = GameObject.Find ("leftEyeImg");
        rightEyeImg = GameObject.Find ("rightEyeImg");
        imgCaption = GameObject.Find ("imgCaption");
        reportImage = GameObject.Find ("reportImage");
        saveFavorite = GameObject.Find ("saveFavorite");

        titleMessage = GameObject.Find ("TitleMessage");
        fetchAudio = GetComponent<AudioSource> ();
        analytics = GameObject.Find ("Analytics").GetComponent<Analytics>();
        analytics.Init ();

        monoPanoramaShuffle = new ShuffleBag<int> (15003);
        for (int i = 0; i < 15003; i++) {
            monoPanoramaShuffle.Add(i, 1);
        }

        stereoImagesShuffle = new ShuffleBag<int> (4496);
        for (int i = 0; i < 4497; i++) {
            stereoImagesShuffle.Add(i, 1);
        }

        StartCoroutine (Fetch ());
    }
Пример #18
0
    public void HasMatchingPattern_HistoricProfileProfileNotExitsts_ReturnFalse([Content] Item profileItem, Contact contact, ITracker tracker, Analytics.Tracking.Profile profile)
    {
      //Arrange
      tracker.Contact.Returns(contact);
      contact.BehaviorProfiles[Arg.Is(profileItem.ID)].Returns(x => null);

      var fakeSiteContext = new FakeSiteContext("fake")
      {
        Database = Database.GetDatabase("master")
      };
      //Act
      using (new TrackerSwitcher(tracker))
      {
        using (new SiteContextSwitcher(fakeSiteContext))
        {
          var provider = new ProfileProvider();
          var result = provider.HasMatchingPattern(new ProfileItem(profileItem), ProfilingTypes.Historic);
          //Assert 
          result.Should().BeFalse();
        }
      }
    }
Пример #19
0
 private void AnalyticsEnabled_CheckedChanged(object sender, EventArgs e)
 {
     AnalyticsEnabled.Enabled = AppCenterEnabled.Checked;
     Analytics.SetEnabledAsync(AnalyticsEnabled.Checked).Wait();
 }
Пример #20
0
        public async Task <string> SendPostRequest(string serviceName, object parameters, bool logDatatoAppCenter = true)
        {
            string url      = GetBaseAddress() + serviceName;
            string jsonData = JsonConvert.SerializeObject(parameters);
            object username = "";

            if (Application.Current.Properties.ContainsKey("UserName"))
            {
                username = Application.Current.Properties["UserName"];
            }
            object userID = "";

            if (Application.Current.Properties.ContainsKey("UserID"))
            {
                userID = Application.Current.Properties["UserID"];
            }
            try
            {
                using (var client = new HttpClient())
                {
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "text/html,application/xhtml+xml,application/xml");
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
                    client.DefaultRequestHeaders.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36");
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Accept-Charset", "ISO-8859-1");
                    client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
                    var postData = new StringContent(jsonData, UnicodeEncoding.UTF8, "application/json");
                    var response = await client.PostAsync(url, postData);

                    if (logDatatoAppCenter)
                    {
                        Analytics.TrackEvent("API Requests", new Dictionary <string, string>
                        {
                            { "RequestURI:", url },
                            { "StatusCode:", response.StatusCode + "" },
                            { "User Name:", username + "" },
                            { "User ID:", userID + "" }
                        });
                    }
                    else
                    {
                        if (logDatatoAppCenter)
                        {
                            Analytics.TrackEvent("API Requests", new Dictionary <string, string>
                            {
                                { "RequestURI:", url },
                                { "PayLoad:", jsonData },
                                { "StatusCode:", response.StatusCode + "" },
                                { "User Name:", username + "" },
                                { "User ID:", userID + "" }
                            });
                        }
                    }



                    if (!response.IsSuccessStatusCode)
                    {
                        Analytics.TrackEvent("API Requests", new Dictionary <string, string>
                        {
                            { "RequestURI:", url },
                            { "PayLoad:", jsonData },
                            { "StatusCode:", response.StatusCode + "" },
                            { "UserName:"******"" },
                            { "UserID:", userID + "" }
                        });
                        throw new Exception($"Http request failed. Status code : {response.StatusCode}.");
                    }
                    return(await response.Content.ReadAsStringAsync());
                }
            }
            catch (Exception ex)
            {
                Crashes.TrackError(ex, new Dictionary <string, string>
                {
                    { "StackTrace", ex.StackTrace },
                    { "Error Message", ex.Message },
                    { "RequestURI:", url },
                    { "PayLoad:", jsonData },
                    { "UserName:"******"" },
                    { "UserID:", userID + "" }
                });

                Debug.WriteLine(ex.Message);
                throw ex;
            }
        }
Пример #21
0
    void Start()
    {
        PANORAMA_SHADER = Shader.Find ("InsideVisible");
        statusMessage = GameObject.Find ("StatusMessage").GetComponent<TextMesh>();
        monoEyePano = GameObject.Find ("monoEyePano");
        leftEyePano = GameObject.Find ("leftEyePano");
        rightEyePano = GameObject.Find ("rightEyePano");
        leftEyeImg = GameObject.Find ("leftEyeImg");
        rightEyeImg = GameObject.Find ("rightEyeImg");
        imgCaption = GameObject.Find ("imgCaption");
        reportImage = GameObject.Find ("reportImage");
        saveFavorite = GameObject.Find ("saveFavorite");

        titleMessage = GameObject.Find ("TitleMessage");
        fetchAudio = GetComponent<AudioSource> ();
        analytics = GameObject.Find ("Analytics").GetComponent<Analytics>();
        analytics.Init ();

        StartCoroutine (Fetch ());
    }
    void Awake()
    {
        //Debug.Log("AnalyticsTesting Awake()");

        // prevent additional Analytics objects being created on level reloads
        if (instance)
        {
            DestroyImmediate(this.gameObject);
            return;
        }
        instance = this;
        DontDestroyOnLoad(gameObject);

        string clientID = "";
        const string clientIdPrefKey = "GoogleUniversalAnalytics_clientID";
        // If you want to force a new client ID for temporary testing,
        // uncomment following line for a single run:
        //////// PlayerPrefs.DeleteKey(clientIdPrefKey);
        // (remember to disable it again)

        if (PlayerPrefs.HasKey(clientIdPrefKey))
            clientID = PlayerPrefs.GetString(clientIdPrefKey);
        if (clientID.Length < 8 || !PlayerPrefs.HasKey(clientIdPrefKey))
        {
            // Need to generate unique & anonymous client ID for analytics.
            // SystemInfo.deviceUniqueIdentifier would be nice for this, but
            // use of it is abandoned as it can lead to additional required
            // permissions or submission approval problems on some platforms.
            // So we only use a combination of timestamp, random value and
            // some sources of device-specific data to make up an anonymous
            // id which is also sufficiently unique.
            int deviceData = SystemInfo.graphicsDeviceName.GetHashCode() ^ SystemInfo.graphicsDeviceVersion.GetHashCode() ^ SystemInfo.operatingSystem.GetHashCode() ^ SystemInfo.processorType.GetHashCode();
            clientID = getPOSIXTime().ToString("X8") + Random.Range(0, 0x7fffffff).ToString("x8") + deviceData.ToString("X8");

            //Debug.Log("Created client id for analytics: " + clientID);
            PlayerPrefs.SetString(clientIdPrefKey, clientID);
            PlayerPrefs.Save();
        }

        string offlineCacheFilePath = ""; // empty string=disable (in GUA class)
        if (useOfflineCache && offlineCacheFileName != null && offlineCacheFileName.Length > 0)
        {
            offlineCacheFilePath = Application.persistentDataPath + '/' + offlineCacheFileName;
            //Debug.Log("Full path for offline cache: " + offlineCacheFilePath);
        }

        //bool useStringEscaping = true; // see the docs about this
        if (gua == null)
            gua = GoogleUniversalAnalytics.Instance;
        gua.initialize(this, trackingID, clientID, appName, appVersion, useHTTPS, offlineCacheFilePath);
        //gua.setStringEscaping(useStringEscaping); // see the docs about this

        if (PlayerPrefs.HasKey(disableAnalyticsByUserOptOutPrefKey))
        {
            gua.analyticsDisabled = (PlayerPrefs.GetInt(disableAnalyticsByUserOptOutPrefKey, 0) != 0);
        }

        if (!gua.analyticsDisabled)
        {
            // Start by sending a hit with some generic info, including an app
            // screen hit with the first level name, since first scene doesn't get
            // automatically call to OnLevelWasLoaded.
            gua.beginHit(GoogleUniversalAnalytics.HitType.Screenview);
            gua.addScreenResolution(Screen.currentResolution.width, Screen.currentResolution.height);
#if !UNITY_METRO && !UNITY_WEBPLAYER && !UNITY_STANDALONE && !UNITY_3_5
            gua.addScreenColors(Handheld.use32BitDisplayBuffer ? 32 : 16);
#endif
            // Note: this adds language e.g. as "English", although Google API example has "en-us".
            gua.addUserLanguage(Application.systemLanguage.ToString());
            gua.addScreenName(newLevelAnalyticsEventPrefix + Application.loadedLevelName);
            gua.sendHit();


            // Next, client SystemInfo statistics are submitted ONCE on the first
            // launch when internet is reachable.

            // If you make a few version upgrades and at some point want to get
            // fresh statistics of your active users, update the category string
            // below and after next update users will re-submit SystemInfo once.
            const string category = "SystemInfo_since_v001";
            const string prefKey = "GoogleUniversalAnalytics_" + category;

            // Existing pref key could be deleted with following command:
            //// PlayerPrefs.DeleteKey(prefKey);
            // Warning: Do not enable that code row here (except for single time
            //          testing). Otherwise all following single time statistics
            //          hits would be sent on each launch.

            if ((useOfflineCache || gua.internetReachable) &&
                !PlayerPrefs.HasKey(prefKey))
            {
                gua.sendEventHit(category, "ScreenDPI", ((int)Screen.dpi).ToString(), (int)Screen.dpi);
                gua.sendEventHit(category, "ScreenResolution", "" + Screen.currentResolution.width + "x" + Screen.currentResolution.height);
                gua.sendEventHit(category, "ViewportSize", "" + Screen.width + "x" + Screen.height);

                gua.sendEventHit(category, "operatingSystem", SystemInfo.operatingSystem);
                gua.sendEventHit(category, "processorType", SystemInfo.processorType);
                gua.sendEventHit(category, "processorCount", SystemInfo.processorCount.ToString(), SystemInfo.processorCount);
                // round down to 128MB chunks for label
                gua.sendEventHit(category, "systemMemorySize", (128 * (SystemInfo.systemMemorySize / 128)).ToString(), SystemInfo.systemMemorySize);
                // round down to 16MB chunks for label
                gua.sendEventHit(category, "graphicsMemorySize", (16 * (SystemInfo.graphicsMemorySize / 16)).ToString(), SystemInfo.graphicsMemorySize);
                gua.sendEventHit(category, "graphicsDeviceName", SystemInfo.graphicsDeviceName);
                gua.sendEventHit(category, "graphicsDeviceVendor", SystemInfo.graphicsDeviceVendor);
                gua.sendEventHit(category, "graphicsDeviceID", SystemInfo.graphicsDeviceID.ToString(), SystemInfo.graphicsDeviceID);
                gua.sendEventHit(category, "graphicsDeviceVendorID", SystemInfo.graphicsDeviceVendorID.ToString(), SystemInfo.graphicsDeviceVendorID);
                gua.sendEventHit(category, "graphicsDeviceVersion", SystemInfo.graphicsDeviceVersion);
                gua.sendEventHit(category, "graphicsShaderLevel", SystemInfo.graphicsShaderLevel.ToString(), SystemInfo.graphicsShaderLevel);
                // round down to chunks for label (10-5000 MPix depending on value range)
                int pixelFillrateChunkSize = 5000;
                if (SystemInfo.graphicsPixelFillrate < 40000)
                    pixelFillrateChunkSize = 2000;
                if (SystemInfo.graphicsPixelFillrate < 10000)
                    pixelFillrateChunkSize = 1000;
                else if (SystemInfo.graphicsPixelFillrate < 4000)
                    pixelFillrateChunkSize = 500;
                else if (SystemInfo.graphicsPixelFillrate < 1300)
                    pixelFillrateChunkSize = 100;
                else if (SystemInfo.graphicsPixelFillrate < 200)
                    pixelFillrateChunkSize = 20;
                else if (SystemInfo.graphicsPixelFillrate < 100)
                    pixelFillrateChunkSize = 10;
                gua.sendEventHit(category, "graphicsPixelFillrate", (pixelFillrateChunkSize * (SystemInfo.graphicsPixelFillrate / pixelFillrateChunkSize)).ToString(), SystemInfo.graphicsPixelFillrate);
                gua.sendEventHit(category, "deviceType", SystemInfo.deviceType.ToString());
                // round down to 512 chunks for label
#if !UNITY_3_5
                gua.sendEventHit(category, "maxTextureSize", (512 * (SystemInfo.maxTextureSize / 512)).ToString(), SystemInfo.maxTextureSize);
                gua.sendEventHit(category, "supports3DTextures", SystemInfo.supports3DTextures ? "yes" : "no", SystemInfo.supports3DTextures ? 1 : 0);
                gua.sendEventHit(category, "supportsComputeShaders", SystemInfo.supportsComputeShaders ? "yes" : "no", SystemInfo.supportsComputeShaders ? 1 : 0);
                gua.sendEventHit(category, "supportsInstancing", SystemInfo.supportsInstancing ? "yes" : "no", SystemInfo.supportsInstancing ? 1 : 0);
                gua.sendEventHit(category, "npotSupport", SystemInfo.npotSupport.ToString());
#endif
                gua.sendEventHit(category, "supportsShadows", SystemInfo.supportsShadows ? "yes" : "no", SystemInfo.supportsShadows ? 1 : 0);
                gua.sendEventHit(category, "supportsRenderTextures", SystemInfo.supportsRenderTextures ? "yes" : "no", SystemInfo.supportsRenderTextures ? 1 : 0);
                gua.sendEventHit(category, "supportedRenderTargetCount", SystemInfo.supportedRenderTargetCount.ToString(), SystemInfo.supportedRenderTargetCount);
                gua.sendEventHit(category, "deviceModel", SystemInfo.deviceModel);
                gua.sendEventHit(category, "supportsAccelerometer", SystemInfo.supportsAccelerometer ? "yes" : "no", SystemInfo.supportsAccelerometer ? 1 : 0);
                gua.sendEventHit(category, "supportsGyroscope", SystemInfo.supportsGyroscope ? "yes" : "no", SystemInfo.supportsGyroscope ? 1 : 0);
                gua.sendEventHit(category, "supportsLocationService", SystemInfo.supportsLocationService ? "yes" : "no", SystemInfo.supportsLocationService ? 1 : 0);
                gua.sendEventHit(category, "supportsVibration", SystemInfo.supportsVibration ? "yes" : "no", SystemInfo.supportsVibration ? 1 : 0);
                gua.sendEventHit(category, "supportsImageEffects", SystemInfo.supportsImageEffects ? "yes" : "no", SystemInfo.supportsImageEffects ? 1 : 0);
                PlayerPrefs.SetInt(prefKey, getPOSIXTime());
                PlayerPrefs.Save();
            }
        } // !gua.analyticsDisabled
	} // Awake
Пример #23
0
    void Awake()
    {
        //Debug.Log("AnalyticsTesting Awake()");

        // prevent additional Analytics objects being created on level reloads
        if (instance)
        {
            DestroyImmediate(this.gameObject);
            return;
        }
        instance = this;
        DontDestroyOnLoad(gameObject);

        string clientID = "";
        const string clientIdPrefKey = "GoogleUniversalAnalytics_clientID";
        // If you want to force a new client ID for temporary testing,
        // uncomment following line for a single run:
        //////// PlayerPrefs.DeleteKey(clientIdPrefKey);
        // (remember to disable it again)

        if (PlayerPrefs.HasKey(clientIdPrefKey))
            clientID = PlayerPrefs.GetString(clientIdPrefKey);
        if (clientID.Length < 8 || !PlayerPrefs.HasKey(clientIdPrefKey))
        {
            // Need to generate unique & anonymous client ID for analytics.
            // SystemInfo.deviceUniqueIdentifier would be nice for this, but
            // use of it is abandoned as it can lead to additional required
            // permissions or submission approval problems on some platforms.
            // So we only use a combination of timestamp, random value and
            // some sources of device-specific data to make up an anonymous
            // id which is also sufficiently unique.
            int deviceData = SystemInfo.graphicsDeviceName.GetHashCode() ^ SystemInfo.graphicsDeviceVersion.GetHashCode() ^ SystemInfo.operatingSystem.GetHashCode() ^ SystemInfo.processorType.GetHashCode();
            clientID = getPOSIXTime().ToString("X8") + Random.Range(0, 0x7fffffff).ToString("x8") + deviceData.ToString("X8");

            //Debug.Log("Created client id for analytics: " + clientID);
            PlayerPrefs.SetString(clientIdPrefKey, clientID);
            PlayerPrefs.Save();
        }

        string offlineCacheFilePath = ""; // empty string=disable (in GUA class)
        if (useOfflineCache && offlineCacheFileName != null && offlineCacheFileName.Length > 0)
        {
            offlineCacheFilePath = Application.persistentDataPath + '/' + offlineCacheFileName;
            //Debug.Log("Full path for offline cache: " + offlineCacheFilePath);
        }

        //bool useStringEscaping = true; // see the docs about this
        if (gua == null)
            gua = GoogleUniversalAnalytics.Instance;
        gua.initialize(this, trackingID, clientID, appName, appVersion, useHTTPS, offlineCacheFilePath);
        //gua.setStringEscaping(useStringEscaping); // see the docs about this

        if (gua.shouldWarnAboutUsingExampleTrackingProperty())
        {
            GameObject guiWarningGO = new GameObject();
            GUIText guiWarning = guiWarningGO.AddComponent<GUIText>();
            guiWarning.name = "GUA Tracking Property ID WARNING";
            guiWarning.text = "GUA WARNING: Wrong analytics property ID!"; // USE YOUR ANALYTICS TRACKING PROPERTY ID FROM GOOGLE ANALYTICS
            guiWarning.fontSize = 16;
	    #if !UNITY_3_5
            guiWarning.color = Color.red;
	    #endif
            guiWarning.fontStyle = FontStyle.Bold;
            guiWarning.anchor = TextAnchor.UpperCenter;
            guiWarning.transform.position = new Vector3(0.5f, 0.9f);
        }

        if (PlayerPrefs.HasKey(disableAnalyticsByUserOptOutPrefKey))
        {
            gua.analyticsDisabled = (PlayerPrefs.GetInt(disableAnalyticsByUserOptOutPrefKey, 0) != 0);
        }

        if (!gua.analyticsDisabled)
        {
            // Start by sending a hit with some generic info, including an app
            // screen hit with the first level name, since first scene doesn't get
            // automatically call to OnLevelWasLoaded.
            gua.beginHit(GoogleUniversalAnalytics.HitType.Screenview);
            gua.addScreenResolution(Screen.currentResolution.width, Screen.currentResolution.height);
            gua.addViewportSize(Screen.width, Screen.height);
            gua.addScreenName(newLevelAnalyticsEventPrefix + Application.loadedLevelName);
            gua.sendHit();


            // Next, client SystemInfo statistics are submitted ONCE on the first
            // launch when internet is reachable.

            // If you make a few version upgrades and at some point want to get
            // fresh statistics of your active users, update the category string
            // below and after next update users will re-submit SystemInfo once.
            const string category = "SystemInfo_since_v001";
            const string prefKey = "GoogleUniversalAnalytics_" + category;

            // Existing pref key could be deleted with following command:
            //// PlayerPrefs.DeleteKey(prefKey);
            // Warning: Do not enable that code row here (except for single time
            //          testing). Otherwise all following single time statistics
            //          hits would be sent on each launch.

            if (sendSystemInfo &&
                (useOfflineCache || gua.internetReachable) &&
                !PlayerPrefs.HasKey(prefKey))
            {
                sendSystemInfoEvent(category, "ScreenResolution", "" + Screen.currentResolution.width + "x" + Screen.currentResolution.height);
                sendSystemInfoEvent(category, "ViewportSize", "" + Screen.width + "x" + Screen.height);
                sendSystemInfoEvent(category, "ScreenDPI", ((int)Screen.dpi).ToString(), (int)Screen.dpi);

                sendSystemInfoEvent(category, "operatingSystem", SystemInfo.operatingSystem);
                sendSystemInfoEvent(category, "processorType", SystemInfo.processorType);
                sendSystemInfoEvent(category, "processorCount", SystemInfo.processorCount.ToString(), SystemInfo.processorCount);
                // round down to 128MB chunks for label
                sendSystemInfoEvent(category, "systemMemorySize", (128 * (SystemInfo.systemMemorySize / 128)).ToString(), SystemInfo.systemMemorySize);
                // round down to 16MB chunks for label
                sendSystemInfoEvent(category, "graphicsMemorySize", (16 * (SystemInfo.graphicsMemorySize / 16)).ToString(), SystemInfo.graphicsMemorySize);
                sendSystemInfoEvent(category, "graphicsDeviceName", SystemInfo.graphicsDeviceName);
                sendSystemInfoEvent(category, "graphicsDeviceVendor", SystemInfo.graphicsDeviceVendor);
                sendSystemInfoEvent(category, "graphicsDeviceID", SystemInfo.graphicsDeviceID.ToString(), SystemInfo.graphicsDeviceID);
                sendSystemInfoEvent(category, "graphicsDeviceVendorID", SystemInfo.graphicsDeviceVendorID.ToString(), SystemInfo.graphicsDeviceVendorID);
                sendSystemInfoEvent(category, "graphicsDeviceVersion", SystemInfo.graphicsDeviceVersion);
                sendSystemInfoEvent(category, "graphicsShaderLevel", SystemInfo.graphicsShaderLevel.ToString(), SystemInfo.graphicsShaderLevel);
#               if UNITY_3_5 || UNITY_4_0 || UNITY_4_1 || UNITY_4_2 || UNITY_4_3 || UNITY_4_5 || UNITY_4_6
                // (graphicsPixelFillrate is not supported on Unity 5.0+)
                // round down to chunks for label (10-5000 MPix depending on value range)
                int pixelFillrateChunkSize = 5000;
                if (SystemInfo.graphicsPixelFillrate < 40000)
                    pixelFillrateChunkSize = 2000;
                if (SystemInfo.graphicsPixelFillrate < 10000)
                    pixelFillrateChunkSize = 1000;
                else if (SystemInfo.graphicsPixelFillrate < 4000)
                    pixelFillrateChunkSize = 500;
                else if (SystemInfo.graphicsPixelFillrate < 1300)
                    pixelFillrateChunkSize = 100;
                else if (SystemInfo.graphicsPixelFillrate < 200)
                    pixelFillrateChunkSize = 20;
                else if (SystemInfo.graphicsPixelFillrate < 100)
                    pixelFillrateChunkSize = 10;
                sendSystemInfoEvent(category, "graphicsPixelFillrate", (pixelFillrateChunkSize * (SystemInfo.graphicsPixelFillrate / pixelFillrateChunkSize)).ToString(), SystemInfo.graphicsPixelFillrate);
#               else // or Unity 5.0+:
                // New additions in Unity 5.0+:
                sendSystemInfoEvent(category, "graphicsMultiThreaded", SystemInfo.graphicsMultiThreaded ? "yes" : "no", SystemInfo.graphicsMultiThreaded ? 1 : 0);
#               endif // Unity 5.0+
                sendSystemInfoEvent(category, "deviceType", SystemInfo.deviceType.ToString());
                // round down to 512 chunks for label
#               if !UNITY_3_5
                sendSystemInfoEvent(category, "maxTextureSize", (512 * (SystemInfo.maxTextureSize / 512)).ToString(), SystemInfo.maxTextureSize);
                sendSystemInfoEvent(category, "supports3DTextures", SystemInfo.supports3DTextures ? "yes" : "no", SystemInfo.supports3DTextures ? 1 : 0);
                sendSystemInfoEvent(category, "supportsComputeShaders", SystemInfo.supportsComputeShaders ? "yes" : "no", SystemInfo.supportsComputeShaders ? 1 : 0);
                sendSystemInfoEvent(category, "supportsInstancing", SystemInfo.supportsInstancing ? "yes" : "no", SystemInfo.supportsInstancing ? 1 : 0);
                sendSystemInfoEvent(category, "npotSupport", SystemInfo.npotSupport.ToString());
#               endif
                sendSystemInfoEvent(category, "supportsShadows", SystemInfo.supportsShadows ? "yes" : "no", SystemInfo.supportsShadows ? 1 : 0);
                sendSystemInfoEvent(category, "supportsRenderTextures", SystemInfo.supportsRenderTextures ? "yes" : "no", SystemInfo.supportsRenderTextures ? 1 : 0);
                sendSystemInfoEvent(category, "supportedRenderTargetCount", SystemInfo.supportedRenderTargetCount.ToString(), SystemInfo.supportedRenderTargetCount);
                sendSystemInfoEvent(category, "deviceModel", SystemInfo.deviceModel);
                sendSystemInfoEvent(category, "supportsAccelerometer", SystemInfo.supportsAccelerometer ? "yes" : "no", SystemInfo.supportsAccelerometer ? 1 : 0);
                sendSystemInfoEvent(category, "supportsGyroscope", SystemInfo.supportsGyroscope ? "yes" : "no", SystemInfo.supportsGyroscope ? 1 : 0);
                sendSystemInfoEvent(category, "supportsLocationService", SystemInfo.supportsLocationService ? "yes" : "no", SystemInfo.supportsLocationService ? 1 : 0);
                sendSystemInfoEvent(category, "supportsVibration", SystemInfo.supportsVibration ? "yes" : "no", SystemInfo.supportsVibration ? 1 : 0);
                sendSystemInfoEvent(category, "supportsImageEffects", SystemInfo.supportsImageEffects ? "yes" : "no", SystemInfo.supportsImageEffects ? 1 : 0);
                PlayerPrefs.SetInt(prefKey, getPOSIXTime());
                PlayerPrefs.Save();
            } // sendSystemInfo
        } // !gua.analyticsDisabled

        if (sendExceptions &&
            (!Application.isEditor || sendExceptionsAlsoFromEditor))
        {
#           if !UNITY_3_5 && !UNITY_4_0 && !UNITY_4_1 && !UNITY_4_2 && !UNITY_4_3 && !UNITY_4_5 && !UNITY_4_6
            // Unity 5.0+:
            Application.logMessageReceived += Callback_HandleLog;
#           else
            Application.RegisterLogCallback(Callback_HandleLog);
#           endif
        }
Пример #24
0
      void FillAnalyticsInfo(Analytics.MessageCache info)
      {
         info.SchemaVersion = GMap.NET.Analytics.SchemaVersionValue.Item020000;

         info.Id = Guid.NewGuid();
         info.ApplicationGroupId = SessionIdGuid;

         info.Business = new GMap.NET.Analytics.BusinessInformation();
         info.Business.CompanyId = CompanyIdGuid;
         info.Business.CompanyName = "*****@*****.**";

         info.TimeSentUtc = DateTime.UtcNow;

         info.ApiLanguage = ".NET CLR";
         info.ApiVersion = "2.1.4.0";

         info.Application = new Analytics.ApplicationInformation();
         info.Application.Id = ApplicationIdGuid;
         info.Application.Name = "GMap.NET";
         info.Application.ApplicationType = SystemType;
         info.Application.Version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
      }
Пример #25
0
    public void HasMatchingPattern_HistoricProfileAndItemExists_ShouldReturnTrue([Content] Item profileItem, Contact contact, ITracker tracker, Analytics.Tracking.Profile profile)
    {
      //Arrange
      tracker.Contact.Returns(contact);
      var behaviorPattern = Substitute.For<IBehaviorProfileContext>();
      behaviorPattern.PatternId.Returns(profileItem.ID);
      contact.BehaviorProfiles[Arg.Is(profileItem.ID)].Returns(behaviorPattern);

      var pattern = profileItem.Add("fakePattern", new TemplateID(PatternCardItem.TemplateID));
      profile.PatternId = pattern.ID.Guid;
      var fakeSiteContext = new FakeSiteContext("fake")
      {
        Database = Database.GetDatabase("master")
      };


      using (new TrackerSwitcher(tracker))
      {
        using (new SiteContextSwitcher(fakeSiteContext))
        {
          var provider = new ProfileProvider();
          provider.HasMatchingPattern(new ProfileItem(profileItem), ProfilingTypes.Historic).Should().BeTrue();
        }
      }
    }
Пример #26
0
        private void DuplicateQuote_Click(object sender, RoutedEventArgs e)
        {
            Analytics.TrackEvent("Quotes - Create DUPLICATE Quote");
            Analytics.TrackEvent("DEBUG - #1 SHOW/HIDE GRIDS");
            //First Setup the form to create a new quote
            quoteinfo.Visibility        = Visibility.Collapsed;
            quoteitemdetails.Visibility = Visibility.Collapsed;
            quoteBtn.Visibility         = Visibility.Collapsed;
            quoteSearchBtn.Visibility   = Visibility.Collapsed;
            addQuoteBtn.Visibility      = Visibility.Visible;
            newquote.Visibility         = Visibility.Visible;
            newQuoteDataGrid.Visibility = Visibility.Visible;
            QID.Visibility      = Visibility.Collapsed;
            lblLocation.Text    = "Quotes | Duplicate Existing Quote";
            newquote.IsSelected = true;
            Properties.Settings.Default.Status = "*** DUPLICATE QUOTE ENTRY ***";
            Properties.Settings.Default.Save();
            // Normally we would now clear all the data from the view to prep for new - Here we will only clear certain fields
            Analytics.TrackEvent("DEBUG - #2 CLEAR OUT FIELDS");
            foreach (var child in newQuoteDataGrid.Children)
            {
                //   var tb = child as TextBox;
                //   if (tb != null)
                //   {
                //       tb.Text = "";
                //   }
            }
            //We will still clear the checkboxes so the rep can ensure they are correct
            Analytics.TrackEvent("DEBUG - #3 CLEAR OUT CHECK BOXES");
            foreach (var child in newQuoteDataGrid.Children)
            {
                var cb = child as CheckBox;
                if (cb != null)
                {
                    cb.IsChecked = false;
                }
            }
            //Add some pre-defined text before starting the quote
            Analytics.TrackEvent("DEBUG - #4 ADD PRE-DEFINED TEXT");
            add_quotedate.SelectedDate = DateTime.Now;
            add_siteaddress.Text       = "Same As Address";
            add_salesrep.Text          = Properties.Settings.Default.Name;
            add_repID.Text             = Properties.Settings.Default.Qid;
            TitleUpdate();

            Analytics.TrackEvent("DEBUG - #5 CHECK IF NEWQUOTE IS VISIBLE");

            //   if (newquote.IsVisible)
            if (newquote.IsVisible)
            {
                // Create a new object because the old one
                // is being tracked by EF now.
                Analytics.TrackEvent("DEBUG - #6 DEFINE newQuote THEN ASSIGN TEXT FROM INSERTED INTO FIELDS");
                quote newQuote = new quote()
                {
                    Date1          = DateTime.Now,
                    Representative = Properties.Settings.Default.Name,
                    Company        = add_custname.Text,
                    Address        = add_custaddress.Text,
                    ContactPerson  = add_custcontact.Text,
                    Phone          = add_custphone.Text,
                    Mobile         = add_custmobile.Text,
                    Email          = add_custemail.Text,
                    StrataNo       = add_custstrata.Text,
                    RefNo          = add_custref.Text,
                    JobLocation    = add_siteaddress.Text,
                    SiteContact    = add_sitecontact.Text,
                    SCPhone        = add_sitephone.Text,
                    SCMobile       = add_sitemobile.Text,
                    SCEmail        = add_siteemail.Text,
                    Inductiontime  = add_indtime.Text,
                    Notes          = add_notes.Text,
                    repID          = Properties.Settings.Default.Qid,
                    //    Induction = add_induction.
                };
                {
                    Analytics.TrackEvent("DEBUG - #7 BRING VIEW INTO CONTEXT");
                    context.quotes.Local.Add(newQuote);
                    qtViewSource.View.Refresh();
                    qtViewSource.View.MoveCurrentTo(newQuote);
                }
                Analytics.TrackEvent("DEBUG - #8 SHOW/HIDE GRIDS");
                //Close the secondary ADD grid and move back to EXISTING grid
                newQuoteDataGrid.Visibility = Visibility.Collapsed;
                newquote.Visibility         = Visibility.Collapsed;
                btnAddCancel.Visibility     = Visibility.Collapsed;
                quoteSearchBtn.Visibility   = Visibility.Collapsed;
                quoteBtn.Visibility         = Visibility.Visible;
                addQuoteBtn.Visibility      = Visibility.Collapsed;
                quoteinfo.Visibility        = Visibility.Visible;
                quoteitemdetails.Visibility = Visibility.Visible;
                lblLocation.Text            = "Quotes | All Loaded";
                quoteinfo.IsSelected        = true;
            }    //Save to the database now all has been checked
            Analytics.TrackEvent("DEBUG - #9 SAVE CONTEXT TO DB");
            context.SaveChanges();
            qtViewSource.View.MoveCurrentToPrevious();
            qtViewSource.View.MoveCurrentToNext();
            TitleUpdate();
            Analytics.TrackEvent("DEBUG #10 END - COMPLETED DUPLICATION OF QUOTE");
        }
Пример #27
0
        private async void UpdateEnabled(object sender, CompoundButton.CheckedChangeEventArgs e)
        {
            await Analytics.SetEnabledAsync(e.IsChecked);

            AnalyticsEnabledSwitch.Checked = await Analytics.IsEnabledAsync();
        }
Пример #28
0
 public static void LOG_EVENT_WITH_DICT(string eventName, NSDictionary <NSString, NSObject> parameters)
 {
     Analytics.LogEvent(eventName, parameters);
 }
 public AcrylicDesignerPage()
 {
     InitializeComponent();
     Analytics.TrackEvent("Visited: AcrylicDesignerPage");
 }
Пример #30
0
 public void TrackUserActionAsync( Analytics.AnalyticsEvent action )
 {
     Topics.Radical.Analytics.AnalyticsServices.TrackUserActionAsync( action );
 }
Пример #31
0
 private void OnServerSave() => Analytics.Collect();
Пример #32
0
    protected void PopulateFilterUi()
    {
        if (itemId <= 0 || _hasRun)
            return;

        if (IsPostBack) {
            string oldFilterStatus = (IsUrlFilterStatusEmpty() ? String.Empty : tbUrlFilteringStatus.Text);
            tbUrlFilteringStatus.Text = String.Empty;

            // accept user-specified filtering URLs
            if (tbAddUrlFilter.Text.Length > 0) {
                AddListItem("/" + tbAddUrlFilter.Text.Trim('/'), true);
                tbAddUrlFilter.Text = String.Empty;
            }

            // add all url filters clicked
            if (Context.Request.Form["__EVENTTARGET"] != null && Context.Request.Form["__EVENTTARGET"] == this.btnUrlFilterAddAll.UniqueID) {
                foreach (ListItem li in cbl1.Items) {
                    li.Selected = true;
                }
            }

            // remove all url filters clicked
            if (Context.Request.Form["__EVENTTARGET"] != null && Context.Request.Form["__EVENTTARGET"] == this.btnUrlFilterRemoveAll.UniqueID) {
                foreach (ListItem li in cbl1.Items) {
                    li.Selected = false;
                }
            }

            // use each enabled (checked) url
            foreach (ListItem li in cbl1.Items) {
                if (li.Selected) {
                    _pagePaths.Add("/" + li.Value.Trim('/'));

                    if (tbUrlFilteringStatus.Text.Length > 0)
                        tbUrlFilteringStatus.Text += ", ";

                    tbUrlFilteringStatus.Text += "/" + li.Value.Trim('/');
                }
            }

            // fire any hooked handlers if selection has changed
            if (null != SelectionChanged && oldFilterStatus != tbUrlFilteringStatus.Text)
                SelectionChanged.Invoke(this, new EventArgs());

        } else {
            Analytics anl = new Analytics(ContentApiInstance.RequestInformationRef);
            string[] urls = anl.GetContentUrls(itemId);
            foreach (string url in urls) {
                if (!string.IsNullOrEmpty(url))
                    AddListItem("/" + url.Trim('/'), false);
            }
            foreach (ListItem li in cbl1.Items)
            {
                li.Selected = true;
                _pagePaths.Add("/" + li.Value.Trim('/'));
            }
        }

        _hasRun = true;

        if (tbUrlFilteringStatus.Text.Length == 0)
            tbUrlFilteringStatus.Text = GetMessage("lbl all urls allowed");
    }
Пример #33
0
        // App should wait for Sets fully loaded before opening files requested by user (by click or from cmd)
        // Open files from external links or cmd args on Sets Loaded
        private async void Sets_Loaded(object sender, RoutedEventArgs e)
        {
            int loadedCount = 0;

            if (!_loaded && AppSettingsService.IsSessionSnapshotEnabled)
            {
                try
                {
                    loadedCount = await SessionManager.LoadLastSessionAsync();
                }
                catch (Exception ex)
                {
                    LoggingService.LogError($"[{nameof(NotepadsMainPage)}] Failed to load last session: {ex}");
                    Analytics.TrackEvent("FailedToLoadLastSession", new Dictionary <string, string> {
                        { "Exception", ex.ToString() }
                    });
                }
            }

            if (_appLaunchFiles != null && _appLaunchFiles.Count > 0)
            {
                loadedCount += await OpenFiles(_appLaunchFiles);

                _appLaunchFiles = null;
            }
            else if (_appLaunchCmdDir != null)
            {
                var file = await FileSystemUtility.OpenFileFromCommandLine(_appLaunchCmdDir, _appLaunchCmdArgs);

                if (file != null && await OpenFile(file))
                {
                    loadedCount++;
                }
                _appLaunchCmdDir  = null;
                _appLaunchCmdArgs = null;
            }
            else if (_appLaunchUri != null)
            {
                var operation = NotepadsProtocolService.GetOperationProtocol(_appLaunchUri, out var context);
                if (operation == NotepadsOperationProtocol.OpenNewInstance || operation == NotepadsOperationProtocol.Unrecognized)
                {
                    // Do nothing
                }
                _appLaunchUri = null;
            }

            if (!_loaded)
            {
                if (loadedCount == 0)
                {
                    NotepadsCore.OpenNewTextEditor(_defaultNewFileName);
                }

                if (!App.IsPrimaryInstance)
                {
                    NotificationCenter.Instance.PostNotification(_resourceLoader.GetString("App_ShadowWindowIndicator_Description"), 4000);
                }
                _loaded = true;
            }

            if (AppSettingsService.IsSessionSnapshotEnabled)
            {
                SessionManager.IsBackupEnabled = true;
                SessionManager.StartSessionBackup();
            }

            await BuildOpenRecentButtonSubItems();

            if (!App.IsGameBarWidget)
            {
                // An issue with the Game Bar extension model and Windows platform prevents the Notepads process from exiting cleanly
                // when more than one CoreWindow has been created, and NotepadsMainPage is the last to close. The common case for this
                // is to open Notepads in Game Bar, then open its settings, then close the settings and finally close Notepads.
                // This puts the process in a bad state where it will no longer open in Game Bar and the Notepads process is orphaned.
                // To work around this do not use the EnteredBackground event when running as a widget.
                // Microsoft is tracking this issue as VSO#25735260
                Application.Current.EnteredBackground -= App_EnteredBackground;
                Application.Current.EnteredBackground += App_EnteredBackground;

                Window.Current.CoreWindow.Activated -= CoreWindow_Activated;
                Window.Current.CoreWindow.Activated += CoreWindow_Activated;
            }
        }
 public void Write([Localizable(false)] string message, LogLevel logLevel)
 {
     Analytics.TrackEvent(message);
 }
Пример #35
0
 private void TrackEvent(object sender, EventArgs e)
 {
     Analytics.TrackEvent(EventNameText.Text, mEventProperties.Count > 0 ? mEventProperties : null);
     mEventProperties.Clear();
     PropertiesCountLabel.Text = mEventProperties.Count.ToString();
 }
Пример #36
0
 public void Handle(CardDescriptionChanged message)
 {
     Analytics.TagEvent("Update_Card_Description");
     Handle(api => api.Cards.ChangeDescription(new CardId(message.CardId), message.Description));
 }
Пример #37
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            InitElements();

            backBn.TouchUpInside += (s, e) =>
            {
                this.NavigationController.PopViewController(true);
            };
            if (!methods.IsConnected())
            {
                NoConnectionViewController.view_controller_name = GetType().Name;
                this.NavigationController.PushViewController(storyboard.InstantiateViewController(nameof(NoConnectionViewController)), false);
                return;
            }
            nextBn.TouchUpInside += async(s, e) =>
            {
                if (String.IsNullOrEmpty(EmailTextField.Text))
                {
                    UIAlertView alert_empty = new UIAlertView()
                    {
                        Title = "Введите email"
                    };
                    alert_empty.AddButton("OK");
                    alert_empty.Show();
                }
                else
                {
                    try
                    {
                        ConfirmEmailViewControllerNew.email_value = methods.EmailValidation(EmailTextField.Text);

                        activityIndicator.Hidden = false;
                        nextBn.Hidden            = true;
                        var    deviceName = UIDevice.CurrentDevice.Name;//IdentifierForVendor.ToString();
                        var    UDID       = UIDevice.CurrentDevice.IdentifierForVendor.ToString();
                        string res        = null;
                        try
                        {
                            res = await accountActions.AccountVerification(deviceName, EmailTextField.Text.ToLower(), UDID);
                        }
                        catch
                        {
                            if (!methods.IsConnected())
                            {
                                InvokeOnMainThread(() =>
                                {
                                    NoConnectionViewController.view_controller_name = GetType().Name;
                                    this.NavigationController.PushViewController(storyboard.InstantiateViewController(nameof(NoConnectionViewController)), false);
                                    return;
                                });
                            }
                            return;
                        }
                        Analytics.TrackEvent($"{deviceName} {res}");

                        activityIndicator.Hidden = true;
                        nextBn.Hidden            = false;
                        string      error_message = "";
                        UIAlertView alert         = new UIAlertView()
                        {
                            Title   = "Ошибка",
                            Message = "Что-то пошло не так."
                        };
                        if (res.ToLower().Contains(Constants.alreadyDone.ToLower()))
                        {
                            var possibleRepeat = TimeZone.CurrentTimeZone.ToLocalTime(databaseMethods.GetRepeatAfter());
                            var hour           = possibleRepeat.Hour.ToString();
                            var minute         = possibleRepeat.Minute.ToString();
                            var second         = possibleRepeat.Second.ToString();
                            if (hour.Length < 2)
                            {
                                hour = "0" + hour;
                            }
                            if (minute.Length < 2)
                            {
                                minute = "0" + minute;
                            }
                            if (second.Length < 2)
                            {
                                second = "0" + second;
                            }
                            alert.Message = "Запрос был выполнен ранее. Следующий можно будет выполнить после "
                                            + hour + ":" + minute + ":" + second;
                            alert.AddButton("OK");
                            alert.Show();
                            return;
                        }
                        if (res.Contains("SubscriptionConstraint") || String.IsNullOrEmpty(res))
                        {
                            error_message = "_";
                            var vc = storyboard.InstantiateViewController(nameof(EmailAlreadyRegisteredViewController));
                            this.NavigationController.PushViewController(vc, true);
                        }
                        else if (res.Contains("The Email field is not a valid e-mail address"))
                        {
                            error_message = "Неверный формат почты";
                        }
                        if (!String.IsNullOrEmpty(error_message))
                        {
                            if (!error_message.Contains("_"))
                            {
                                alert = new UIAlertView()
                                {
                                    Title   = "Ошибка",
                                    Message = error_message
                                };
                                alert.AddButton("OK");
                                alert.Show();
                            }
                        }
                        if (res.Contains("actionJwt"))
                        {
                            var deserialized_value = JsonConvert.DeserializeObject <AccountVerificationModel>(res);
                            databaseMethods.InsertActionJwt(deserialized_value.actionJwt);
                            Analytics.TrackEvent($"{"actionJwt:"} {deserialized_value.actionJwt}");
                            EmailViewControllerNew.actionToken = deserialized_value.actionToken;
                            EmailViewControllerNew.repeatAfter = deserialized_value.repeatAfter;
                            EmailViewControllerNew.validTill   = deserialized_value.validTill;
                            databaseMethods.InsertValidTillRepeatAfter(EmailViewControllerNew.validTill, EmailViewControllerNew.repeatAfter, ConfirmEmailViewControllerNew.email_value);
                            var vc = storyboard.InstantiateViewController(nameof(WaitingEmailConfirmViewController));
                            this.NavigationController.PushViewController(vc, true);
                        }
                    }
                    catch
                    {
                        UIAlertView alert_empty = new UIAlertView()
                        {
                            Title = "Email некорректен"
                        };
                        alert_empty.AddButton("OK");
                        alert_empty.Show();
                    }
                }
            };
            EmailTextField.EditingChanged += (s, e) =>
            {
                email_value = EmailTextField.Text;
            };

            email_value = databaseMethods.GetEmailFromValidTill_RepeatAfter();
            var timer = new System.Timers.Timer();

            timer.Interval = 400;
            timer.Elapsed += delegate
            {
                timer.Stop();
                timer.Dispose();
                InvokeOnMainThread(() =>
                {
                    if (!String.IsNullOrEmpty(email_value))
                    {
                        EmailTextField.BecomeFirstResponder();
                        EmailTextField.Text = email_value;
                    }
                });
            };
            timer.Start();
        }
Пример #38
0
 public void Handle(CardDueDateChanged message)
 {
     Analytics.TagEvent("Update_Card_Due");
     Handle(api => api.Cards.ChangeDueDate(new CardId(message.CardId), message.DueDate));
 }
Пример #39
0
        // key goal is to create background tracer that is independent of request.
        public static async Task <bool> PerformBackgroundDeployment(
            DeploymentInfoBase deployInfo,
            IEnvironment environment,
            IDeploymentSettingsManager settings,
            TraceLevel traceLevel,
            Uri uri,
            bool waitForTempDeploymentCreation)
        {
            var tracer       = traceLevel <= TraceLevel.Off ? NullTracer.Instance : new CascadeTracer(new XmlTracer(environment.TracePath, traceLevel), new ETWTracer(environment.RequestId, "POST"));
            var traceFactory = new TracerFactory(() => tracer);

            var backgroundTrace = tracer.Step(XmlTracer.BackgroundTrace, new Dictionary <string, string>
            {
                { "url", uri.AbsolutePath },
                { "method", "POST" }
            });

            // For waiting on creation of temp deployment
            var tempDeploymentCreatedTcs = new TaskCompletionSource <object>();

            // For determining whether or not we failed to create the deployment due to lock contention.
            // Needed for deployments where deferred deployment is not allowed. Will be set to false if
            // lock contention occurs and AllowDeferredDeployment is false, otherwise true.
            var deploymentWillOccurTcs = new TaskCompletionSource <bool>();

            // This task will be let out of scope intentionally
            var deploymentTask = Task.Run(() =>
            {
                try
                {
                    // lock related
                    string lockPath           = Path.Combine(environment.SiteRootPath, Constants.LockPath);
                    string deploymentLockPath = Path.Combine(lockPath, Constants.DeploymentLockFile);
                    string statusLockPath     = Path.Combine(lockPath, Constants.StatusLockFile);
                    string hooksLockPath      = Path.Combine(lockPath, Constants.HooksLockFile);
                    var statusLock            = new LockFile(statusLockPath, traceFactory);
                    var hooksLock             = new LockFile(hooksLockPath, traceFactory);
                    var deploymentLock        = DeploymentLockFile.GetInstance(deploymentLockPath, traceFactory);

                    var analytics = new Analytics(settings, new ServerConfiguration(), traceFactory);
                    var deploymentStatusManager = new DeploymentStatusManager(environment, analytics, statusLock);
                    var siteBuilderFactory      = new SiteBuilderFactory(new BuildPropertyProvider(), environment);
                    var webHooksManager         = new WebHooksManager(tracer, environment, hooksLock);
                    var deploymentManager       = new DeploymentManager(siteBuilderFactory, environment, traceFactory, analytics, settings, deploymentStatusManager, deploymentLock, NullLogger.Instance, webHooksManager);
                    var fetchDeploymentManager  = new FetchDeploymentManager(settings, environment, tracer, deploymentLock, deploymentManager, deploymentStatusManager);

                    IDisposable tempDeployment = null;

                    try
                    {
                        // Perform deployment
                        deploymentLock.LockOperation(() =>
                        {
                            deploymentWillOccurTcs.TrySetResult(true);

                            ChangeSet tempChangeSet = null;
                            if (waitForTempDeploymentCreation)
                            {
                                // create temporary deployment before the actual deployment item started
                                // this allows portal ui to readily display on-going deployment (not having to wait for fetch to complete).
                                // in addition, it captures any failure that may occur before the actual deployment item started
                                tempDeployment = deploymentManager.CreateTemporaryDeployment(
                                    Resources.ReceivingChanges,
                                    out tempChangeSet,
                                    deployInfo.TargetChangeset,
                                    deployInfo.Deployer);

                                tempDeploymentCreatedTcs.TrySetResult(null);
                            }

                            fetchDeploymentManager.PerformDeployment(deployInfo, tempDeployment, tempChangeSet).Wait();
                        }, "Performing continuous deployment", TimeSpan.Zero);
                    }
                    catch (LockOperationException)
                    {
                        if (tempDeployment != null)
                        {
                            tempDeployment.Dispose();
                        }

                        if (deployInfo.AllowDeferredDeployment)
                        {
                            deploymentWillOccurTcs.TrySetResult(true);

                            using (tracer.Step("Update pending deployment marker file"))
                            {
                                // REVIEW: This makes the assumption that the repository url is the same.
                                // If it isn't the result would be buggy either way.
                                FileSystemHelpers.SetLastWriteTimeUtc(fetchDeploymentManager._markerFilePath, DateTime.UtcNow);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    tracer.TraceError(ex);
                }
                finally
                {
                    // Will no-op if already set
                    deploymentWillOccurTcs.TrySetResult(false);
                    backgroundTrace.Dispose();
                }
            });

#pragma warning disable 4014
            // Run on BG task (Task.Run) to avoid ASP.NET Request thread terminated with request completion and
            // it doesn't get chance to clean up the pending marker.
            Task.Run(() => PostDeploymentHelper.TrackPendingOperation(deploymentTask, TimeSpan.Zero));
#pragma warning restore 4014

            // When the frontend/ARM calls /deploy with isAsync=true, it starts polling
            // the deployment status immediately, so it's important that the temp deployment
            // is created before we return.
            if (waitForTempDeploymentCreation)
            {
                // deploymentTask may return withoout creating the temp deployment (lock contention,
                // other exception), in which case just continue.
                await Task.WhenAny(tempDeploymentCreatedTcs.Task, deploymentTask);
            }

            // If deferred deployment is not permitted, we need to know whether or not the deployment was
            // successfully requested. Otherwise, to preserve existing behavior, we assume it was.
            if (!deployInfo.AllowDeferredDeployment)
            {
                return(await deploymentWillOccurTcs.Task);
            }
            else
            {
                return(true);
            }
        }
Пример #40
0
 public void Handle(CardNameChanged message)
 {
     Analytics.TagEvent("Update_Card_Name");
     Handle(api => api.Cards.ChangeName(new CardId(message.CardId), message.Name));
 }
        public override Task Initialize()
        {
            Analytics.TrackEvent(GetType().Name);

            return(base.Initialize());
        }
Пример #42
0
 public void Handle(CardCommented message)
 {
     Analytics.TagEvent("Comment_Card");
     Handle(api => api.Cards.AddComment(new CardId(message.CardId), message.Text));
 }
Пример #43
0
        public void RetryServerErrorWithDefaultMaxRetryTimeTestNetStandard20()
        {
            Stopwatch watch          = new Stopwatch();
            string    DummyServerUrl = "http://localhost:8181";

            using (var DummyServer = new WebServer(DummyServerUrl))
            {
                // Set invalid host address and make timeout to 1s
                var config = new Config().SetAsync(false);
                config.SetHost(DummyServerUrl);
                config.SetTimeout(new TimeSpan(0, 0, 1));
                Analytics.Initialize(Constants.WRITE_KEY, config);

                var TestCases = new RetryErrorTestCase[]
                {
                    // The errors (500 > code >= 400) doesn't require retry
                    new RetryErrorTestCase()
                    {
                        ErrorMessage  = "Server Gone",
                        ResponseCode  = HttpStatusCode.Gone,
                        ShouldRetry   = false,
                        Timeout       = 10000,
                        BaseActionUrl = "/ServerGone"
                    },
                    // 429 error requires retry
                    new RetryErrorTestCase()
                    {
                        ErrorMessage  = "Too many requests",
                        ResponseCode  = (HttpStatusCode)429,
                        ShouldRetry   = true,
                        Timeout       = 10000,
                        BaseActionUrl = "/TooManyRequests"
                    },
                    // Server errors require retry
                    new RetryErrorTestCase()
                    {
                        ErrorMessage  = "Bad Gateway",
                        ResponseCode  = HttpStatusCode.BadGateway,
                        ShouldRetry   = true,
                        Timeout       = 10000,
                        BaseActionUrl = "/BadGateWay"
                    }
                };

                foreach (var testCase in TestCases)
                {
                    // Setup Action module which returns error code
                    var actionModule = new ActionModule(testCase.BaseActionUrl, HttpVerbs.Any, (ctx) =>
                    {
                        return(ctx.SendStandardHtmlAsync((int)testCase.ResponseCode));
                    });
                    DummyServer.WithModule(actionModule);
                }

                DummyServer.RunAsync();

                foreach (var testCase in TestCases)
                {
                    Analytics.Client.Config.SetHost(DummyServerUrl + testCase.BaseActionUrl);
                    // Calculate working time for Identiy message with invalid host address
                    watch.Reset();
                    watch.Start();
                    Actions.Identify(Analytics.Client);
                    watch.Stop();

                    Assert.AreEqual(0, Analytics.Client.Statistics.Succeeded);

                    // Handling Identify message will less than 10s because the server returns GONE message.
                    // That's because it retries submit when it's failed.
                    if (testCase.ShouldRetry)
                    {
                        Assert.IsTrue(watch.ElapsedMilliseconds > testCase.Timeout);
                    }
                    else
                    {
                        Assert.IsFalse(watch.ElapsedMilliseconds > testCase.Timeout);
                    }
                }
            }
        }
Пример #44
0
        private void UpdateGeneratedDtos(ProjectItem projectItem, INativeTypesHandler typesHandler)
        {
            LogOutputWindow($"--- Updating ServiceStack Reference '{projectItem.Name}' ---", showPane: true);
            string projectItemPath = projectItem.GetFullPath();
            var    selectedFiles   = projectItem.DTE.SelectedItems.Cast <SelectedItem>().ToList();
            bool   isDtoSelected   = false;

            isDtoSelected = selectedFiles
                            .Any(item => typesHandler.IsHandledFileType(item.Name));

            //Handle FSharp file extension name change for DTO files, eg .dto.fs to .dtos.fs
            if (!isDtoSelected && typesHandler is FSharpNativeTypesHandler)
            {
                isDtoSelected = selectedFiles
                                .Any(item => item.Name.ToLowerInvariant()
                                     .EndsWith(".dto.fs"));
            }

            if (isDtoSelected)
            {
                string filePath = projectItemPath;
                var    existingGeneratedCode = File.ReadAllLines(filePath).Join(Environment.NewLine);

                if (!typesHandler.TryExtractBaseUrl(existingGeneratedCode, out var baseUrl))
                {
                    LogOutputWindow("Unable to read URL from DTO file. Please ensure the file was generated correctly from a ServiceStack server.");
                    return;
                }
                try
                {
                    var  options = typesHandler.ParseComments(existingGeneratedCode);
                    bool setSslValidationCallback = false;
                    //Don't set validation callback if one has already been set for VS.
                    if (ServicePointManager.ServerCertificateValidationCallback == null)
                    {
                        //Temp set validation callback to return true to avoid common dev server ssl certificate validation issues.
                        setSslValidationCallback = true;
                        ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
                    }

                    string updatedCode = typesHandler.GetUpdatedCode(baseUrl, options);
                    if (setSslValidationCallback)
                    {
                        //If callback was set to return true, reset back to null.
                        ServicePointManager.ServerCertificateValidationCallback = null;
                    }

                    try
                    {
                        File.WriteAllText(filePath, updatedCode);
                        bool optOutOfStats = dte.GetOptOutStatsSetting();
                        if (!optOutOfStats)
                        {
                            var langName = typesHandler.RelativeTypesUrl.Substring(6);
                            Analytics.SubmitAnonymousUpdateReferenceUsage(langName);
                        }
                    }
                    catch (Exception ex)
                    {
                        HandleException(ex, "ServiceStack Reference: File.WriteAllText()");
                    }
                }
                catch (Exception e)
                {
                    HandleException(e, "Failed to update ServiceStack Reference: Unhandled error");
                }

                LogOutputWindow("--- Update ServiceStack Reference Complete ---");
            }
            else
            {
                LogOutputWindow("--- Valid file not found ServiceStack Reference '" + projectItem.Name + "' ---");
            }
        }
Пример #45
0
        private void m_btnOk_Click(object sender, EventArgs e)
        {
            DisableForm(true);

            QuoteSystem currentQuoteSystem = CurrentQuoteSystem;

            if (currentQuoteSystem == m_project.QuoteSystem)
            {
                if ((m_project.QuoteSystemStatus & QuoteSystemStatus.NotParseReady) > 0)
                {
                    m_project.QuoteSystemStatus = QuoteSystemStatus.Reviewed;
                    // Kicks off the quote parse (which we haven't run yet)
                    m_project.QuoteSystem = currentQuoteSystem;
                }
                else
                {
                    HandleAnalysisCompleted(this, null);
                }
                return;
            }

            string validationMessage;

            if (!ValidateQuoteSystem(currentQuoteSystem, out validationMessage))
            {
                MessageBox.Show(validationMessage, LocalizationManager.GetString("DialogBoxes.QuotationMarksDlg.QuoteSystemInvalid", "Quote System Invalid"));
                DisableForm(false);
                return;
            }
            if (m_project.Books.SelectMany(b => b.Blocks).Any(bl => bl.UserConfirmed) && m_project.IsQuoteSystemReadyForParse && m_project.QuoteSystem != null)
            {
                string part1 = LocalizationManager.GetString("DialogBoxes.QuotationMarksDlg.QuoteSystemChangePart1", "Changing the quote system will require the text to be broken up into speaking parts again.  An attempt will be made to preserve the work you have already completed, but some character assignments might be lost.  A backup of your project will be created before this occurs.");
                string part2 = LocalizationManager.GetString("DialogBoxes.QuotationMarksDlg.QuoteSystemChangePart2", "Are you sure you want to change the quote system?");
                string msg   = part1 + Environment.NewLine + Environment.NewLine + part2;
                string title = LocalizationManager.GetString("DialogBoxes.QuotationMarksDlg.ConfirmQuoteSystemChange", "Confirm Quote System Change");
                if (MessageBox.Show(msg, title, MessageBoxButtons.YesNo) != DialogResult.Yes)
                {
                    SetupQuoteMarksComboBoxes(m_project.QuoteSystem);
                    DisableForm(false);
                    return;
                }
            }

            if (m_project.QuoteSystemStatus == QuoteSystemStatus.Obtained)
            {
                Analytics.Track("ObtainedQuoteSystemChanged", new Dictionary <string, string>
                {
                    { "old", m_project.QuoteSystem != null ? m_project.QuoteSystem.ToString() : String.Empty },
                    { "new", currentQuoteSystem.ToString() }
                });
            }
            else if (m_project.QuoteSystemStatus != QuoteSystemStatus.UserSet)
            {
                Analytics.Track("GuessedQuoteSystemChanged", new Dictionary <string, string>
                {
                    { "old", m_project.QuoteSystem != null ? m_project.QuoteSystem.ToString() : String.Empty },
                    { "new", currentQuoteSystem.ToString() }
                });
            }

            // Want to set the status even if already UserSet because that triggers setting QuoteSystemDate
            m_project.QuoteSystemStatus = QuoteSystemStatus.UserSet;

            m_project.QuoteSystem = currentQuoteSystem;
        }
 partial void VisitLostCousinsWebsiteClicked(NSObject sender)
 {
     SpecialMethods.VisitWebsite("http://www.lostcousins.com/?ref=LC585149");
     Analytics.TrackAction(Analytics.LostCousinsAction, Analytics.LCWebLinkEvent);
 }
        /// <summary>
        /// Constructor for the Application object.
        /// </summary>
        public App()
        {
            // Global handler for uncaught exceptions.
            UnhandledException += Application_UnhandledException;

            // Standard Silverlight initialization
            InitializeComponent();

            // Phone-specific initialization
            InitializePhoneApplication();

            // Show graphics profiling information while debugging.
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // Display the current frame rate counters.
                Application.Current.Host.Settings.EnableFrameRateCounter = true;

                // Show the areas of the app that are being redrawn in each frame.
                //Application.Current.Host.Settings.EnableRedrawRegions = true;

                // Enable non-production analysis visualization mode,
                // which shows areas of a page that are being GPU accelerated with a colored overlay.
                //Application.Current.Host.Settings.EnableCacheVisualization = true;

                // Disable the application idle detection by setting the UserIdleDetectionMode property of the
                // application's PhoneApplicationService object to Disabled.
                // Caution:- Use this under debug mode only. Application that disables user idle detection will continue to run
                // and consume battery power when the user is not using the phone.
                PhoneApplicationService.Current.UserIdleDetectionMode = IdleDetectionMode.Disabled;
            }

            //Retrieves locale of the mobile device
            CurrentCulture = Thread.CurrentThread.CurrentCulture.ToString();
            CurrentUICulture = Thread.CurrentThread.CurrentUICulture.ToString();

            var uris = new[]
            {
                GetThemeSettingsUri()
            };

            LoadResources(uris);

            //Creates an instance of the Diagnostics component.
            diagnostics = new RadDiagnostics();

            //Defines the default email where the diagnostics info will be send.
            diagnostics.EmailTo = "*****@*****.**";

            //Initializes this instance.
            diagnostics.Init();

              //Creates a new instance of the RadRateApplicationReminder component.
            rateReminder = new RadRateApplicationReminder();

            //Sets how often the rate reminder is displayed.
            rateReminder.RecurrencePerUsageCount = 2;

            IsTrackImageLoad = false;
            AppVersion = "";

            DataTracker = new Tracker();
            DataTracker.RegisterNewDeviceIfNotAlready();

            DownloadCloudAppConfig();
            //LoadDefaultCloudAppConfig();

            _analytics = Analytics.GetInstance();
            //_timeLaunch = DateTime.Now;

            //Initialize user config
            var u = MiscHelpers.GetItemFromIsolatedStorage<UserConfigModel>("fbd-userconfig.xml");
            if (u == null)
            {
                u = new UserConfigModel
                    {
                        FetchLanguage = FetchLanguages.en,
                        FontSize = FontSizes.medium,
                        //FacebookLogin = FacebookLoginStatus.Logout,
                        FacebppkAccessToken = String.Empty,
                        IsTutorialRead = new int[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
                    };
                MiscHelpers.SaveDataToIsolatedStorage("fbd-userconfig.xml", u, typeof (UserConfigModel));

                //Set default hometiles and fetch the corrsponding context
                HomePagePinTiles.GetInstance().InitTiles();
            }
            DataFetcher dataFetcher2 = DataFetcher.GetInstance();
            dataFetcher2.FetchCategories(null);

            UserConfig.FetchLanguage = u.FetchLanguage;
            UserConfig.FontSize = u.FontSize;
            //UserConfig.FacebookLogin = u.FacebookLogin;
            //UserConfig.FacebppkAccessToken = u.FacebppkAccessToken;
            App.AccessToken = u.FacebppkAccessToken;
            UserConfig.IsTutorialRead = u.IsTutorialRead;
            if (UserConfig.IsTutorialRead == null)
            {
                u.IsTutorialRead = new int[] {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
                MiscHelpers.SaveDataToIsolatedStorage("fbd-userconfig.xml", u, typeof(UserConfigModel));
            }

            //Initialize categories config
            DataFetcher fetcher = DataFetcher.GetInstance();
            CategoryConfigA.Config = fetcher.GetCategoryConfig(
                new Uri("CategoryConfig_" + CultureSelector.GetCultureLocale(CurrentUICulture) + ".json", UriKind.Relative)
            );
            CategoryConfigB.Config = fetcher.GetCategoryConfig(
                new Uri("CategoryConfig_" + UserConfig.FetchLanguage + ".json", UriKind.Relative)
            );

            BackgroundWorker bw = new BackgroundWorker();
            bw.WorkerSupportsCancellation = true;
            bw.WorkerReportsProgress = true;
            bw.DoWork += delegate
            {
                //Initial file management
                //FileHelper.RemoveAllFeedBoardFiles();
                //Removed all feedboard cache files
                FileHelper.RemoveFeedBoardCaches();
                FileHelper.RemoveRedundantFeedBoardFiles();
                //FileHelper.ViewFiles();

                //Prefetcher
                DataFetcher dataFetcher = DataFetcher.GetInstance();
                dataFetcher.PreFetch();
            };
            bw.RunWorkerAsync();

            //Background agent
            BackgroundAgent b = new BackgroundAgent();
            //b.StartPeriodicAgent();
            b.StartResourceIntensiveAgent();
        }
Пример #48
0
 protected override void InitializeTarget()
 {
     Analytics.Initialize(WriteKey);
     base.InitializeTarget();
 }
Пример #49
0
    public void HasMatchingPattern_ItemExists_ShouldReturnTrue([Content] Item profileItem, CurrentInteraction currentInteraction, ITracker tracker, Analytics.Tracking.Profile profile)
    {
      tracker.Interaction.Returns(currentInteraction);
      currentInteraction.Profiles[null].ReturnsForAnyArgs(profile);

      var pattern = profileItem.Add("fakePattern", new TemplateID(PatternCardItem.TemplateID));
      profile.PatternId = pattern.ID.Guid;
      var fakeSiteContext = new FakeSiteContext("fake")
      {
        Database = Database.GetDatabase("master")
      };


      using (new TrackerSwitcher(tracker))
      {
        using (new SiteContextSwitcher(fakeSiteContext))
        {
          var provider = new ProfileProvider();
          provider.HasMatchingPattern(new ProfileItem(profileItem), ProfilingTypes.Active).Should().BeTrue();
        }
      }
    }
Пример #50
0
        public Result ExecuteCommand(DynamoRevitCommandData commandData)
        {
            var startupTimer = Stopwatch.StartNew();

            if (ModelState == RevitDynamoModelState.StartedUIless)
            {
                if (CheckJournalForKey(commandData, JournalKeys.ShowUiKey, true) ||
                    CheckJournalForKey(commandData, JournalKeys.ModelShutDownKey))
                {
                    //When we move from UIless to UI we prefer to start with a fresh revitDynamoModel
                    //in order to benefit from a startup sequence similar to Dynamo Revit UI launch.
                    //Also there might be other situations which demand a new revitDynamoModel.
                    //In order to be able to address them we process ModelShutDownKey.
                    //An example of this situation is when you have a revitDynamoModel already started and you switch
                    //the document in Revit. Since revitDynamoModel is well connected to the previous document we need to
                    //shut it down and start a new one in order to able to run a graph in the new document.
                    revitDynamoModel.ShutDown(false);
                    ModelState = RevitDynamoModelState.NotStarted;
                }
                else
                {
                    TryOpenAndExecuteWorkspaceInCommandData(commandData);
                    return(Result.Succeeded);
                }
            }

            if (ModelState == RevitDynamoModelState.StartedUI)
            {
                TryOpenAndExecuteWorkspaceInCommandData(commandData);
                return(Result.Succeeded);
            }

            HandleDebug(commandData);

            InitializeCore(commandData);
            //subscribe to the assembly load
            AppDomain.CurrentDomain.AssemblyLoad += AssemblyLoad;

            try
            {
                extCommandData = commandData;

                UpdateSystemPathForProcess();

                // create core data models
                revitDynamoModel = InitializeCoreModel(extCommandData);
                revitDynamoModel.UpdateManager.RegisterExternalApplicationProcessId(Process.GetCurrentProcess().Id);
                revitDynamoModel.Logger.Log("SYSTEM", string.Format("Environment Path:{0}", Environment.GetEnvironmentVariable("PATH")));

                // handle initialization steps after RevitDynamoModel is created.
                revitDynamoModel.HandlePostInitialization();
                ModelState = RevitDynamoModelState.StartedUIless;

                // show the window
                if (CheckJournalForKey(extCommandData, JournalKeys.ShowUiKey, true))
                {
                    dynamoViewModel = InitializeCoreViewModel(revitDynamoModel);

                    // Let the host (e.g. Revit) control the rendering mode
                    var save = RenderOptions.ProcessRenderMode;
                    InitializeCoreView().Show();
                    RenderOptions.ProcessRenderMode = save;
                    revitDynamoModel.Logger.Log(Dynamo.Applications.Properties.Resources.WPFRenderMode + RenderOptions.ProcessRenderMode.ToString());

                    ModelState = RevitDynamoModelState.StartedUI;
                    // Disable the Dynamo button to prevent a re-run
                    DynamoRevitApp.DynamoButtonEnabled = false;
                }

                //foreach preloaded exception send a notification to the Dynamo Logger
                //these are messages we want the user to notice.
                preLoadExceptions.ForEach(x => revitDynamoModel.Logger.LogNotification
                                              (revitDynamoModel.GetType().ToString(),
                                              x.GetType().ToString(),
                                              DynamoApplications.Properties.Resources.MismatchedAssemblyVersionShortMessage,
                                              x.Message));

                TryOpenAndExecuteWorkspaceInCommandData(extCommandData);

                //unsubscribe to the assembly load
                AppDomain.CurrentDomain.AssemblyLoad -= AssemblyLoad;
                Analytics.TrackStartupTime("DynamoRevit", startupTimer.Elapsed, ModelState.ToString());
            }
            catch (Exception ex)
            {
                // notify instrumentation
                Analytics.TrackException(ex, true);

                MessageBox.Show(ex.ToString());

                DynamoRevitApp.DynamoButtonEnabled = true;

                //If for some reason Dynamo has crashed while startup make sure the Dynamo Model is properly shutdown.
                if (revitDynamoModel != null)
                {
                    revitDynamoModel.ShutDown(false);
                    revitDynamoModel = null;
                }

                return(Result.Failed);
            }

            return(Result.Succeeded);
        }
Пример #51
0
    public void HasMatchingPattern_TrackerReturnsProfileWithoutID_ShouldReturnFalse([Content] Item profileItem, CurrentInteraction currentInteraction, ITracker tracker, Analytics.Tracking.Profile profile)
    {
      tracker.Interaction.Returns(currentInteraction);
      currentInteraction.Profiles[null].ReturnsForAnyArgs(profile);
      profile.PatternId = null;

      var fakeSiteContext = new FakeSiteContext("fake")
      {
        Database = Database.GetDatabase("master")
      };


      using (new TrackerSwitcher(tracker))
      {
        using (new SiteContextSwitcher(fakeSiteContext))
        {
          var provider = new ProfileProvider();
          provider.HasMatchingPattern(new ProfileItem(profileItem), ProfilingTypes.Active).Should().BeFalse();
        }
      }
    }
Пример #52
0
 public MainPage()
 {
     InitializeComponent();
     Analytics.TrackEvent("Another Custom Event");
 }
Пример #53
0
 public void SetUserId(string userId)
 {
     Analytics.SetUserId(userId);
 }
Пример #54
0
 public void SetScreenAndClassName(string screenName, string screenClassName)
 {
     Analytics.SetScreenNameAndClass(screenName, screenClassName);
 }
Пример #55
0
 protected override Analytics.ProtectAnalytics.IUserAction CreateAnalyticsEvent(Analytics.ProtectAnalytics.UserActionProperty[] properties)
 {
     return new Analytics.ProtectAnalytics.CleanUserAction()
     {
         Properties = properties
     };
 }
Пример #56
0
 protected abstract Analytics.ProtectAnalytics.IUserAction CreateAnalyticsEvent(Analytics.ProtectAnalytics.UserActionProperty[] properties);