C# ASP.NET Webpage Change Database Query Timeout

I had a c# web page that was taking longer and longer to query a growing database. The fact that the page took a few moments to load wasn’t a problem however the fact that it would timeout was.

I tried adjusting the connection string to have a Connection Timeout parameter on it however eventually realised the connection string was not the place to set this property.

Continue reading

Active Directory Synchronization With Office 365

Its fairly simple for even the smallest organisation to implement single “sign-on” with Office365. This doesnt require a complex ADFS implementation but comes in the form of username and password synchronisation.

The first thing the organisation needs is a public domain and the ability to update the DNS records for it. This public domain will be used to make up the UPN’s (user principal names) that users will use to logon in both the on-premise environment and when logging on to their O365 account.

Continue reading

SQL Group By

I had a list of items in a database with a date against them of when they were last updated. Each item appeared in the database twice and potentially with different dates against them:

When using a “Select Distinct” query this resulted in 2 rows being returned for some of the items because the dates were different.

Continue reading

Powershell Workflows

 

I had a job that was scanning a growing folder structure which was taking longer and longer as the folder structure grew and I needed a way to make the job run faster. At this point I discovered powershell workflows which seemed like an easy way to separate my processing job into multiple threads.

There is plenty of reading around workflows written by people far more in the know about powershell than I am.

Ed Wilson wrote a great article explaining it: https://blogs.technet.microsoft.com/heyscriptingguy/2012/12/26/powershell-workflows-the-basics/
Stephane van Gulick also wrote a great article: http://powershelldistrict.com/powershell-workflows/

Continue reading

Powershell Start-Job not working from scheduled task

I had a powershell script that used the start-job command to pass some variables to another script that would run in the background.

I was using start-job as i was passing an array as one of the parameters to the second script and calling powershell.exe and passing an array did just not work (someone may be able to confirm if that is expected behavior).

Continue reading

IIS Custom Error Pages For .Net Applications

When taking a temporary intranet portal offline it was necessary to make sure that users would hit a certain page if they tried to revisit any part of the site.
The standard 404 Not Found Error would be received but we wanted to redirect them to a custom page instead. This is not difficult in IIS but what will redirect for a missing html page will not redirect for a .aspx page, further configuration is needed.

When trying to browse for any page that does not exist:

1

Continue reading

C# aspx Page Throwing 404 Error

I was recently working on a c# .aspx page in Visual Studio. The page had a gridview linked to a SQL datasource and various buttons. The page was working fine for some time however after some changes that initially seemed to cause no issue (the issue was still seen after undoing said changes) i was getting 404 Page Not Found errors whenever i clicked a button on the page or tried to edit/select a row in the gridview.
Continue reading

c# .Net Query Active Directory

I used the following code in a Visual Studio c# .Net web page for obtaining the email address of the user running the web page, since i wanted to notify them after completing a form on the page although that part of the code is not shown here:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.DirectoryServices;
//using System.DirectoryServices.Protocols;
//using System.DirectoryServices.ActiveDirectory;



namespace demo_project
{
    public partial class testauth : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                string userString = User.Identity.Name.ToString().ToUpper();
                DirectoryEntry de = new DirectoryEntry("LDAP://dc=domain,dc=com");
                DirectorySearcher ds = new DirectorySearcher(de);
                ds.PropertiesToLoad.Add("mail");
                ds.Filter = "(&(cn=" + userString + ")(objectCategory=person))";
                SearchResult sr = ds.FindOne();
                string email = sr.Properties["mail"][0].ToString();
                Label1.Text = email;
                Label1.Visible = true;
            }

            catch { }
        }
    }
}

Continue reading

Powershell Connect to SQL

To connect to a SQL database within a powershell script:

###CREATE CONNECTION STRING
$sqlconstring = "server=SERVER\INSTANCE;database=database;Integrated Security=sspi" 



###CREATE CONNECTION OBJECT THAT TAKES THE CONNECTION STRING
$sqlConnection = new-object System.Data.SqlClient.SqlConnection "$sqlconstring" 

###OPEN THE CONNECTION
$sqlConnection.Open() 

###CREATE A SQL COMMAND LINKED TO THE CONNECTION
$sqlCommand = $sqlConnection.CreateCommand() 

## SET COMMAND TEXT
$sqlcommand.commandtext = "Select * FROM table_name

###EXECUTE THE QUERY AND STORE THE RESULTS
$results = $sqlCommand.ExecuteReader()

Continue reading

Generate Patching Schedule

This is a bit of powershell I wrote to generate a CSV file containing all the servers in AD. I needed it to generate a monthly patching schedule, I used several extensionAttributes in AD to populate information related to patching i.e. day no., weekday, outage window, responsible team. This would email me at the start of the month after running in Orchestrator with that months patching schedule. It does mean the attributes need to be populated for each server and all new servers:

$schedule = powershell {

$patchingarray = @()
$serverarray =  @( get-adcomputer -filter {operatingsystem -like "*server*" -and name -notlike "*clu*"} -properties name, operatingsystem, extensionattribute12, extensionattribute13, extensionattribute14, extensionattribute15 | select name, operatingsystem, extensionattribute12, extensionattribute13, extensionattribute14, extensionattribute15)

foreach ($server in $serverarray){
# Create a new custom object to hold our result. 
$serverobject = new-object PSObject

# Add our data to $serverObject as attributes using the add-member command
$serverObject | add-member -membertype NoteProperty -name "ServerName" -Value $server.name 
$serverObject | add-member -membertype NoteProperty -name "OS" -Value $server.operatingsystem
$serverObject | add-member -membertype NoteProperty -name "Weekday" -Value $server.extensionattribute14 
$serverObject | add-member -membertype NoteProperty -name "Number" -Value $server.extensionattribute15
$serverObject | add-member -membertype NoteProperty -name "BusinessOwner" -Value $server.extensionattribute13
$serverObject | add-member -membertype NoteProperty -name "OutageWindow" -Value $server.extensionattribute12

# Save the current $serverObject by appending it to $patchingArray ( += means append a new element to ‘me’) 

$patchingarray += $serverObject 

} 
$filepath =  "\\server\share\patching\schedule\schedule.csv"

$patchingarray| Export-csv  $filepath

return $filepath

}

The output:
schedule

SCOM Fundamentals

Here’s some notes I made on SCOM when I was talking about it to some colleagues. I am sure there is plenty more I could have said but this might serve as a good starting point for someone trying to understand the concepts.

Classes: https://technet.microsoft.com/en-gb/library/hh457568.aspx

All classes have a base class (not parent) and lead back up the tree to object:
scomclasshierarchy
Continue reading

SCOM Monitor Processor Core Utilization

By default SCOM does not monitor individual processor core utilization. In order to monitor the individual core usage you have to create a collection rule (disabled by default) and an override for the server containing the cores to be monitored. I recently had to do this to monitor what happened after an application upgrade, the hope was the upgraded application would now be using multiple cores and not just one.

First thing to do in the Authoring tab of the console is to create a new windows performance collection rule:

proc_perf1
Continue reading

SCVMM Service Template Deployment Failing and SCVMM Guest Agent Not Installing

The reason for the double title of this post is that both are interlinked. The problem I had with a multiple VM Service Template failing to deploy was simply because the SCVM Guest Agent failed to deploy to one of the VM’s during deployment time.

Unfortunately SCVMM didn’t exactly help me out in why this had happened but I got there in the end.

The Service Template deployment would hang at the installing applications step, which was strange because my templates didn’t contain any applications, later I realised this was talking about the SCVMM Guest Agent:

vmmguestagentfail1

Continue reading

Orchestrator Runbooks Not Appearing In Service Manager

After creating a new folder in the Orchestrator Runbook Designer console and a couple of runbooks I found the connector from Service Manager to Orchestrator was not pulling the new runbooks through. The permissions on the new folder had inherited and the account running the connector had permissions.

I found the following SQL command to run against the Orchestrator database

TRUNCATE TABLE [Microsoft.SystemCenter.Orchestrator.Internal].AuthorizationCache

This refreshes the orchestrator authorization cache which presumably contained data created before my new runbook folder. After that running the connector again pulled through the new runbooks as expected.

Deploying an SCVMM Service Template Through Orchestrator

Templates in SCVMM provide a particularly useful way to deploy a multi component environment. The deployment can be automated through Orchestrator and then of course published through Service Manager to make deployment even smoother.

I created the following Orchestrator runbook to redeploy 2 VM’S that I had configured in a Service Template:

sco_scvm_template_1

Continue reading

SCOM All Agents Grey

The other week out of the blue all of my SCOM agents turned grey in the SCOM console. After a lot of searching and several calls with Microsoft we determined what the problem was.

It seems that the inability to authenticate one particular run as account on the agents would actually turn them grey as opposed to just logging an error/raising an alert.

The run as account in question was related to the System Center Advisor service which we had been looking at before, way before I should clarify.

So on a Health Service object you can run a task called “Show failed rules and Monitors for this Health Service” which I did on one of the grey agents which produced the following:

greyagent1

Continue reading

Search For All Files Owned By A User – Powershell

The following powershell script will look through a given folder structure and log all files with a specific owner:

$files = get-childitem "\\server\share" -file -recurse
$outputfile = "D:\powershell\owners\log.txt"

    foreach ($file in $files) {
  
         $filepath = "$filedir\$file"
    
         $fileowner = get-acl $filepath | select owner

         if ($fileowner.Owner.Contains("username")) {
              $owner = $fileowner.owner
              $outputline = "$filepath - $owner"
              $outputline | out-file -filepath $outputfile  -append
    
   }
       }

Connect to Office365 Exchange Online Through Powershell

To manage your O365 exchange organisation powershell has to connect to the online service but this is not the same as connecting to Azure AD through powershell where the connect-msolservice cmdlet is used.

To connect to exchange online:

cred = Get-Credential 
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell/ -Credential $cred -Authentication Basic –AllowRedirection 
Import-PSSession $Session

I needed to fetch the number of items and mailbox size of a few users which I used the get-mailboxstatistics command for:

get-mailboxstatistics -identity user@domain.com | fl itemcount, totalitemsize

This information is not available through the O365 portal, at least the number of items isn’t anyway.

The Exchange powershell cmdlets are downloaded automatically when making the connection they don’t need to be installed on the machine making the connection.

Delete Files Older Than x Days

# set folder path
$file_path = "\\server\folder\folder"
 
# set max age of files
$max_days = "-2"
 
# get the current date
$curr_date = Get-Date
 
# determine how far back we go based on current date
$del_date = $curr_date.AddDays($max_days)
 
# delete the files
Get-ChildItem $file_path -file -recurse | Where-Object { $_.LastWriteTime -lt $del_date } |  Remove-Item -Recurse

Notice the -file option on the Get-ChildItem cmdlet, that forces the script to look at files only. The -recurse flag causes it to go through sub folders.

The -Recurse flag on the Remove-Item cmdlet is required if automating this script otherwise it will wait for a confirmation prompt (i.e the scheduled task/runbook will just stay in a running state.