public void Run(string dataFile) { FileInfo f = new FileInfo(dataFile); Console.WriteLine($"Using data file at '{f.FullName}'"); // Use the DeviceDetectionPipelineBuilder to build a new Pipeline // to use an on-premise Hash engine with the low memory // performance profile. using (var pipeline = new DeviceDetectionPipelineBuilder() .UseOnPremise(dataFile, null, false) // Prefer low memory profile where all data streamed // from disk on-demand. Experiment with other profiles. //.SetPerformanceProfile(PerformanceProfiles.HighPerformance) .SetPerformanceProfile(PerformanceProfiles.LowMemory) //.SetPerformanceProfile(PerformanceProfiles.Balanced) .Build()) { // First try a desktop User-Agent. AnalyseUserAgent(desktopUserAgent, pipeline); Console.WriteLine(); // Now try a mobile User-Agent. AnalyseUserAgent(mobileUserAgent, pipeline); Console.WriteLine(); // Now try the User Agent Client Hints. AnalyseUach(platformUach, pipeline); } }
public static bool IsMobileDevice( string userAgent ) { string resourceFileName = "51Degrees-LiteV4.1.hash"; string resourceName = Assembly.GetExecutingAssembly().GetManifestResourceNames() .Where(n => n.Contains(resourceFileName)) .FirstOrDefault(); var assembly = Assembly.GetExecutingAssembly(); var resourceStream = assembly.GetManifestResourceStream(resourceName); var fileInfo = new FileInfo(resourceName); // Testing for directory; disregard //var asdf = Assembly.GetTypes();//GetAssembly(typeof(FiftyOneDegreesMobileDeviceDetector)).Name; //using (var reader = new StreamReader(resourceStream, Encoding.UTF8)) //{ // return await reader.ReadToEndAsync(); //} //var folder1 = Assembly.GetExecutingAssembly(); //string assemblyFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); //string folder2 = Path.GetDirectoryName(Assembly.GetCallingAssembly().Location); //string folder3 = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); //var myType = typeof(FiftyOneDegreesMobileDeviceDetector); //var n = myType.Namespace; //string baseDirectory = AppContext.BaseDirectory; //string AssemblyPath = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\")); //var directory = new DirectoryInfo(Directory.GetCurrentDirectory()); //while (directory != null && !directory.GetFiles("*.sln").Any()) //{ // directory = directory.Parent; //} //var a = directory != null; var pipelineInstance = new DeviceDetectionPipelineBuilder() .UseOnPremise(resourceName, null, true) .SetPerformanceProfile(PerformanceProfiles.LowMemory) .UseResultsCache() .Build(); // Create a new FlowData instance ready to be populated with evidence for the // Pipeline. var data = pipelineInstance.CreateFlowData(); // Add a User-Agent string to the evidence collection. data.AddEvidence(FiftyOne.Pipeline.Core.Constants.EVIDENCE_QUERY_USERAGENT_KEY, userAgent); // Process the supplied evidence. data.Process(); // Get device data from the flow data. var device = data.Get <IDeviceData>(); return(device.IsMobile.HasValue ? device.IsMobile.Value : false); }
public void Run(string dataFile) { FileInfo f = new FileInfo(dataFile); Console.WriteLine($"Using data file at '{f.FullName}'"); Console.WriteLine($"---------------------------------------"); Console.WriteLine($"This example demonstrates detection " + $"using user-agent client hints."); Console.WriteLine($"The sec-ch-ua value can be used to " + $"determine the browser of the connecting device, " + $"but not other components such as the hardware."); Console.WriteLine($"Similarly, sec-ch-ua-platform and " + $"platform-version value can be used to " + $"determine the platform/operating system."); Console.WriteLine($"We show this by first performing " + $"detection with the sec-ch-ua fields only."); Console.WriteLine($"We then repeat with the user-agent " + $"header only."); Console.WriteLine($"Finally, we use both sec-ch-ua fields " + "and user-agent. Note that sec-ch-ua takes priority " + "over the user-agent for detection of the browser and" + "sec-ch-ua-platform and platform-version act similarly " + "for the platform."); Console.WriteLine($"---------------------------------------"); // Use the DeviceDetectionPipelineBuilder to build a new Pipeline // to use an on-premise Hash engine with the low memory // performance profile. using (var pipeline = new DeviceDetectionPipelineBuilder() .UseOnPremise(dataFile, null, false) // Prefer low memory profile where all data streamed // from disk on-demand. Experiment with other profiles. //.SetPerformanceProfile(PerformanceProfiles.HighPerformance) .SetPerformanceProfile(PerformanceProfiles.LowMemory) //.SetPerformanceProfile(PerformanceProfiles.Balanced) .Build()) { // first try with just sec-ch-ua. AnalyseClientHints(pipeline, false, true); Console.WriteLine(); // Now with just user-agent. AnalyseClientHints(pipeline, true, false); Console.WriteLine(); // Finally, perform detection with both. AnalyseClientHints(pipeline, true, true); } }
public void DeviceDetectionPipelineBuilder_CheckConfiguration( string datafilename, bool autoUpdate, bool shareUsage, string licenseKey) { var datafile = Utils.GetFilePath(datafilename); var updateService = new Mock <IDataUpdateService>(); // Configure the pipeline. var pipeline = new DeviceDetectionPipelineBuilder( new NullLoggerFactory(), null, updateService.Object) .UseOnPremise(datafile.FullName, licenseKey, false) .SetAutoUpdate(autoUpdate) .SetShareUsage(shareUsage) .Build(); // Check that the flow elements in the pipeline are as expected. if (shareUsage) { Assert.AreEqual(2, pipeline.FlowElements.Count); Assert.IsTrue(pipeline.FlowElements.Any( e => e.GetType() == typeof(ShareUsageElement))); } else { Assert.AreEqual(1, pipeline.FlowElements.Count); } Assert.IsTrue(pipeline.FlowElements.Any( e => e.GetType() == typeof(DeviceDetectionHashEngine))); // Get the device detection engine element and check that it has // been configured as specified. var engine = pipeline.FlowElements.Single( e => e.GetType() == typeof(DeviceDetectionHashEngine)) as DeviceDetectionHashEngine; if (licenseKey != null) { Assert.AreEqual(autoUpdate, engine.DataFiles[0].AutomaticUpdatesEnabled); Assert.AreEqual(licenseKey, engine.DataFiles[0].Configuration.DataUpdateLicenseKeys[0]); } else { // If there is no license key ocnifugred then automatic updates will be // disabled. Assert.AreEqual(false, engine.DataFiles[0].AutomaticUpdatesEnabled); } }
public void Run(string resourceKey, string cloudEndPoint = "") { var builder = new DeviceDetectionPipelineBuilder() // Tell it that we want to use cloud and pass our resource key. .UseCloud(resourceKey); // If a cloud endpoint has been provided then set the // cloud pipeline endpoint. if (string.IsNullOrWhiteSpace(cloudEndPoint) == false) { builder.SetEndPoint(cloudEndPoint); } // Create the pipeline using (var pipeline = builder.Build()) { // Output details for a mobile User-Agent. AnalyseUserAgent(mobileUserAgent, pipeline); } }
public void Run(string dataFile, string uaFile, int count) { FileInfo f = new FileInfo(dataFile); Console.WriteLine($"Using data file at '{f.FullName}'"); // Build a pipeline containing a Device Detection Hash engine // using the Device Detection Pipeline Builder. using (var pipeline = new DeviceDetectionPipelineBuilder() .UseOnPremise(dataFile, null, false) .SetDataFileSystemWatcher(false) .SetShareUsage(false) // Prefer maximum performance profile where all data loaded // into memory. Experiment with other profiles. .SetPerformanceProfile(PerformanceProfiles.MaxPerformance) //.SetPerformanceProfile(PerformanceProfiles.LowMemory) //.SetPerformanceProfile(PerformanceProfiles.Balanced) //.UseResultsCache() .SetUsePerformanceGraph(true) .SetUsePredictiveGraph(false) .Build()) { Run(uaFile, count, pipeline); } }
public void Run(string originalDataFile, string licenseKey) { // Copy the original data file to another location as we do not // want to preserve the original for other examples. File.Copy(originalDataFile, dataFile, true); FileInfo f = new FileInfo(dataFile); Console.WriteLine($"Using data file at '{f.FullName}'"); DateTime initialPublishedDate = DateTime.MinValue; // Create a temporary Device Detection 'Hash' Engine to check the initial published date of the data file. // There is no need to do this in production, it is for demonstration purposes only. // This also higlights the added simplicity of the Device Detection Pipeline builder. using (var loggerFactory = new LoggerFactory()) { var dataUpdateService = new DataUpdateService(loggerFactory.CreateLogger <DataUpdateService>(), new HttpClient()); using (var temporaryDeviceDetectionEngine = new DeviceDetectionHashEngineBuilder(loggerFactory, dataUpdateService) .Build(dataFile, false)) { // Get the published date of the device data file. Engines can have multiple data files but // for the Device Detection 'Hash' engine we can guarantee there will only be one. initialPublishedDate = temporaryDeviceDetectionEngine.DataFiles.Single().DataPublishedDateTime; } } Console.WriteLine($"Data file published date: {initialPublishedDate}"); Console.Write($"Creating pipeline and updating device data"); CancellationTokenSource cancellationSource = new CancellationTokenSource(); Task.Run(() => { OutputUntilCancelled(".", 1000, cancellationSource.Token); }); // Build a new Pipeline to use an on-premise Hash engine and // configure automatic updates. var pipeline = new DeviceDetectionPipelineBuilder() // Use the On-Premise engine (aka Hash engine) and pass in // the path to the data file, your license key and whether // to use a temporary file. // A license key is required otherwise automatic updates will // remain disabled. .UseOnPremise(dataFile, licenseKey, true) // Enable automatic updates. .SetAutoUpdate(true) // Watch the data file on disk and refresh the engine // as soon as that file is updated. .SetDataFileSystemWatcher(true) // Enable update on startup, the auto update system // will be used to check for an update before the // device detection engine is created. This will block // creation of the pipeline. .SetDataUpdateOnStartUp(true) .Build(); cancellationSource.Cancel(); Console.WriteLine(); // Get the published date of the data file from the Hash engine // after building the pipeline. var updatedPublishedDate = pipeline .GetElement <DeviceDetectionHashEngine>() .DataFiles .Single() .DataPublishedDateTime; if (DateTime.Equals(initialPublishedDate, updatedPublishedDate)) { Console.WriteLine("There was no update available at this time."); } Console.WriteLine($"Data file published date: {updatedPublishedDate}"); }
/// <summary> /// This test will create a device detection pipeline based on the /// supplied parameters, process 1000 user agents. /// The various parameters allow the test to be run for many /// different configurations. /// </summary> /// <param name="datafileName"> /// The filename of the data file to use for device detection. /// </param> /// <param name="performanceProfile"> /// The performance profile to use. /// </param> /// <param name="useLazyLoading"> /// Whether or not to use the lazy loading feature. /// </param> /// <param name="multiThreaded"> /// Whether to use a single thread or multiple threads when /// passing user agents to the pipeline for processing. /// </param> public void TestOnPremise_AllConfigurations_100_UserAgents( string datafileName, PerformanceProfiles performanceProfile, bool useLazyLoading, bool multiThreaded) { var datafile = TestHelpers.Utils.GetFilePath(datafileName); var updateService = new Mock <IDataUpdateService>(); // Configure the pipeline builder based on the // parameters passed to this method. var builder = new DeviceDetectionPipelineBuilder( new NullLoggerFactory(), null, updateService.Object) .UseOnPremise(datafile.FullName, null, false) .SetPerformanceProfile(performanceProfile) .SetShareUsage(false) .SetDataFileSystemWatcher(false); if (useLazyLoading) { builder.UseLazyLoading(); } CancellationTokenSource cancellationSource = new CancellationTokenSource(); using (var pipeline = builder.Build()) { var options = new ParallelOptions() { CancellationToken = cancellationSource.Token, // The max parallelism is limited to 8 when the // multiThreaded flag is enabled. // This is because, if it is not limited, the lazy // loading tests will start all requests almost // immediately and then some will take so long to // complete that they exceed the configured timeout. MaxDegreeOfParallelism = (multiThreaded ? 8 : 1) }; // Create a parallel loop to actually process the user agents. Parallel.ForEach(USER_AGENTS.GetRandomUserAgents(100), options, (useragent) => { // Create the flow data instance using (var flowData = pipeline.CreateFlowData()) { // Add the user agent to the flow data // and process it flowData.AddEvidence( Pipeline.Core.Constants.EVIDENCE_HTTPHEADER_PREFIX + Pipeline.Core.Constants.EVIDENCE_SEPERATOR + "User-Agent", useragent) .Process(); // Make sure no errors occurred. If any did then // cancel the parallel process. if (flowData.Errors != null) { Assert.AreEqual(0, flowData.Errors.Count, $"Expected no errors but got {flowData.Errors.Count}" + $":{Environment.NewLine}{ReportErrors(flowData.Errors)}"); cancellationSource.Cancel(); } // Get the device data instance and access the // IsMobile property to ensure we can get // data out. var deviceData = flowData.Get <IDeviceData>(); var result = deviceData.IsMobile; } }); } }