Tag Archive: csharp


Universal Caching

I wrote this library so I don’t have to keep track if I should use HttpRuntime.Cache, AppDomain.CurrentDomain.SetData, HttpContext.Current.Session, or a Dictionary…now I just use GlobalCache or UserCache.  It also makes unit testing a webapp a snap, because if you use IGlobalCache/IUserCache in your code, you just inject the Windows-based cache in your unit test setup.

You can download the solution with dlls here: Universal Caching solution

How to eliminate magic strings from Html.DropDownListFor

Magic strings are just nuclear-powered bug magnets. They attract fat-fingering mistakes while coding and practically guarantee bugs will be introduced while refactoring. If you’re like me, you’ll hate the magic strings required in the Html.DropDownListFor as much as I do. Now there’s an easy way to get rid of them once and for all…

View full article »

If you have a entity with a nested entity, you can show the nested entity’s properties with a little trick.

For example if you have these business objects:

public class MyObj
{     
    public MyOtherObj MyProperty { get; set; }
}

public class MyOtherObj
{
     public int SomeProperty { get; set; }
}

If you want to show a field from MyProperty (e.g. MyOtherObj.SomeProperty), and MyObj is your report’s datasource, your report fieldbox will need to look like this:

First(Fields!MyProperty.Value.SomeProperty)

(NOTE: do not add “.Value” onto the end of the property name as normal, it will produce a #error at runtime).

How to get failed login attempts and last login date from AD server

You can fetch a user’s last good login date and number of failed login attempts from the AD server. First, you will need these keys in your section in your web.config (which will need to be updated as the app is passed to QA/Prod):
We will store the login attempts:

public void StoreLoginAttempts(string userName)
{
string adServer = GetConfigAppSettings("AD_DomainIP");
string adServerUser = GetConfigAppSettings("AD_User");
string adServerPassword = GetConfigAppSettings("AD_Pass");
string adServerContainer = GetConfigAppSettings("AD_Container");

// looks like this: "CN=Users,DC=AD,DC=MyDomain,DC=org"
if (!string.IsNullOrEmpty(adServer) 
&& !string.IsNullOrEmpty(adServerUser) 
&& !string.IsNullOrEmpty(adServerPassword) 
&& !string.IsNullOrEmpty(adServerContainer))
{
PrincipalContext principalContext =
new PrincipalContext
(ContextType.Domain,adServer,adServerContainer,adServerUser,adServerPassword);
UserPrincipal user = 
UserPrincipal.FindByIdentity(principalContext, userName);
int numberOfFailedLoginAttempts = user.BadLogonCount;
DateTime? lastSuccessfulLogin = null;
if (user.LastLogon != null)
{
lastSuccessfulLogin = user.LastLogon.Value.ToLocalTime();
}

// save to session 
storeSetSession("NumberOfFailedLoginAttempts", 
numberOfFailedLoginAttempts.ToString());
SetSession("LastSuccessfulLogin", lastSuccessfulLogin.ToString());
}
}

You can fetch the login attempts and last login by getting the session object. For example, you can use a code block like this in your code to populate the login attempts message in your app’s header or footer:

private string GetLoginAttemptsMessage()
{
// get values from session saved during LogOn
string numberOfFailedLoginAttempts = GetSession("NumberOfFailedLoginAttempts");
string lastSuccessfulLogin = GetSession("LastSuccessfulLogin");
return
string.Format("There have been {0} unsuccessful login attempt(s) since your last successful AD login on {1}"
,numberOfFailedLoginAttempts, lastSuccessfulLogin);
}

Here’s an easy way to get the MVC root path in JavaScript Js files. Since Js files don’t let you run embedded C# code, and you don’t want to hard code a URL path because the dev and production environments have different root paths, so it’s hard to get properly resolved URLs for JavaScript in MVC. One way to solve this is to create an extension method (JavaScript calls it a prototype) to a global variable in your Site.Master page that automatically converts any reference to “~/” to your MVC root path.
Place this JavaScript block above your links and script references in your Site.Master page (for example, right underneath the head tag).

// THIS MUST BE LEFT AT THE TOP OF THE PAGE...all links and scripts below will need this extension method
// Create an extension method ("resolve") 
that returns the correct server path of the server, whether the server is virtual directory or root
Url = 
function() { }
Url.prototype ={
_relativeRoot: '<%= ResolveUrl("~/") %>',
// create an extension method called "resolve"
resolve: function(relative) {
var resolved = relative;
if (relative.charAt(0) == '~') 
resolved = this._relativeRoot + relative.substring(2);
return resolved;
}
}
$Url = new Url();

Now in any js file in JavaScript that requires an MVC path resolution, just use:

var imageUrl = $Url.resolve("~/mypic.gif");  //’resolve’ is an extension method created in Site.Master
© 2017 Robert Corvus