C# Active Directory

2 min read

using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

.Net has a UserPrincipal built-in class, which will allow you quick access to common objects such as the Name and User Principal name

 // create your domain context
 PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
 // define a "query-by-example" principal - here, we search for a UserPrincipal
 // and with the first name (GivenName) of "Bruce"
 UserPrincipal qbeUser = new UserPrincipal(ctx);
 qbeUser.GivenName = "Steve";
 // create your principal searcher passing in the QBE principal
 PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
 // find all matches
 foreach(var found in srch.FindAll())
 {
   // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....
 }

MVC Remote Validator

< 1 min read Let’s take a look at a brand new MVC 3 validator – RemoteAttribute. The Remote validator is very simple to use and yet extremely powerful. Remote is for situations where it is impossible to duplicate server side validation logic on the client, often because the validation involves connecting to a database or calling a service. If all your other validation uses javascript and responds to the user’s input immediately, then it is not a good user experience to require a post back to validate one particular field. This is where the remote validator fits in.
In this example, we are going to add remote validation to the username field to check that it is unique.

[Remote("ValidateUserName", "Account", ErrorMessage = "Username is not available.")]
public string UserName { get; set; }

Remote has three constructors allowing you to specify either a routeName, a controller and action or a controller, action and area. Here we are passing controller and action and additionally overriding the error message

public ActionResult ValidateUserName(string username)
{
    return Json(!username.Equals("duplicate"), JsonRequestBehavior.AllowGet);
}

SQL Full Backup all databases

< 1 min read Backups are one of the most important tasks when maintaining a system, and as the complexity of your environment grows, you need tools to automate tasks. Using the SQL Agent, you can schedule the following stored procedure to back up every database and database log on your server (or modify it to your needs), excluding some stuff you can live without.

CREATE PROCEDURE BackupDatabases
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE @name VARCHAR(50) /*database name*/
    DECLARE @dbpath VARCHAR(256) /*path for backup db files*/
    DECLARE @logpath VARCHAR(256) /*path for backup log files*/
    DECLARE @dbName VARCHAR(256) /*filename for backup*/
    DECLARE @logName VARCHAR(256) /*filename for backup*/
    DECLARE @fileDate VARCHAR(20) /*used for file name*/
    SET @dbpath = 'C:Database Backup'
    SET @logpath = 'C:Database Log Backup'
    SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
    DECLARE db_cursor CURSOR FOR
    SELECT name
    FROM master.dbo.sysdatabases
    WHERE name NOT IN ('master','model','msdb','tempdb') /* Exclude any databases you don't want to backup */
    OPEN db_cursor  
    FETCH NEXT FROM db_cursor INTO @name  
    WHILE @@FETCH_STATUS = 0  
    BEGIN  
           SET @dbName = @dbpath + @name + '_' + @fileDate + '.BAK'
           BACKUP DATABASE @name TO DISK = @dbName WITH FORMAT;
           SET @logName = @logpath + @name + '_' + @fileDate + '.BAK'
           BACKUP LOG @name TO DISK = @logName;
           FETCH NEXT FROM db_cursor INTO @name
    END
    CLOSE db_cursor
    DEALLOCATE db_cursor
END
GO

SQL Batch alter all columns

< 1 min read

Sometimes you need to make mass changes to a database, and either add or remove a column, or other table or data manipulations. The script below prints SQL statements you can later execute for whatever you need. It loops through each table in your database, and replaces ? with the table name.

EXEC sp_msforeachtable
'PRINT ALTER TABLE ? ADD LastModified DATETIME NOT NULL DEFAULT GETDATE();
ALTER TABLE ? ADD UserID int NULL;
ALTER TABLE ? ADD Deleted bit NOT NULL DEFAULT 0;'
EXEC sp_msforeachtable
    'PRINT Update ? SET SiteID=1'

IE 8 HTML5 Compatibility

< 1 min read Adds new HTML5 elements, and supports printing HTML5 elements and includes the default styles for HTML5 elements, like block on article and section.

To use this script, download the html5shiv and roll it in to your own code (ideally minified). It must be included before theelement (i.e. in the) but doesn’t matter if it appears before or after the CSS – but for the sake of performance, it would make better sense to include the CSS first then this script.


Dynamic Linq for searching

< 1 min read

 var predicate = PredicateBuilder.True();
 var q = db.Profiles.Where(t => !t.aspnet_Users.aspnet_Membership.IsLockedOut);
 foreach (string keyword in pars)
 {
     string temp = keyword;
     predicate = predicate.And(t => t.FirstName.StartsWith(temp) || t.LastName.StartsWith(temp));
 }

Filezilla Access to only certain subfolders

< 1 min read I had a scenario once, where I needed to give certain users access to multiple sub folders, without creating multiple FTP accounts. The goal was for them to see certain folders, but not others.
So let’s say my folder structure is:

And my user should be able to have full control of Site1 and Site2, but not even see Site3.
To do this, first create the user, and give him only List access on the root folder

Next, add each of the sub folders he has access to, and give him appropriate access on each sub folder.

When he connects now, he will only see the folders he has access to.

C# Render Razor View as String

< 1 min read The Razor View Engine is very powerful, easy to use, and just overall great for binding data to HTML. But sometimes you need to render HTML for use in Emails, download pages, generate PDF’s, or other purposes, so it would be neat if you could use the Razor View Engine to generate those for you, and just give you the HTML to do with it as you wish. Luckily we have this somewhat built-in, and here’s a wrapper for it.

public string RenderRazorViewToString(string viewName, object model)
{
  ViewData.Model = model;
  using (var sw = new StringWriter())
  {
    var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
    var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);
    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
    return sw.GetStringBuilder().ToString();
  }
}

You can now use it as in the following example

var htmlPage = RenderRazorViewToString("~/Views/Home/myview.cshtml", siteModel);

You can of course extend the method above, and pass it your own ViewData, TempData, RouteData, change the View Engine, enable or disable ClientValidation and UnobtrusiveJavasript, and so on.

C# Add and Edit Office Document Custom Properties

< 1 min read Office documents store a lot more information than is obviously visible at first. Microsoft released a library called DSOfile, which is intended for changing properties of Office files if you don’t have Office installed.
First, you need to download the DSOfile from Microsoft. http://support.microsoft.com/kb/224351

Second, you’ll need to reference it in your project

using DSOFile;

Next, you can start looping through the Office predefined properties of each file. Note, some attributes are read-only.

OleDocumentProperties file = new OleDocumentProperties();
file.Open(@"C:myfile.docx", false, dsoFileOpenOptions.dsoOptionDefault);
int charCount = file.SummaryProperties.CharacterCount;
int wordCount = file.SummaryProperties.WordCount;
int pageCount = file.SummaryProperties.PageCount;
file.SummaryProperties.Author = "John Smith";
file.SummaryProperties.Category = "My Category";
file.SummaryProperties.Company = "My Company Inc.";
file.SummaryProperties.Manager = "David Smith";
file.SummaryProperties.Subject = "Sample files";
file.SummaryProperties.Title = "A very sample file";
file.Save();
file.Close(true);

Those might sometimes not be enough, so surely enough you can add your own custom attributes, and use the NTFS File System as your own personal database.

OleDocumentProperties file = new DSOFile.OleDocumentProperties();
file.Open(@"C:myfile.docx", false, DSOFile.dsoFileOpenOptions.dsoOptionDefault);
string key = "My Custom Key"; /* Use any key you want, these will be saved in the file. */
object value = "My Custom Value";
// Check if file has a certain property set
bool hasProperty = false;
foreach (DSOFile.CustomProperty p in file.CustomProperties)
    if (p.Name == key)
        hasProperty = true;
// If it doesn't have the property, add it, otherwise set it.
// This is the only way I found to loop through the properties
if (!hasProperty)
    file.CustomProperties.Add(key, ref value);
else
    foreach (DSOFile.CustomProperty p in file.CustomProperties)
        if (p.Name == key)
            p.set_Value(value);
// Go through existing custom properties.
foreach (DSOFile.CustomProperty p in file.CustomProperties)
{
    Console.WriteLine("{0}:{1}", p.Name, p.get_Value().ToString());
}
file.Save();
file.Close(true);