/// <summary> /// Gets the match from the cache for the useragent or if not /// present in the cache from the detection provider. /// </summary> /// <param name="userAgent">The user agent whose properties are needed</param> /// <returns>A results object for the user agent</returns> private static InternalResult GetMatchByUserAgent(string userAgent) { InternalResult result; if (_cacheUserAgent._itemsActive.TryGetValue(userAgent, out result) == false) { // The result wasn't in the cache so find it from the 51Degrees provider. var match = _provider.Match(userAgent); // Construct the results for the values and the profile Ids. result = new InternalResult( new SortedList <string, string>(_numberOfProperties), match.ProfileIds.OrderBy(i => i.Key).SelectMany(i => BitConverter.GetBytes(i.Value)).ToArray()); // Load the values into the results. foreach (var property in _requiredProperties.SelectMany(i => i.Value)) { var values = match[property]; if (values != null) { result.Values.Add(property.Name, values.ToString()); } } // Load the dynamic values into the results. foreach (var dynamicProperty in _dynamicProperties) { // Add special properties for the detection. switch (dynamicProperty) { case DynamicProperties.Id: result.Values.Add("Id", String.Join( Constants.ProfileSeperator, match.ProfileIds.OrderBy(i => i.Key).Select(i => i.Value.ToString()))); break; case DynamicProperties.Difference: result.Values.Add("Difference", match.Difference.ToString()); break; case DynamicProperties.Method: result.Values.Add("Method", match.Method.ToString()); break; } } // Add the results to the cache. _cacheUserAgent._itemsActive[userAgent] = result; } // Ensure the result is added to the background cache. //_cacheUserAgent.SetBackground(userAgent, result); _cacheUserAgent.AddRecent(userAgent, result); return(result); }
/// <summary> /// In a single thread loops through the useragents in the file /// provided perform a match with the data set provided passing /// control back to the method provided for further processing. /// </summary> /// <param name="provider"></param> /// <param name="userAgents"></param> /// <param name="method"></param> /// <returns>Counts for each of the methods used</returns> internal static Results DetectLoopSingleThreaded(Provider provider, IEnumerable<string> userAgents, ProcessMatch method, object state) { provider.DataSet.ResetCache(); var match = provider.CreateMatch(); var results = new Results(); foreach (var line in userAgents) { provider.Match(line.Trim(), match); method(results, match, state); results.Count++; results.Methods[match.Method]++; } AssertPool(provider); ReportMethods(results.Methods); ReportProvider(provider); ReportTime(results); return results; }
/// <summary> /// Using multiple threads loops through the useragents in the file /// provided perform a match with the data set provided passing /// control back to the method provided for further processing. /// </summary> /// <param name="provider"></param> /// <param name="userAgents"></param> /// <param name="method"></param> /// <returns>Counts for each of the methods used</returns> internal static Results DetectLoopMultiThreaded(Provider provider, IEnumerable<string> userAgents, ProcessMatch method, object state) { provider.DataSet.ResetCache(); var results = new Results(); Parallel.ForEach(userAgents, line => { var match = provider.Match(line.Trim()); method(results, match, state); Interlocked.Increment(ref results.Count); lock (results.Methods) { results.Methods[match.Method] = results.Methods[match.Method] + 1; } }); AssertPool(provider); ReportMethods(results.Methods); ReportProvider(provider); ReportTime(results); return results; }
// Snippet Start public static void Run(string fileName) { // DataSet is the object used to interact with the data file. // StreamFactory creates Dataset with pool of binary readers to // perform device lookup using file on disk. DataSet dataSet = StreamFactory.Create(fileName, false); // Provides access to device detection functions. Provider provider = new Provider(dataSet); // Used to store and access detection results. Match match; // Contains boolean detection result for the IsMobile property. bool IsMobileBool; // User-Agent string of an iPhone mobile device. string mobileUserAgent = ("Mozilla/5.0 (iPhone; CPU iPhone " + "OS 7_1 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like " + "Gecko) 'Version/7.0 Mobile/11D167 Safari/9537.53"); // User-Agent string of Firefox Web browser version 41 on desktop. string desktopUserAgent = ("Mozilla/5.0 (Windows NT 6.3; " + "WOW64; rv:41.0) Gecko/20100101 Firefox/41.0"); // User-Agent string of a MediaHub device. string mediaHubUserAgent = ("Mozilla/5.0 (Linux; Android " + "4.4.2; X7 Quad Core Build/KOT49H) AppleWebKit/537.36 " + "(KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 " + "Safari/537.36"); Console.WriteLine("Starting Strongly Typed Example."); // Carries out a match for a mobile User-Agent. Console.WriteLine("\nMobile User-Agent: " + mobileUserAgent); match = provider.Match(mobileUserAgent); IsMobileBool = getIsMobileBool(match); if (IsMobileBool) { Console.WriteLine(" Mobile"); } else { Console.WriteLine(" Non-Mobile"); } // Carries out a match for a desktop User-Agent. Console.WriteLine("\nDesktop User-Agent: " + desktopUserAgent); match = provider.Match(desktopUserAgent); IsMobileBool = getIsMobileBool(match); if (IsMobileBool) { Console.WriteLine(" Mobile"); } else { Console.WriteLine(" Non-Mobile"); } // Carries out a match for a MediaHub User-Agent. Console.WriteLine("\nMediaHub User-Agent: " + mediaHubUserAgent); match = provider.Match(mediaHubUserAgent); IsMobileBool = getIsMobileBool(match); if (IsMobileBool) { Console.WriteLine(" Mobile"); } else { Console.WriteLine(" Non-Mobile"); } // Finally close the dataset, releasing resources and file locks. dataSet.Dispose(); }
// Snippet Start public static void Run(string fileName) { // DataSet is the object used to interact with the data file. // StreamFactory creates Dataset with pool of binary readers to // perform device lookup using file on disk. The type if // disposable and is therefore contained in using block to // ensure file handles and resources are freed. using (DataSet dataSet = StreamFactory.Create(fileName, false)) { // Provides access to device detection functions. Provider provider = new Provider(dataSet); // Used to store and access detection results. Match match; // Contains detection result for the IsMobile property. string IsMobile; // User-Agent string of an iPhone mobile device. string mobileUserAgent = ("Mozilla/5.0 (iPhone; CPU iPhone " + "OS 7_1 like Mac OS X) AppleWebKit/537.51.2 (KHTML, like " + "Gecko) 'Version/7.0 Mobile/11D167 Safari/9537.53"); // User-Agent string of Firefox Web browser version 41 on desktop. string desktopUserAgent = ("Mozilla/5.0 (Windows NT 6.3; " + "WOW64; rv:41.0) Gecko/20100101 Firefox/41.0"); // User-Agent string of a MediaHub device. string mediaHubUserAgent = ("Mozilla/5.0 (Linux; Android " + "4.4.2; X7 Quad Core Build/KOT49H) AppleWebKit/537.36 " + "(KHTML, like Gecko) Version/4.0 Chrome/30.0.0.0 " + "Safari/537.36"); Console.WriteLine("Staring Getting Started Example."); // Carries out a match for a mobile User-Agent. Console.WriteLine("\nMobile User-Agent: " + mobileUserAgent); match = provider.Match(mobileUserAgent); IsMobile = match["IsMobile"].ToString(); Console.WriteLine(" IsMobile: " + IsMobile); // Carries out a match for a desktop User-Agent. Console.WriteLine("\nDesktop User-Agent: " + desktopUserAgent); match = provider.Match(desktopUserAgent); IsMobile = match["IsMobile"].ToString(); Console.WriteLine(" IsMobile: " + IsMobile); // Carries out a match for a MediaHub User-Agent. Console.WriteLine("\nMediaHub User-Agent: " + mediaHubUserAgent); match = provider.Match(mediaHubUserAgent); IsMobile = match["IsMobile"].ToString(); Console.WriteLine(" IsMobile: " + IsMobile); // Returns the number of profiles that are Mobile. Console.WriteLine("\nNumber of mobile profiles: {0}", dataSet.FindProfiles("IsMobile", "True").Length); } }
// Snippet Start public static void Run(string fileName, string inputFile) { // DataSet is the object used to interact with the data file. // StreamFactory creates Dataset with pool of binary readers to // perform device lookup using file on disk. DataSet dataSet = StreamFactory.Create(fileName, false); // Provides access to device detection functions. Provider provider = new Provider(dataSet); // Used to store and access detection results. // Same match will be reused multiple times to avoid unnecessary // object creation. Match match = provider.CreateMatch();; // Name of the output file results will be saved to. string outputFile = "OfflineProcessingOutput.csv"; // How many lines of the input CSV file to read. const int linesToRead = 20; // Line currently being read. int currentLine = 0; // HTTP User-Agent string to match, taken from input the CSV file. string userAgent; // 51Degrees properties to append the CSV file with. // For the full list of properties see: // https://51degrees.com/resources/property-dictionary string[] properties = { "IsMobile", "PlatformName", "PlatformVersion" }; // Opens input and output files. StreamReader fin = new StreamReader(inputFile); StreamWriter fout = new StreamWriter(outputFile); Console.WriteLine("Starting Offline Processing Example."); // Print CSV headers to output file. fout.Write("User-Agent"); for (int i = 0; i < properties.Count(); i++) { fout.Write("|" + properties[i]); } fout.Write("\n"); while ((userAgent = fin.ReadLine()) != null && currentLine < linesToRead) { // Match current User-Agent. Match object reused. provider.Match(userAgent, match); // Write the User-Agent. fout.Write(userAgent); // Append properties. foreach (var property in properties) { fout.Write("|" + match[property]); } fout.Write("\n"); currentLine++; } fin.Close(); fout.Close(); Console.WriteLine("Output Written to " + outputFile); // Finally close the dataset, releasing resources and file locks. dataSet.Dispose(); }