writing posixAccount to LDAP doesn't work - asp.net-mvc-4

I tried to write PosixAccount on LDAP to an existing user. i get no error, but when checking LDAP the new entry has not been written.
i added a new user first which is working well!
=>
public bool RegisterUser(UserObject userObj, HttpContext httpContext){
bool success = false;
//create a directory entry
using (DirectoryEntry de = new DirectoryEntry())
{
try
{
InitializeCommonDataForDirectoryEntry(
de,
String.Format("{0}/{1}",
GetConfigEntry(Common.CommonDefinitions.CE_LDAP_CONFIG_SERVER, httpContext),
GetConfigEntry(Common.CommonDefinitions.CE_LDAP_CONFIG_DIRECTORY_ENTRY_ROOT, httpContext)),
httpContext);
DirectorySearcher ds = new DirectorySearcher(de);
ds.SearchScope = System.DirectoryServices.SearchScope.Subtree;
ds.Filter = "(&(objectClass=organizationalUnit)(ou=people))";
SearchResult result = ds.FindOne();
if (result != null)
{
DirectoryEntry myDirectoryEntry = result.GetDirectoryEntry();
DirectoryEntry newEntry = myDirectoryEntry.Children.Add(String.Format("cn={0}", userObj.userName), "inetOrgPerson");
if (userObj.company != null && !userObj.company.Equals(String.Empty))
newEntry.Properties["businessCategory"].Add(String.Format("{0}", userObj.company));
newEntry.Properties["givenName"].Add(String.Format("{0}", userObj.firstName));
newEntry.Properties["sn"].Add(String.Format("{0}", userObj.lastName));
newEntry.Properties["uid"].Add(String.Format("{0}", userObj.userName));
newEntry.Properties["mail"].Add(String.Format("{0}", userObj.email));
userObj.password = GenerateSaltedSHA1(userObj.password);
newEntry.Properties["userPassword"].Add(String.Format("{0}", userObj.password));
newEntry.Properties["pager"].Add(String.Format("{0}", userObj.newsletter));
newEntry.Properties["initials"].Add(String.Format("{0}", GetConfigEntry(Common.CommonDefinitions.CE_MOWEE_PACKAGE_1, httpContext)));
newEntry.CommitChanges();
newEntry.RefreshCache();
success = true;
}
}
catch (Exception ex)
{
Trace.Write("Exception : RegisterUser: " + ex);
GeneralUtils.SendBugMail(ex, httpContext);
}
}
return success;
}
after that i want to write posixAccount for that user, which is not working
maybe someone can help me PLEASE and check what i did wrong !?
=>
public bool WritePosixAccountDataForRegisteredUser(UserObject userObj, HttpContext httpContext)
{
bool success = false;
//create a directory entry
using (DirectoryEntry de = new DirectoryEntry())
{
try
{
InitializeCommonDataForDirectoryEntry(
de,
String.Format("{0}/ou=people,{1}",
GetConfigEntry(Common.CommonDefinitions.CE_LDAP_CONFIG_SERVER, httpContext),
GetConfigEntry(Common.CommonDefinitions.CE_LDAP_CONFIG_DIRECTORY_ENTRY_ROOT, httpContext)),
httpContext);
DirectorySearcher ds = new DirectorySearcher(de);
ds.SearchScope = System.DirectoryServices.SearchScope.Subtree;
ds.Filter = String.Format("(&(objectClass=*)(cn={0}))", userObj.userName);
SearchResult result = ds.FindOne();
if (result != null)
{
DirectoryEntry userEntry = result.GetDirectoryEntry();
//mandatory attributes
/*
* cn
gidNumber
homeDirectory
uid
uidNumber
* */
IADsPropertyList propList = (IADsPropertyList)userEntry.NativeObject;
ActiveDs.PropertyEntry myNewEntry1 = new ActiveDs.PropertyEntry();
ActiveDs.IADsPropertyValue propVal1 = new ActiveDs.PropertyValue();
propVal1.CaseIgnoreString = "posixAccount";
propVal1.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
myNewEntry1.Name = "objectClass";
myNewEntry1.Values = new object[] { propVal1 };
myNewEntry1.ControlCode = (int)ADS_PROPERTY_OPERATION_ENUM.ADS_PROPERTY_APPEND;
myNewEntry1.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
propList.PutPropertyItem(myNewEntry1);
ActiveDs.PropertyEntry myNewEntry2 = new ActiveDs.PropertyEntry();
ActiveDs.IADsPropertyValue propVal2 = new ActiveDs.PropertyValue();
propVal2.CaseIgnoreString = "504";
propVal2.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
myNewEntry2.Name = "gidNumber";
myNewEntry2.Values = new object[] { propVal2 };
myNewEntry2.ControlCode = (int)ADS_PROPERTY_OPERATION_ENUM.ADS_PROPERTY_APPEND;
myNewEntry2.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
propList.PutPropertyItem(myNewEntry2);
ActiveDs.PropertyEntry myNewEntry3 = new ActiveDs.PropertyEntry();
ActiveDs.IADsPropertyValue propVal3 = new ActiveDs.PropertyValue();
propVal3.CaseIgnoreString = "/data/WowzaMediaServer-3.0.3/content/mowee/" + userObj.userName;
propVal3.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
myNewEntry3.Name = "homeDirectory";
myNewEntry3.Values = new object[] { propVal3 };
myNewEntry3.ControlCode = (int)ADS_PROPERTY_OPERATION_ENUM.ADS_PROPERTY_APPEND;
myNewEntry3.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
propList.PutPropertyItem(myNewEntry3);
ActiveDs.PropertyEntry myNewEntry4 = new ActiveDs.PropertyEntry();
ActiveDs.IADsPropertyValue propVal4 = new ActiveDs.PropertyValue();
propVal4.CaseIgnoreString = "1100";
propVal4.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
myNewEntry4.Name = "uidNumber";
myNewEntry4.Values = new object[] { propVal4 };
myNewEntry4.ControlCode = (int)ADS_PROPERTY_OPERATION_ENUM.ADS_PROPERTY_APPEND;
myNewEntry4.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
propList.PutPropertyItem(myNewEntry4);
ActiveDs.PropertyEntry myNewEntry5 = new ActiveDs.PropertyEntry();
ActiveDs.IADsPropertyValue propVal5 = new ActiveDs.PropertyValue();
propVal5.CaseIgnoreString = userObj.userName;
propVal5.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
myNewEntry5.Name = "cn";
myNewEntry5.Values = new object[] { propVal5 };
myNewEntry5.ControlCode = (int)ADS_PROPERTY_OPERATION_ENUM.ADS_PROPERTY_APPEND;
myNewEntry5.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
propList.PutPropertyItem(myNewEntry5);
ActiveDs.PropertyEntry myNewEntry6 = new ActiveDs.PropertyEntry();
ActiveDs.IADsPropertyValue propVal6 = new ActiveDs.PropertyValue();
propVal6.CaseIgnoreString = userObj.userName;
propVal6.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
myNewEntry6.Name = "uid";
myNewEntry6.Values = new object[] { propVal6 };
myNewEntry6.ControlCode = (int)ADS_PROPERTY_OPERATION_ENUM.ADS_PROPERTY_APPEND;
myNewEntry6.ADsType = (int)ADSTYPEENUM.ADSTYPE_CASE_IGNORE_STRING;
propList.PutPropertyItem(myNewEntry6);
de.RefreshCache(new String[] { "objectClass" });
de.RefreshCache(new String[] { "gidNumber" });
de.RefreshCache(new String[] { "homeDirectory" });
de.RefreshCache(new String[] { "uidNumber" });
de.RefreshCache(new String[] { "cn" });
de.RefreshCache(new String[] { "uid" });
de.CommitChanges();
success = true;
}
}
catch (Exception ex)
{
Trace.Write("Exception : RegisterUser: " + ex);
GeneralUtils.SendBugMail(ex, httpContext);
}
}
return success;
}

I think the error you get would be informative for diagnosing any further.
When you create an object in AD I am pretty sure even if you do not specify a CN you get a default naming attribute of CN set. So this posixAccount create, which is setting cn, might be conflicting with an existing cn value. I forget if CN is multivalued or single valued in AD, but if it is single valued this would make more sense.

Related

connect to ssrs srevice in asp.net core

I get exception when connection with ssrs service last for more than 5 minutes
var binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Ntlm;
binding.MaxReceivedMessageSize = 2147483647;
binding.MaxBufferPoolSize = 2147483647;
binding.MaxBufferSize = 2147483647;
binding.SendTimeout = TimeSpan.FromMinutes(_SendTimeout);
binding.OpenTimeout = TimeSpan.FromMinutes(_SendTimeout);
binding.ReceiveTimeout = TimeSpan.FromMinutes(_SendTimeout);
binding.CloseTimeout = TimeSpan.FromMinutes(_SendTimeout);
var rsExec = new rsexec2005.ReportExecutionServiceSoapClient(binding, new
EndpointAddress(SSRSReportExecutionUrl));
var clientCredentials = new NetworkCredential(SSRSUsername, SSRSPassword,
SSRSDomain);
if (rsExec.ClientCredentials != null)
{
rsExec.ClientCredentials.Windows.AllowedImpersonationLevel =
System.Security.Principal.TokenImpersonationLevel.Impersonation;
rsExec.ClientCredentials.Windows.ClientCredential = clientCredentials;
}
LoadReportResponse report = null;
try
{
rsExec.Endpoint.EndpointBehaviors.Add(new
ReportingServicesEndpointBehavior());
report = await rsExec.LoadReportAsync(null, "/" + SSRSFolderPath + "/" +
reportName, null);
}
catch (Exception ex1)
{
return new Response { code = 1, report = null, message = ex1.InnerException +"
# "+ ex1.Message };
}
rsexec2005.ParameterValue[] reportParam = new
rsexec2005.ParameterValue[report.executionInfo.Parameters.ToList().Count];
var Count = 0;
foreach (var item in report.executionInfo.Parameters.ToList())
{
var Paramkay = Params.Keys.SingleOrDefault(i => i.ToLower() ==
item.Name.ToLower());
if (Paramkay != null)
{
reportParam[Count] = new rsexec2005.ParameterValue();
reportParam[Count].Name = item.Name;
reportParam[Count].Value = Params[Paramkay];
Count++;
}
}
await rsExec.SetExecutionParametersAsync(null, null, reportParam, "en-us");
RenderResponse response = null;
try
{
const string deviceInfo = #"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
response = await rsExec.RenderAsync(new RenderRequest(null, null, extention, deviceInfo));
}
catch (TimeoutException ex4)
{
return new Response { code = 4, report = null , message= ex4.InnerException + " # " + ex4.Message };
}
catch (Exception ex2)
{
return new Response { code = 2, report = null , message = ex2.InnerException + " # " + ex2.Message };
}

WCF - CustomBinding for signing timestamp, body and BinarySecirityToken

I need to call a java/Oracle partner which has strict format requirements.
My request should look like this :
sample request
But it actually looks like this :
my request
The BinarySecurityToken is duplicated for some reason.
My custom binding :
UPLVaccinatieGegevensClient client = new UPLVaccinatieGegevensClient(GetBinding(), new EndpointAddress(new Uri("https://...."), EndpointIdentity.CreateDnsIdentity("...")));
client.ClientCredentials.ClientCertificate.SetCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.X509FindType.FindByThumbprint, "...");
client.ClientCredentials.ServiceCertificate.SetDefaultCertificate(System.Security.Cryptography.X509Certificates.StoreLocation.LocalMachine, System.Security.Cryptography.X509Certificates.StoreName.My, System.Security.Cryptography.X509Certificates.X509FindType.FindByThumbprint, "...");
var vs = client.Endpoint.EndpointBehaviors.FirstOrDefault((i) => i.GetType().Namespace == "Microsoft.VisualStudio.Diagnostics.ServiceModelSink");
if (vs != null)
{
client.Endpoint.Behaviors.Remove(vs);
}
client.Endpoint.Contract.ProtectionLevel = System.Net.Security.ProtectionLevel.Sign;
//UPLVaccinatieGegevensClient client = new UPLVaccinatieGegevensClient("UPLVaccinatieGegevens1");
var request = GetRequest();
var response = client.GetAanleverenVaccinatieGegevens(request);
}
private static CustomBinding GetBinding()
{
var messageSecurity = new AsymmetricSecurityBindingElement
{
MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10,
InitiatorTokenParameters = new X509SecurityTokenParameters
{
InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient,
ReferenceStyle = SecurityTokenReferenceStyle.External,
X509ReferenceStyle = X509KeyIdentifierClauseType.RawDataKeyIdentifier,
RequireDerivedKeys = false
},
RecipientTokenParameters = new X509SecurityTokenParameters
{
InclusionMode = SecurityTokenInclusionMode.Never,
ReferenceStyle = SecurityTokenReferenceStyle.External,
X509ReferenceStyle = X509KeyIdentifierClauseType.Any,
RequireDerivedKeys = false
},
};
messageSecurity.EnableUnsecuredResponse = true;
messageSecurity.IncludeTimestamp = true;
messageSecurity.SecurityHeaderLayout = SecurityHeaderLayout.LaxTimestampFirst;
messageSecurity.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Basic256;
messageSecurity.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
messageSecurity.SetKeyDerivation(false);
messageSecurity.EndpointSupportingTokenParameters.Signed.Add(messageSecurity.InitiatorTokenParameters);
messageSecurity.LocalClientSettings.TimestampValidityDuration = new TimeSpan(0, 1, 0);
HttpsTransportBindingElement elem = new HttpsTransportBindingElement { RequireClientCertificate = true };
CustomBinding binding = new CustomBinding(messageSecurity, new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), elem);
return binding;
}
What am I missing ?
It appears that the extra token was being added when X509SecurityTokenParameters.InclusionMode was set to anything else than SecurityTokenInclusionMode.Never on the either of InitiatorTokenParameters, RecipientTokenParameters or EndpointSupportingTokenParameters.Signed.
You can try to set the value of InclusionMode to SecurityTokenInclusionMode.Never:
InclusionMode = SecurityTokenInclusionMode.Never

how to populate comma delimited string to checkboxlist in gridview

protected void MYgrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList ddlC = (DropDownList)e.Row.FindControl("ddlCountry1");
DropDownList ddlS = (DropDownList)e.Row.FindControl("ddlState1");
if (ddlC != null)
{
BindCountry(ddlC, ddlS);
}
}
if (e.Row.RowType == DataControlRowType.DataRow && MYgrid.EditIndex == e.Row.RowIndex)
{
DropDownList ddlC = (DropDownList)e.Row.FindControl("ddlCountry");
DropDownList ddlS = (DropDownList)e.Row.FindControl("ddlState");
if (ddlC != null)
{
cmd = new SqlCommand("select * from M_Country", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlC.DataSource = dt;
ddlC.DataTextField = "CountryName";
ddlC.DataValueField = "C_ID";
ddlC.DataBind();
ddlC.Items.FindByText((e.Row.FindControl("lblCountry") as Label).Text).Selected = true;
}
if (ddlS != null)
{
cmd = new SqlCommand("select * from M_State", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlS.DataSource = dt;
ddlS.DataTextField = "StateName";
ddlS.DataValueField = "S_ID";
ddlS.DataBind();
ddlS.Items.FindByText((e.Row.FindControl("lblState") as Label).Text).Selected = true;
}
RadioButtonList rblG = (RadioButtonList)e.Row.FindControl("rblGender");
rblG.Items.FindByText((e.Row.FindControl("lblGender") as Label).Text).Selected = true;
CheckBoxList chkH = (CheckBoxList)e.Row.FindControl("chkHobby");
Label ll = (Label)e.Row.FindControl("lblHobby");
string ss = ll.Text;
string[] ss1 = ss.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string ss2 in ss1)
{
for (int i = 0; i < 2; i++)
{
if (ss2 == chkH.Items[i].Text)
{
chkH.Items[i].Selected = true;
}
}
}
}
}

CloudStack: Unable to verify user credentials and/or request signature

I am working on CloudStack API now and I have the problem about making the API request. I always got "{ "listtemplatesresponse" : {"errorcode":401,"errortext":"unable to verify user credentials and/or request signature"} }" even though I change the parameter.
This error occurs in some commands that require the parameter and this is the command that I use:
command=listTemplates&templatefilter=featured
I don't know what I did wrong since it works with others. Here is the code I use to make the API request:
try {
String encodedApiKey = URLEncoder.encode(apiKey.toLowerCase(), "UTF-8");
ArrayList<String> sortedParams = new ArrayList<String>();
sortedParams.add("apikey="+encodedApiKey);
StringTokenizer st = new StringTokenizer(apiUrl, "&");
while (st.hasMoreTokens()) {
String paramValue = st.nextToken().toLowerCase();
String param = paramValue.substring(0, paramValue.indexOf("="));
String value = URLEncoder.encode(paramValue.substring(paramValue.indexOf("=")+1, paramValue.length()), "UTF-8");
sortedParams.add(param + "=" + value);
}
Collections.sort(sortedParams);
System.out.println("Sorted Parameters: " + sortedParams);
String sortedUrl = null;
boolean first = true;
for (String param : sortedParams) {
if (first) {
sortedUrl = param;
first = false;
} else {
sortedUrl = sortedUrl + "&" + param;
}
}
sortedUrl += "&response=json";
System.out.println("sorted URL : " + sortedUrl);
String encodedSignature = signRequest(sortedUrl, secretKey);
String finalUrl = host + "?" + apiUrl + "&response=json&apiKey=" + apiKey + "&signature=" + encodedSignature;
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(finalUrl);
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
System.out.println("str: "+str);
result = str.toString();
System.out.println("result: "+str);
}
else
System.out.println("Error response!!");
} catch (Throwable t) {
System.out.println(t);
}
And this is signRequest function:
public static String signRequest(String request, String key) {
try {
Mac mac = Mac.getInstance("HmacSHA1");
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
mac.init(keySpec);
mac.update(request.getBytes());
byte[] encryptedBytes = mac.doFinal();
return URLEncoder.encode(Base64.encodeBytes(encryptedBytes), "UTF-8");
} catch (Exception ex) {
System.out.println(ex);
}
return null;
}
Please feel free to ask me if you need more information. All comments and advice are welcome!
Have you tried sorting after you've added "&response=json" to the list of parameters?
E.g.
try {
String encodedApiKey = URLEncoder.encode(apiKey.toLowerCase(), "UTF-8");
ArrayList<String> sortedParams = new ArrayList<String>();
sortedParams.add("apikey="+encodedApiKey);
sortedParams.add("response=json");
StringTokenizer st = new StringTokenizer(apiUrl, "&");
while (st.hasMoreTokens()) {
String paramValue = st.nextToken().toLowerCase();
String param = paramValue.substring(0, paramValue.indexOf("="));
String value = URLEncoder.encode(paramValue.substring(paramValue.indexOf("=")+1, paramValue.length()), "UTF-8");
sortedParams.add(param + "=" + value);
}
Collections.sort(sortedParams);
System.out.println("Sorted Parameters: " + sortedParams);
String sortedUrl = null;
boolean first = true;
for (String param : sortedParams) {
if (first) {
sortedUrl = param;
first = false;
} else {
sortedUrl = sortedUrl + "&" + param;
}
}
System.out.println("sorted URL : " + sortedUrl);
String encodedSignature = signRequest(sortedUrl, secretKey);
String finalUrl = host + "?" + apiUrl + "&response=json&apiKey=" + apiKey + "&signature=" + encodedSignature;
StringBuilder str = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(finalUrl);
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) { // Status OK
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
str.append(line);
}
System.out.println("str: "+str);
result = str.toString();
System.out.println("result: "+str);
}
else
System.out.println("Error response!!");
} catch (Throwable t) {
System.out.println(t);
}
Your API Key and Response parameters need to be part of the sorted Url used when signing, which they appear to be.
try changing
return URLEncoder.encode(Base64.encodeBytes(encryptedBytes), "UTF-8");
to
return URLEncoder.encode(Base64.encodeAsString(encryptedBytes), "UTF-8");

.ToList() throws exception of "Object reference not set to an instance of an object."

private void BindDataGridDetails(string p)
{
var allClients = new List<DataLayer.Client>();
if (string.IsNullOrWhiteSpace(p))
{
allClients = entities.Clients.ToList();
}
else
{
allClients = entities.Clients.Where(m =>m.CompanyName.Contains(p)||m.ContactPersonName.Contains(p)).ToList();
}
allClients = entities.Clients.ToList();
var finalClientList = allClients.Select(v => new
{
v.UserId,
v.MobileNumber,
v.Designation,
v.CompanyName,
v.ContactPersonName,
EmailAddress = v.User.EmailAddress,
status = v.User.Status.Name
}).ToList();
Gdview.DataSource = finalClientList;
Gdview.DataBind();
}
Following is the required db table
User(id,statusid,emailaddress)
client(id,userid,designation,mobilenumber,companyname,contactperson)
status(statusid,statusname)