You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CRM中为用户每次登录创建Geo Log实体并解决插件开发问题?

Hey there! Let's work through this CRM login tracking plugin challenge together—capturing login geodata like IP, browser, OS, and coordinates is super useful for security and analytics, so let's get this sorted.

Step 1: Pick the Right Trigger Event for Login

First, you need to register your plugin against the correct CRM message to catch login events. For Microsoft Dataverse (Dynamics 365 CRM), the UserLogin message is exactly what you need. Make sure to register it in the Post-operation stage—this ensures the login is completed before you try to capture any context data, avoiding partial or missing info.

Don’t forget to set the plugin’s execution mode:

  • Use synchronous if you need the Geo Log created immediately (but be mindful of login performance)
  • Use asynchronous if you want to avoid blocking the login flow (better for performance, especially if you’re calling external geolocation APIs)
Step 2: Grab Login Context Details (IP, Browser, OS)

Once your plugin is triggered, you can pull the required data directly from the plugin execution context. Here’s how to do it in C#:

public void Execute(IServiceProvider serviceProvider)
{
    IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
    
    // Get IP Address directly from context
    string ipAddress = context.ClientIpAddress;
    
    // Parse Browser and OS from User Agent string
    string userAgent = context.UserAgent;
    string browser = "Unknown";
    string operatingSystem = "Unknown";

    // Simple regex to extract browser (adjust patterns as needed)
    Regex browserRegex = new Regex(@"Chrome|Firefox|Edge|Safari|IE|Opera", RegexOptions.IgnoreCase);
    Match browserMatch = browserRegex.Match(userAgent);
    if (browserMatch.Success)
    {
        browser = browserMatch.Value;
    }

    // Simple regex to extract OS (adjust patterns as needed)
    Regex osRegex = new Regex(@"Windows|Mac OS X|Android|iOS|Linux", RegexOptions.IgnoreCase);
    Match osMatch = osRegex.Match(userAgent);
    if (osMatch.Success)
    {
        operatingSystem = osMatch.Value;
    }

    // Rest of your logic here...
}

Pro tip: For more accurate parsing, you could use a lightweight user-agent parsing library, but keep in mind sandbox plugin restrictions—stick to libraries that don’t require external dependencies if possible.

Step 3: Resolve IP to Longitude & Latitude

To get coordinates from the IP address, you’ll need to call a geolocation API. Since this is a server-side plugin, you’ll need to enable external service access in the plugin registration tool (check the "Can connect to external services" box for sandbox plugins).

Here’s a simplified example of how to handle this (replace the API endpoint with your preferred geolocation service):

double? longitude = null;
double? latitude = null;

if (!string.IsNullOrEmpty(ipAddress))
{
    try
    {
        // Store API keys in CRM environment variables instead of hardcoding!
        string geoApiKey = GetEnvironmentVariable(serviceProvider, "GeolocationApiKey");
        string geoApiUrl = $"https://api.yourgeoservice.com/ip?key={geoApiKey}&ip={ipAddress}";

        using (HttpClient client = new HttpClient())
        {
            HttpResponseMessage response = await client.GetAsync(geoApiUrl);
            if (response.IsSuccessStatusCode)
            {
                string geoResponse = await response.Content.ReadAsStringAsync();
                JObject geoData = JObject.Parse(geoResponse);
                
                longitude = (double?)geoData["longitude"];
                latitude = (double?)geoData["latitude"];
            }
        }
    }
    catch (Exception ex)
    {
        // Log error to CRM plugin trace log
        ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
        tracingService.Trace("Geolocation API call failed: {0}", ex.Message);
    }
}

Important: Avoid long-running API calls in synchronous plugins—they can cause login timeouts. Use asynchronous execution for this step if your geolocation service has any latency.

Step 4: Create the Geo Log Entity Record

Finally, use the CRM organization service to create your Geo Log record. Make sure your entity has fields for all the data you’re capturing (IP, browser, OS, longitude, latitude, and a lookup to the user):

// Get the organization service
IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

// Create the Geo Log entity (replace with your entity's logical name and field names)
Entity geoLog = new Entity("crmprefix_geolog");
geoLog["crmprefix_ipaddress"] = ipAddress;
geoLog["crmprefix_browser"] = browser;
geoLog["crmprefix_operatingsystem"] = operatingSystem;
geoLog["crmprefix_longitude"] = longitude;
geoLog["crmprefix_latitude"] = latitude;
geoLog["crmprefix_userid"] = new EntityReference("systemuser", context.UserId); // Link to the logged-in user

// Save the record
service.Create(geoLog);
Common Troubleshooting Tips
  • Plugin not firing? Double-check your plugin registration: ensure it’s linked to the UserLogin message, Post-operation stage, and deployed to the correct environment. Avoid unnecessary filtering that might exclude users.
  • Missing IP/UserAgent? Some login methods (like backend service logins) might not populate these fields. Add null checks to avoid exceptions.
  • Sandbox errors? Confirm you’ve enabled external service access if you’re calling a geolocation API. Also, make sure your plugin doesn’t exceed CRM’s execution timeout limits.
  • Performance issues? Shift the geolocation and record creation to an asynchronous plugin to keep login fast for users.

内容的提问来源于stack exchange,提问作者Po Po

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:24:52