Wednesday, September 04, 2013

C# : Always learn something new

Saw this on Rob Miles blog.

What does ?? mean in C# ?

You can read the full article but the essence is:

"?? provides a convenient way that I can map the null value of a nullable variable onto a specific value

int actualAge = customerAge ?? -1;
 
It saves us having to write code that tests for null and sets a value appropriately. 

The above statement sets the value of actualAge to the value in customerAge unless the value in customerAge is null, in which case it sets it to –1.

if (customerAge == null)
    actualAge = -1;
else    actualAge = customerAge;
 
In other words ?? is a short form of the above test"

Enjoy!
 



ADFS : MSIS7042: The same client browser session has made '6' requests in the last '1' seconds.

Out of the blue, got this problem.

WTF?

So reviewed my changes to date.

I had made a change to fix the ubiquitous problem:

ID3206: A signin response may only redirect within the current web application

If you have played with WIF, you will have seen this particular problem.

The solution is BTW:

Add this to the global.asax

private void Application_BeginRequest(object sender, EventArgs e)
{
      if (String.Compare(Request.Path, Request.ApplicationPath,     StringComparison.InvariantCultureIgnoreCase) == 0 && !(Request.Path.EndsWith("/")))
                Response.Redirect(Request.Path + "/");

}
This seemed to have fixed the bug but then introduced another - the dreaded slippery slope.

After googling around, I found the problem.

In my ADFS RP, I had configured the endpoint without a trailing slash.

Added the missing "/" and all was well.

Enjoy!

Thursday, August 29, 2013

Stackoverflow : onwards and upwards

Moving up the ladder!

Top 3% and all!


Enjoy!

Wednesday, August 28, 2013

C# : String with spaces is not null or empty

Came across an interesting case.

I was checking a text field with

String.IsNullOrEmpty

and I noticed that if you enter spaces, it is neither null or empty!

Mr. Google out of bed bright and early and:

String.IsNullOrEmpty() Check for Space

The solution is the "IsNullOrWhiteSpace(string value)" one.

Enjoy!
 

AAD : SSO between AAD and Salesforce

The write-up is here:

Tutorial: Windows Azure AD integration with Salesforce

but I couldn't get it working.

Luckily, I have some SAML experience so figured out the problem.

I posted before about how important it is to get the NameID stuff right and this was indeed the problem.

When you create the user in Salesforce, you have to make sure that the Salesforce username is exactly the same as the login name you use for your AAD tenant.

And you have to use a valid email name.

The email name and username do not have to match.

So assume I log into my AAD tenant as:

jbloggs@tenant.onmicrosoft.com

My email address is jbloggs@gmail.com.

So I create the Salesforce user with:

email = jbloggs@gmail.com

username = jbloggs@tenant.onmicrosoft.com

Check your email - you will get a "Change Password" email from Salesforce.

Change your password. 

Login to AAD - navigate to the Access Panel - click Salesforce.

What will happen is that AAD will take your logged in name, put it in a NameID SAML assertion called username and pass it to Salesforce.

Salesforce will check that there is a registered user with that username.

There is so A-OK - you are logged in.

I did not have to synchronise any accounts to achieve this.

Enjoy!


Monday, August 12, 2013

ASP.NET : Inline validation controls no longer red

So I had a project that I was busy migrating from .NET 3.5 to .NET 4.5.

Now I use the asp:RequiredFieldValidator controls and suddenly I noticed that the error messages were no longer in red.

I then compared the projects - no obvious .ccs changes or anything like that.

Then I compared the web.config files and noticed that:

pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID" validateRequest="false"

had changed to:

pages controlRenderingCompatibilityVersion="4.0" clientIDMode="AutoID" validateRequest="false"

This must have happened during the wizard that migrates the project.

Have a look at:

What's New in ASP.NET 4 and Visual Web Developer

where it mentions that validators no longer render inline color:Red styles.

Changing it back to "3.5" sorted it out.

Isn't red the international error colour anyway?

Enjoy!


Friday, August 09, 2013

WCF : The request for security token could not be satisfied because authentication failed

 

In full:

System.ServiceModel.Security.SecurityNegotiationException The caller was not authenticated by the service. System.ServiceModel.FaultException: The request for security token could not be satisfied because authentication failed.

I see this when the WS call is cross domain on wsHttpBinding.

Quick and dirty is to remove the security (or move to basicHttpBinding).

Not recommended on a Production system but to get over the hump …

On the client side change:

<wsHttpBinding>
<binding name="WSHttpBinding_IService" >
<security mode="None" />
</binding>
</wsHttpBinding>


On the WS side change:


<system.serviceModel>
<services>
<service name=xxx">
<endpoint address="" binding="wsHttpBinding" contract="WcfServiceLibrary.IService" bindingConfiguration="NoSecurityConfig">
<identity>
<dns value="yyy" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>

<bindings>
<wsHttpBinding>
<binding name="NoSecurityConfig">
<security mode="None" />
</binding>
</wsHttpBinding>
</bindings>


Essentially, the changes are to add the “security mode = None” and to add the new bindingConfiguration ="NoSecurityConfig" and then specify the binding for it.



Enjoy!






Monday, July 29, 2013

Visual Studio : Could not write lines to file xxx Access to the path yyy is denied

Using Visual Studio 2012, checked a project into TFS and got the above error.

WTF?

Mr. Google to the rescue and the majority view was either:
  • Make the file readable i.e. no readonly
  • Delete the /bin and /obj directories and rebuild
The file was R/W already so went for option 2 and the error disappeared.

All good!

Enjoy!


Wednesday, July 03, 2013

AD : Locked accounts in Active Directory (AD)

This is truly a curved ball.

Once upon a time, there was an attribute in AD called:

  userAccountControl - ADS_UF_LOCKOUT = 16 (d) 10 (h)

However, in later versions of Windows Server (e.g. 2008), this was moved to:

  msDS-User-Account-Control-Computed - UF_LOCKOUT = 16 (d) 10 (h).

BUT there was a slight problem. As the name implies this is a computed attribute i.e. it doesn't actually exist. Rather it is computed on the fly. The implication is that it can't be used in a standard search query.

Hence the curved ball.

Some blogs suggest you can use:

filter = "(&(objectClass=user)(lockoutTime>=0))"  

This works in the sense that it refines a potentially huge list to a much smaller one.

However, it is not sufficient. When a user is locked out and then unlocked, this attribute can be set to zero (as opposed to the previous time that was stored). 

Easy enough, change the filter to:

filter = "(&(objectClass=user)(lockoutTime>0))"  

Dream on - that's not a valid filter query language construct.

So this first list has to be iterated through again to check that the user is actually locked.

Lots of code out there to do this e.g.
UserPrincipal oUserPrincipal = GetUser(sUserName); 
userPrincipal.IsAccountLockedOut();
or if you want to get fancy - refer c# LDAP check user is locked or not
string attribName = "msDS-User-Account-Control-Computed";
user.RefreshCache(new string[] { attribName });
const int UF_LOCKOUT = 0x0010;
int userFlags = (int)user.Properties[attribName].Value;
if ( (userFlags & UF_LOCKOUT) == UF_LOCKOUT)
{
    // if this is the case, the account is locked out
    return true;
}
return false;

To unlock - refer Everything in Active Directory via C#.Net 3.5 (Using System.DirectoryServices.AccountManagement).
UserPrincipal oUserPrincipal = GetUser(sUserName);
oUserPrincipal.UnlockAccount();
oUserPrincipal.Save();
To unlock via ADUC, click the Account tab on the user's Properties and then check the "Unlock Account" check box.

Note: You cannot lock an account either programmatically or through ADUC.

The system will lock the account based on the user's password policy e.g. user will be locked out after x invalid attempts. The policy may state that the user many never be locked out.

Enjoy!

Tuesday, July 02, 2013

Misc : The blog clocks up 100,000 page views

Whoop de do!

100354 pageviews and counting!

Enjoy!

ASP : WTF happened to my asp:Menu in .NET Framework 4.5?

Going through the upgrade exercise I mentioned in my previous post.

All good but my menu is now poked - all bunched up to the left. Still works but looks really munged!

Mr. Google to the rescue!

Menu.RenderingMode Property

The reason is that:

"The value of the RenderingMode property determines how the menu control renders markup for the Menu control.

In ASP.NET 3.5 and earlier versions, the Menu control uses HTML table elements and inline styles to specify the appearance of the menu in a browser. In ASP.NET 4 and later versions, by default the Menu control uses HTML listitem elements and cascading style sheet (CSS) styles."


Enjoy!

WIF : Migrate from WIF 3.5 to WIF 4.5 and VS 2010 to VS 2012


Been going through this exercise lately and thought I would document for others.

Some references:

http://msdn.microsoft.com/en-us/library/jj157091.aspx
http://msdn.microsoft.com/en-us/library/jj157089.aspx
http://msdn.microsoft.com/en-us/library/hh873305.aspx
http://msdn.microsoft.com/en-us/library/hh987037.aspx

Copy project to another directory, make all files R/W and then open with VS 2012. Check migration report.

Remove source control references if applicable.

Under Properties / Application / Target Framework, change to 4.5.

Remove Microsoft.IdentityModel from References

Add System.IdentityModel and System.IdentityModel.Services to references.

Change “using Microsoft.IdentityModel.Claims” to “using System.Security.Claims”

Change IClaimsPrincipal to ClaimsPrincipal

Change IClaimsIdentity to ClaimsIdentity

Change claim.ClaimType to claim.Type. Similarly for ClaimValue etc.

'FederatedPassiveSignInStatus' control has been removed. Remove all references. This includes the
<%@ Register assembly="Microsoft.IdentityModel"
namespace="Microsoft.IdentityModel.Web.Controls" tagprefix="wif" %>
in the aspx pages.

Add STS / FedUtil functionality has been removed. You need to download the “Identity and Access Tool” (available via NuGet).

Running the tool makes “different” changes to the web.config e.g. adds sections for system.identityModel.and a ida:FederationMetadataLocation section.

Comment out all the microsoft.identityModel sections in the web.config.

Update:

<modules runAllManagedModulesForAllRequests="true">
<!-- <add name="WSFederationAuthenticationModule" type="Microsoft.IdentityModel.Web.WSFederationAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler" />-->
<!-- <add name="SessionAuthenticationModule" type="Microsoft.IdentityModel.Web.SessionAuthenticationModule, Microsoft.IdentityModel, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" preCondition="managedHandler" />-->
<add name="WSFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
<add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"/>
</modules>

Enjoy!