Using Kentico 7 API via Console App

2019-03-04 18:15发布

问题:

I have the following, using Kentico API 7 via a console application:

String connectionString = CMS.DataEngine.ConnectionHelper.GetConnectionString("MyConnString");
Console.WriteLine("connectionString ? " + connectionString);
//CMS.DataEngine.GeneralConnection
CMS.DataEngine.GeneralConnection conn = CMS.DataEngine.ConnectionHelper.GetConnection(connectionString);
conn.Open();
Console.WriteLine("connection is open? " + conn.IsOpen());

CMS.CMSHelper.CMSContext.Init();
Console.WriteLine("CurrentSiteID " + CMS.CMSHelper.CMSContext.CurrentSiteID);

The connection is open. I get error Console.WriteLine("CurrentSiteID " + CMS.CMSHelper.CMSContext.CurrentSiteID);

that says connection is not initialized. Got help?

回答1:

It certainly is possible to use Kentico API outside of Kentico itself. Recently, I published an article on this topic. However, the article demonstrates the possibility on a newer version of Kentico. But back to your problem...

The CMS.CMSHelper.CMSContext.Init(); method expects a connection string named "CMSConnectionString" to exist in your app.config or web.config.

The documentation also says

You can call this method at any point in your application's life cycle, but it must occur before you use any other Kentico CMS API.

so you should not be touching CMS.DataEngine or any other CMS.* namespace before you call CMSContext.Init(). Once you call that method you can start using the parameter-less overload ConnectionHelper.GetConnection() but I would advise you to take advantage of the Info-Provider pattern that Kentico offers instead of using the direct DB access through CMS.DataEngine.

For instance, this is how you delete users:

// Get the user
UserInfo deleteUser = UserInfoProvider.GetUserInfo("MyNewUser");

// Delete the user
UserInfoProvider.DeleteUser(deleteUser);


回答2:

Unless there's a specific need to create a console application to perform your task, then I would recommend avoiding a console app and instead creating a custom scheduled task.

You can write the code that your task needs to perform within the App_Code folder of your project - or within the CMSAppCode project if you're using a web application project type. This way you don't have to worry about having access to the database or referencing all the DLLs you'll need to utilize the Kentico API.



标签: c# kentico