How to enable preTestConnection checkbox from deployment api for Websphere application server? - websphere-8

I am trying to enable validate pooled connection checkbox for a datasource using deployment api.
AttributeList preTestConnections = new AttributeList();
preTestConnections.add(new Attribute("name", "preTestConnections"));
preTestConnections.add(new Attribute("type", "java.lang.Boolean"));
preTestConnections.add(new Attribute("value", String.valueOf(dsc.isvalidationOnMatchEnbled())));
configService.addElement(session, resourcePropertySet, "resourceProperties", preTestConnections, -1);`
When i do the able the pretestconnection is added to custom properties instead WebSphere Application Server data source properties of datasource.
Please provide the attribute for preTestConnections.

You can accomplish this in the admin console in the following panel:
Resources > DataSources > YOUR_DATASOURCE > WebSphere Application Server data source properties
Then, configure this set of properties how you desire:
The key here is that the property is called testConnection not preTestConnections
You can also accomplish this using wsadmin scripting:
AdminConfig.modify(
'(cells/myCell/nodes/myNode/server/server1|resources.xml#ConnectionPool_1)',
'[[testConnectionInterval "0"] [testConnection "true"]]')
You can also accomplish this using the ConfigService API:
AttributeList preTestConnections = new AttributeList();
preTestConnections.add(new Attribute("name", "testConnection"));
preTestConnections.add(new Attribute("type", "java.lang.Boolean"));
preTestConnections.add(new Attribute("value", String.valueOf(dsc.isvalidationOnMatchEnbled())));
configService.addElement(session, resourcePropertySet, "resourceProperties", preTestConnections, -1);

Related

Create a UserStorageProvider from java code

I want to add a custom UserStorageSPI to Keycloak.
We can do it fro UI by selected it from dropdown under User-Federation -> Add Provider option, but we wanted to to do it from Java Code. We are trying to create an automated system where properties are picked up from YAML files and corresponding realms and clients are created automatically.
Keycloak keycloakClient = KeycloakBuilder.builder()
.serverUrl(authUrl)
.realm(StringUtils.defaultString(realm, "master"))
.username(username)
.password(password)
.clientId(StringUtils.defaultString(client, "admin-cli"))
.resteasyClient(client)
.build();
keycloakClient.realms().create(realm);
This is a sample code that we are using to create a realm.
Looking for a similar way to add the UserStorageSPI
You need ComponentRepresentation, which you can create with the following code:
private ComponentRepresentation createComponentRepresentation() {
ComponentRepresentation cr = new ComponentRepresentation();
cr.setName("your user storage provider id");
cr.setProviderId("your user storage provider id");
cr.setProviderType("org.keycloak.storage.UserStorageProvider");
cr.setConfig(new MultivaluedHashMap<>());
cr.getConfig().putSingle("cachePolicy", "DEFAULT");
cr.getConfig().putSingle("priority", "10");
cr.getConfig().putSingle("enabled", "true");
cr.setParentId("your realm id");
return cr;
}
And use keycloak client to create user federation on realm:
keycloakClient.realm("your realm id").components().add(createComponentRepresentation());

Identity Server EF Core DB Configuration with Azure MSI

I am trying to configure my Identity Server instance that is hosted as an Azure Web App to connect to my database using the Managed Service Identity (https://learn.microsoft.com/en-us/azure/app-service/app-service-web-tutorial-connect-msi).
At the time of this article linked above being written, EF Core did not support Access Tokens for SQL Server connections. It appears this has changed with release 2.2 that is currently in preview.
Currently my configuration store setup looks like this:
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = b =>
{
b.UseSqlServer(
connectionString,
sql => { sql.MigrationsAssembly(migrationsAssembly); }
);
};
})
With the EF Core 2.2 preview package, how would I go about adding the Access Token value equivalently as the guide linked above?
public MyDatabaseContext(SqlConnection conn) : base(conn, true)
{
conn.ConnectionString = WebConfigurationManager.ConnectionStrings["MyDbConnection"].ConnectionString;
// DataSource != LocalDB means app is running in Azure with the SQLDB connection string you configured
if(conn.DataSource != "(localdb)\\MSSQLLocalDB")
conn.AccessToken = (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net/").Result;
Database.SetInitializer<MyDatabaseContext>(null);
}
At initial glance, it looks like I would have to wait for the IdentityServer4.EntityFramework package to support this?
I had a similar issue,
Try the overload of UseSqlServer that accepts a DbConnection, and pass it a SqlConnection with the token set.
It worked for me

asp.net dynamically add connection string in web.config

I have web application and windows application in same solution. I want to dynamically add connection string in web.config file. The connection string information give from windows application. How do i do this please help me.
My window app having:
WebForm1 wf = new WebForm1();
wf.add();
And my wep app having:
public void add()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConnectionStringsSection sec = (ConnectionStringsSection)config.GetSection("connectionStrings");
sec.ConnectionStrings["DBCS"].ConnectionString = "Data Source=GKS_004-PC;Database=hello1;User ID=123;Password=123";
config.Save();
}
I believe you address your problem in a way that may exist a different approach to solve your issue, however in order to do what you want you have two options. First you can read the file using the IO namespace and then parse it like XML using LINQ nodes and second you can use the Configuration class (System.Configuration and System.Web.Configuration namespaces).
//get the configuration file
Configuration config = WebConfigurationManager.OpenWebConfiguration("..."); //path to config
//get Configuration section
ConfigurationSection section = config.GetSection("...");
config.AppSettings.Settings.Add(Key, Value);
config.AppSettings.Settings.Remove(Key);
or this way, instead of using directly Configuration class
AppSettingsSection appsettings = (AppSettingsSection) config.GetSection("...");
appsettings.Settings.Add(key, Value);

Publishing with Core Service and Impersonation

I have a Tridion Core Service Web Application to publish pages. When logged into the server and running it from there via a browser client calling a web service with ajax it works fine. However, when I run the application from my desktop it does nothing, and also throws no error messages.
*Edit:
The Web App hosting the web service is running as an 'Application' under the Tridion 2011 CMS website. This is done to avoid cross-domain ajax issues/
Update: The code below is working fine - both with the impersonate and also with Nick's solution. My issue was actually in how I was calling the web service from jQuery and using the appropriate URL. I am leaving the code and question so maybe it will help others.
My code is:
string binding = "wsHttp_2011";
using (var client = new SessionAwareCoreServiceClient(binding))
{
client.Impersonate("company\\cms_svc");
// ** Get Items to Publish
List<string> itemsToPublish = GetItemsToPublish(publishItem.TcmUri, client);
PublishInstructionData instruction = new PublishInstructionData
{
ResolveInstruction = new ResolveInstructionData() { IncludeChildPublications = false },
RenderInstruction = new RenderInstructionData()
};
PublicationTargetData pubtarget = (PublicationTargetData)client.Read(publishItem.PubTargetUri, readoptions);
List<string> target = new List<string>();
target.Add(pubtarget.Id);
client.Publish(itemsToPublish.ToArray(), instruction, target.ToArray(), GetPublishPriority(publishItem.Priority), readoptions);
}
Have at look at this page on SDL Live Content, which explains various types of scenarios for connecting as different users:
http://sdllivecontent.sdl.com/LiveContent/content/en-US/SDL_Tridion_2011_SPONE/task_87284697A4BB423AAD5387BBD6884735
As per the docs, instead of impersonation you may want to establish your Core Service connection as follows using NetworkCredential:
using (ChannelFactory<ISessionAwareCoreService> factory =
new ChannelFactory<ISessionAwareCoreService>("netTcp_2011"))
{
NetworkCredential networkCredential =
new NetworkCredential("username", "password", "domain");
factory.Credentials.Windows.ClientCredential = networkCredential;
ISessionAwareCoreService client = factory.CreateChannel();
Console.WriteLine(client.GetCurrentUser().Title);
}

ASP.NET Universal Providers + Azure CSCFG

Following Hanselman's post about the new ASP.NET Universal Providers:
http://www.hanselman.com/blog/IntroducingSystemWebProvidersASPNETUniversalProvidersForSessionMembershipRolesAndUserProfileOnSQLCompactAndSQLAzure.aspx
How would you configue it to read the connection string for the CSCFG file as opposed to web.config?
I don't think you can make the Universal Providers read from the ServiceConfiguration (as opposed to the web.config). But what you can do is modify the web.config with information from the ServiceConfiguration each time you deploy your application OR each time you modify the ServiceConfiguration.
In your WebRole.cs you would first write some code that does this. There is a topic on MSDN that kinda explains how you can do this:
Run in elevated mode
Reference %WINDIR%\system32\inetsrv\Microsoft.Web.Administration.dll
Write this in the OnStart method (you will need to change this code):
using (var server = new ServerManager())
{
// get the site's web configuration
var siteNameFromServiceModel = "Web"; // update this site name for your site.
var siteName =
string.Format("{0}_{1}", RoleEnvironment.CurrentRoleInstance.Id, siteNameFromServiceModel);
var siteConfig = server.Sites[siteName].GetWebConfiguration();
// get the appSettings section
var appSettings = siteConfig.GetSection("appSettings").GetCollection()
.ToDictionary(e => (string)e["key"], e => (string)e["value"]);
// reconfigure the machine key
var machineKeySection = siteConfig.GetSection("system.web/machineKey");
machineKeySection.SetAttributeValue("validationKey", appSettings["validationKey"]);
machineKeySection.SetAttributeValue("validation", appSettings["validation"]);
machineKeySection.SetAttributeValue("decryptionKey", appSettings["decryptionKey"]);
machineKeySection.SetAttributeValue("decryption", appSettings["decryption"]);
server.CommitChanges();
}
Now what this topic doesn't cover are changes to the ServiceConfiguration (say you modify the connection string from the portal without redeploying). That's why you'll also need to handle the RoleEnvironment.Changing event, to update the configuration on such a change (you can also prevent the instance to reboot here).

Resources