I am trying to configure LDAP as JNDI Resource in Pivotal - spring-mvc

I get some data with ldap authentication. I can do this correctly with this code.
List<Employees> emps=new ArrayList<Employees>();
String url = "ldap://xxx:389";
String base = "dc=xxx,dc=xxx,dc=xx";
String userDn = "username";
String password = "pass";
try {
LdapContextSource ctxSrc = new LdapContextSource();
ctxSrc.setUrl(url);
ctxSrc.setBase(base);
ctxSrc.setUserDn(userDn);
ctxSrc.setPassword(password);
ctxSrc.afterPropertiesSet();
LdapTemplate lt = new LdapTemplate(ctxSrc);
AndFilter filter = new AndFilter();
filter.and(new EqualsFilter("objectclass", "Person"));
List<String> list = lt.search("", filter.encode(), new ContactAttributeMapperJSON());
emps = new Gson().fromJson(list.toString(), new TypeToken<List<Employees>>() {
}.getType());
this code works correctly. But i want hide my username and pass. So i get datas from content.xml(Pivotal).This is my content.xml:
<Resource name="ldap/LdapResource" auth="Container"
type="javax.naming.ldap.LdapContext"
factory="xxx"
singleton="false"
java.naming.factory.initial="com.sun.jndi.ldap.LdapCtxFactory"
java.naming.provider.url="ldap://xx:389"
java.naming.security.authentication="simple"
java.naming.security.principal="username"
java.naming.security.credentials="pass." />
And my new code block :
List<Employees> emps = new ArrayList<Employees>();
try {
Context initialContext = new InitialContext();
LdapContext ldapContext = (LdapContext) initialContext.lookup("java:comp/env/ldap/LdapResource");
*LdapTemplate lt = new LdapTemplate(ldapContext);*
AndFilter filter = new AndFilter();
filter.and(new EqualsFilter("objectclass", "Person"));
List<String> list = lt.search("", filter.encode(), new ContactAttributeMapperJSON());
emps = new Gson().fromJson(list.toString(), new TypeToken<List<Employees>>() {
}.getType());
here is my problem. I cant LdapTemplate with LdapContext. It works only LdapContextSource and I cant cast LdapContext to LdapContextSource. What should i do ?
Sorry for my bad English. Thank You.

What I've done in that exact same situation is to create a java.naming.spi.ObjectFactory subclass that returns an LdapContextSource instance using the properties given in the Resource element. You can use the standard LDAP JNDI attributes from 'java.naming.Context' or use your own.
Only thing I still have to work out is how to deal with java.naming.security.authentication and java.naming.security.protocol.

Related

Azure Resource Manager DNS: Sample code to create a DNS record

I'm currently trying to move out from using old Microsoft.Azure.Management.Dns package to the new Azure.ResourceManager.Dns.
However I've been having issues in our code that creates Dns records such as an Arecord.
I've tried to go through the official documentation https://learn.microsoft.com/en-us/dotnet/api/azure.resourcemanager.dns.dnsarecordcollection.createorupdate?view=azure-dotnet
But the classes that represent an Arecord are either read only or private so I have no idea how to update this simple lines:
RecordSet set = DnsManagementClient.client.RecordSets.Get(resourceGroupName, zone, recordSetName, RecordType.A);
set.ARecords = set.ARecords ?? new List<ARecord>();
set.ARecords.Add(new ARecord(ipAddress));
DnsManagementClient.client.RecordSets.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, zone, recordSetName, RecordType.A, set, ifNoneMatch: "*");
Currently documentation only talks about Zones, can an example be added to the official documentation on how to add or update a DNS record (A,CNAME,etc..)
https://github.com/Azure/azure-sdk-for-net/tree/main/sdk/dns/Azure.ResourceManager.Dns
I'm expecting a method to create an A record that let's you specify an IP address, and currently all the classes that potentially can be used to do that are either read-only or internal.
DnsARecordData has an internal list of Arecords, DnsARecordData.DnsARecords is where we can invoke the Add method to create the record. The reason DnsARecordData doesn't have a setter method is due to the .Net framework design guideline..
An example of how to create an A record using Azure.Resourcemanager.Dns can be found here:
// Create or update A record
string myARecordName = "myrecord";
DnsARecordData dnsARecordData = new() {TtlInSeconds = (long)TimeSpan.FromHours(1).TotalSeconds};
dnsARecordData.DnsARecords.Add(new DnsARecordInfo { IPv4Address = IPAddress.Parse("127.0.0.1") });
DnsARecordCollection dnsARecordCollection1 = dnsZoneResource.GetDnsARecords();
dnsARecordCollection1.CreateOrUpdate(WaitUntil.Completed, myARecordName, dnsARecordData);
// Create or update CName pointing to A record
string myCnameName = "mycname";
DnsCnameRecordData dnsCnameRecordData = new() { Cname = $"{myARecordName}.{DnsZone}", TtlInSeconds = (long)TimeSpan.FromMinutes(10).TotalSeconds, };
DnsCnameRecordCollection cnameRecordCollection = dnsZoneResource.GetDnsCnameRecords();
cnameRecordCollection.CreateOrUpdate(WaitUntil.Completed, myCnameName, dnsCnameRecordData);
I tried in my environment and got below results:
You can create A record set using Azure.ResourceManager.Dns package. The version of NuGet package is beta-1.
NuGet Package:
Azure.ResourceManager.Dns 1.0.0 beta-1
Code:
using Azure;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Dns;
using Azure.ResourceManager.Resources;
using System.Net;
ArmClient armClient = new ArmClient(new DefaultAzureCredential());
SubscriptionResource subscription = await armClient.GetDefaultSubscriptionAsync();
// first we need to get the resource group
string rgName = "rg-name";
ResourceGroupResource resourceGroup = await subscription.GetResourceGroups().GetAsync(rgName);
string dnsZoneName = "dns name";
DnsZoneCollection dnsZoneCollection = resourceGroup.GetDnsZones();
DnsZoneData data1 = new DnsZoneData("Global")
{
};
ArmOperation<DnsZoneResource> lro = await dnsZoneCollection.CreateOrUpdateAsync(WaitUntil.Completed, dnsZoneName, data1);
DnsZoneResource dnsZone = lro.Value;
RecordSetACollection recordSetACollection = dnsZone.GetRecordSetAs();
string name = "cname1";
var parm = new ARecordSetData();
parm.TTL =600;
parm.ARecords = new List<ARecord>();
parm.ARecords.Add(new ARecord("1.2.3.4"));
ArmOperation<RecordSetAResource> recordSetAResource = recordSetACollection.CreateOrUpdate(WaitUntil.Completed, name,parm);
RecordSetAResource recordSetAs = recordSetAResource.Value;
Console:
Portal:
For more reference:
azure-sdk-for-net/Sample2_ManagingRecordSetPtrs.md at dvbb-mgmt-track2-dns-2 ยท dvbb/azure-sdk-for-net (github.com)

FluentMigrator create password protected SqlLite DB

I use FluentMigrator to create a SqlLite DB in C# using FluentMigrator.Runner.MigrationRunner. I wonder is there any way to use the SetPassword command o the SqlConnection only when the DB needs to be created ? There's a SqLiteRunnerContextFactory object but it don't seem to be a property that I can use to specify password.
public MigrationRunner CreateMigrationRunner(string connectionString, string[] migrationTargets, Assembly assembly, long version)
{
var announcer = new TextWriterAnnouncer(Console.WriteLine) { ShowSql = true };
var options = new ProcessorOptions { PreviewOnly = false, Timeout = 60 };
var runnerContext = new SqLiteRunnerContextFactory().CreateRunnerContext(connectionString, migrationTargets, version, announcer);
var sqlLiteConnection = new SQLiteConnection(connectionString);
//If the DB has already been created, it crashes later on if I specify this
sqlLiteConnection.SetPassword("ban4an4");
return new MigrationRunner(assembly,
runnerContext,
new SQLiteProcessor(sqlLiteConnection,
new SQLiteGenerator(),
announcer,
options,
new SQLiteDbFactory()));
}
I would like to avoid having to look if the file exists before setting password on connection.
Well, finally the code below works perfectly by using SetPassword everytime you create de runner. No need to check if the file exists or not. First time it creates it with the password and second time it opens it with it seems to use it to open DB. Which is exactly what I was looking for.

Get Dynamics CRM contact parentcustomerid

I need to retrieve full name and parent account of contact in Dynamics CRM.
I am using following code:
ColumnSet cols = new ColumnSet(new String[] { "fullname", "parentcustomerid" });
Entity retrContact = (Entity)orgService.Retrieve("contact", contactID, cols);
fullName = retrContact.Attributes["fullname"];
parentAccount = retrContact.Attributes["parentcustomerid"];
nameStr = fullName.ToString();
companyStr = parentAccount.ToString();
My problem is that companyStr getting "Microsoft.Xrm.Sdk.EntityReference" instead of Name value.
parentAccount contains following:
LogicalName "account" string
Name "Microsoft Corp" string
RowVersion null string
How can I get Name string?
The parentcustomerid object is an EntityReference object which has the name you're looking for. This code works:
ColumnSet cols = new ColumnSet(new string[] { "fullname", "parentcustomerid" });
Entity retrContact = (Entity)orgService.Retrieve("contact", new Guid("{9DF2ACC2-0212-E611-80E4-6C3BE5A83B1C}"), cols);
var parentAccount = (EntityReference)retrContact.Attributes["parentcustomerid"];
var companyStr = parentAccount.Name;
You should probably fetch the parentAccount from server (please refer to EntityReference.Name Property
This property is not automatically populated unless the EntityReference object has been retrieved from the server.
E.g. you should fetch the data from server using the Id parentcustomerid, somewhat like
Entity Account = service.Retrieve(Account.EntityLogicalName, parentAccount.Id, new ColumnSet(true));
You can for sure replace Account.EntityLogicalName with "account" string.

Get type of metadata fields of a Metadata schema

I want to get the all fields along with type/datatype of the metadata fields of a Metadata schema.
I have written below sample code to achieve the functionality and I am able to get Name, Description etc but could not find any property with type/dataType. If anyone of you have any idea, please suggest...
var client = new SessionAwareCoreService2010Client();
client.ClientCredentials.Windows.ClientCredential.UserName = "myUserName";
client.ClientCredentials.Windows.ClientCredential.Password = "myPassword";
client.Open();
if (client.State == System.ServiceModel.CommunicationState.Opened)
{
var schemaUri = "tcm:1-47-8";
var fields= client.ReadSchemaFields(schemaUri, true, new ReadOptions());
var fieldName = fields.MetadataFields[0].Name;
}
To know the type of a field, you only need to examine the .NET type of the field.
I typically use an "is" check, but you can also call GetType if you want.
For example:
var client = new SessionAwareCoreService2010Client();
client.ClientCredentials.Windows.ClientCredential.UserName = "myUserName";
client.ClientCredentials.Windows.ClientCredential.Password = "myPassword";
client.Open();
if (client.State == System.ServiceModel.CommunicationState.Opened)
{
var schemaUri = "tcm:1-47-8";
var fields= client.ReadSchemaFields(schemaUri, true, new ReadOptions());
foreach (var field in fields.MetadataFields)
{
if (field is SingleLineTextFieldDefinitionData)
{
// Do something specifically for single-line text fields
}
}
}
The ReadSchemaFields method exposes only the definition of the fields. So it is essentially a wrapper around the properties you enter while you define the field in a schema.
The Content and Metadata are exposed by ComponentData.Content and ComponentData.Metadata respectively. But those are exposed as XML strings, so you will have to do your own parsing of them.
If you (understandably) don't feel like that, have a look at this helper class: http://code.google.com/p/tridion-practice/wiki/ChangeContentOrMetadata
You might also want to read my answer to this question: Updating Components using the Core Service in SDL Tridion 2011

HP Trim web service- how to request a record.?

I am dealing with HP Trim web service with no support at all. I have to set a request of file using web service. i think i have to set following properties but i am not sure what operation this will be added in.
rcqCurrentLoc(Current Location):
rcqDetails(Details):
rcqEndDate(Date of Final Request):
rcqFrequency(Frequency):
rcqFrequencyType(Frequency Type):
rcqHomeLoc(Home Location):
rcqNotes(Notes):
rcqRecord(Object):
rcqRequestDate(Date Object Needed):
rcqRequestor(Requested By):
Can someone please help me on this?
I was looking at wrong properties. The request properties are following
uri(Unique Identifier):
reqEndDate(Date of Final Request):
reqFrequency(Frequency):
reqFrequencyType(Frequency Type):
reqName(Request Info):
reqNotes(Notes):
reqRequestDate(Date Needed):
reqRequestor(Requested By):
and the code is
public void AddFileRequest(string FileUri,string RequestorUserId, DateTime DateNeeded)
{
List<InputProperty> properties = new List<InputProperty>();
InputProperty property = new InputProperty();
property.Name = ReqRequstor;
property.Val = GetUserUri(RequestorUserId);
properties.Add(property);
property = new InputProperty();
property.Name = ReqRequestDate;
property.Val = DateNeeded.ToString();
properties.Add(property);
ShortcutRecordUri uri = new ShortcutRecordUri();
uri.Uri = FileUri;
uri.IsForUpdate = true;
CreateChildItem create = new CreateChildItem();
create.ChildObjectType = ObjectTypeRequest;
create.Items = properties.ToArray();
TrimRequest request = new TrimRequest();
request.Items = new Operation[] { uri, create };
ExecuteRequest(request);
}

Resources