背景:VS2015社区; C#; ClearScript.V8.5.4.5; Google.AdWords.18.25.0
我正在尝试创建一个脚本环境来执行我的预算。一个是C#方面,我正在设置一个JScript环境,并公开我需要的所有AdWords类型和对象,即
static JScriptEngine JSengine = null;
static Dictionary<string, object> Settings = new Dictionary<string, object>();
static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("engine script.js");
Environment.Exit(1);
}
string scriptSpec = args[0];
try
{
JSengine = new JScriptEngine(WindowsScriptEngineFlags.EnableDebugging | WindowsScriptEngineFlags.EnableJITDebugging);
}
catch (Exception exc)
{
return;
}
// .. others as well e.g. File, Environment etc
JSengine.AddHostType("AdWordsUser", typeof(AdWordsUser));
JSengine.AddHostType("AdWordsAppConfig", typeof(AdWordsAppConfig));
JSengine.AddHostType("BudgetOrderService", typeof(BudgetOrderService));
JSengine.AddHostType("Selector", typeof(Selector));
JSengine.AddHostType("Predicate", typeof(Predicate));
JSengine.AddHostType("BudgetOrderPage", typeof(BudgetOrderPage));
JSengine.AddHostType("BudgetOrder", typeof(BudgetOrder));
JSengine.AddHostType("PredicateOperator", typeof(PredicateOperator));
JSengine.AddHostType("AdWordsService", typeof(AdWordsService));
JSengine.AddHostObject("Settings", Settings);
object answer = null;
string script = File.ReadAllText(scriptSpec);
try
{
answer = JSengine.Evaluate(script);
}
catch (ScriptEngineException see)
{
Console.WriteLine(see.ErrorDetails);
}
}
我已经做过几次这样的事了,所以没有惊喜。
目前我遇到的困难是JScript方面的困难。此时的代码如下所示:
var user = new AdWordsUser();
user.OAuthProvider.ClientId = "anonymised.apps.googleusercontent.com";
user.OAuthProvider.ClientSecret = "anonymised";
user.OAuthProvider.AccessToken = "";
user.Config.OAuth2RefreshToken = "anonymised";
user.OAuthProvider.RefreshAccessToken();
var config = new AdWordsAppConfig();
config.ClientCustomerId = "anonymised";
config.DeveloperToken = "anonymised";
config.UserAgent = "anonymised";
config.OAuth2ClientId = user.OAuthProvider.ClientId;
config.OAuth2ClientSecret = user.OAuthProvider.ClientSecret;
config.OAuth2AccessToken = user.OAuthProvider.AccessToken;
config.OAuth2RefreshToken = user.Config.OAuth2RefreshToken;
var bos = user.GetService(AdWordsService.v201603.BudgetOrderService);
var bas = bos.getBillingAccounts();
此时,bos
对getBillingAccounts
一无所知。 bos
了解它的唯一方法是执行
var bos = new BudgetOrderService();
然而,bos
与user
中所需的值之间没有任何关联,并且尝试执行getBillingAccounts
会引发错误。
从中派生的原始C#代码是
BudgetOrderService bos = (BudgetOrderService)user.GetService(AdWordsService.v201603.BudgetOrderService);
BillingAccount[] bas = bos.getBillingAccounts();
将GetService
来电转换为BudgetOrderService
似乎足以让getBillingAccounts
显示bos
。但是,JScript不允许我这样做。
那么从哪里来?
答案 0 :(得分:1)
您应该能够在脚本代码中进行强制转换。试试这个:
// C#
JSengine.Script.host = new HostFunctions();
然后,在你的脚本中:
// JavaScript
var bos = user.GetService(AdWordsService.v201603.BudgetOrderService);
bos = host.cast(BudgetOrderService, bos);
或者您可以使用C#代码公开执行转换的委托。