Tuesday, August 21, 2018

Send email notification when free disk space is low

Powershell script that detects local disk drives with less free space than specified value and sends email notifications (I can't recall where I got the following script. It was probably written by a SQL Server admin).

# Get SMTP server info
$smtp=new-object Net.Mail.SmtpClient("myEmailServer.myDomain.com")

# Set thresholds in GB for C: drive and other drives
$driveCthreshold=10
$threshold=10

# Replace settings below with your e-mails
$emailFrom="serverToMinitor@myDomain.com"
$emailTo="myName@myDomain.com"

# -----------------------------------------------------------------------------

# Get server name
$hostname=Get-WMIObject Win32_ComputerSystem | Select-Object -ExpandProperty name

# Get all drives with free space less than a threshold, while excluding System Volumes
$Results = Get-WmiObject -Class Win32_Volume -Filter "SystemVolume='False' AND DriveType=3" | Where-Object {($_.FreeSpace/1GB –lt  $driveCthreshold –and $_.DriveLetter -eq "C:") –or ($_.FreeSpace/1GB –lt  $threshold –and $_.DriveLetter -ne "C:" )}

If ( ($Results | measure).Count -gt 0 ) 
{
    ForEach ($Result In $Results)
    {
        $drive = $Result.DriveLetter
        $space = $Result.FreeSpace
        $thresh = if($drive -eq 'C:'){$driveCthreshold} else {$threshold}

        # Send e-mail if the free space is less than threshold parameter 
        $smtp.Send(
           $emailFrom, 
           $emailTo, 
           # E-mail subject
           "Disk $drive on $hostname has less than $thresh GB of free space left ",
           # E-mail body 
           ("{0:N0}" -f [math]::truncate($space/1MB))+" MB"
        )
    }
}

Monday, August 20, 2018

ASP.NET MVC - Handle binary or byte arrays as in file download

In ASP.NET MVC, downloading a file over http has been simplified and is user-friendly. The following code streams byte arrays to browser in two ways. GetFile would prompt for user dialog for choice as to Open or Save. OpenFile would try to stream the byte array content and render it in browser directly (pdf, etc). The sample code assumes that db.Binaries entity already has properties, such as BinaryData, MimeType and FileName, etc.
[HttpGet]
pulic FileContentResult GetFile(int id)
{
  var binary = db.Binaries.Find(id);
  if (binary == null)
  {
    return null;
  }
  byte[] binaryData = binary.BinaryData;
  string mimeType = binary.MimeType;
  string fileName = binary.FileName;

  return File(binaryData, mimeType, fileName);
}

[HttpGet]
public ActionResult OpenFile(int id)
{
  var binary = db.Binaries.Find(id);
  if (binary == null)
  {
    return null;
  }
  var contentDisposition = new System.Net.Mime.ContentDisposition
  {
    FileName = binary.FileName, Inline = false
  };
  Response.AddHeader("Content-Disposition", "inline; filename=" + binary.FileName);
  
  return File(binary.BinaryData, binary.MimeType);
}

Thursday, August 16, 2018

Maximum Request Length Exceeded - ASP.NET

When uploading or downloading a large amount of content, ASP.NET may need some request length adjustments in the web.config file. Example below would allow a request to continue for maximum of 3600 seconds (1 hour) and 1 GB of content.

<configuration>
  ...
  <system.web>
    <httpRuntime targetFramework="4.5" executionTimeout="3600" maxRequestLength="1048576" />
  </system.web>
  ...
  <system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="1073741824" /> <!-- 1 GB in bytes -->
      </requestFiltering>
    </security>
  </system.webServer>
  ...
</configuration>


Tuesday, August 7, 2018

SQL Server Database and Log File Details

Quick way to retrieve a database and its log file size, etc...

/*-- Get all databases' mdf and ldf info, including logical names --*/
SELECT * FROM SYS.MASTER_FILES

/*-- Get mdf info (more detail) -- */
SELECT * FROM SYS.DATABASES

/*-- Get mdf info (less detail)  --*/
SELECT * FROM SYS.SYSDATABASES

/*-- Get database info -- */
EXEC sp_helpdb

/*-- Get database info (mdf and ldf), including logical names --*/
EXEC sp_helpdb @dbname = N'Northwind'


Tuesday, July 31, 2018

Get "exec sp_who2" into a table

Running sp_who2 will quickly display all connections to a SQL Server instance. Below is an enhancement to sp_who2 that allows database-specific connections.


DECLARE @DB_NAME varchar(1000)
SELECT @DB_NAME = 'Northwind_DB'

DECLARE @AllConnections TABLE(
    SPID INT,
    Status VARCHAR(MAX),
    LOGIN VARCHAR(MAX),
    HostName VARCHAR(MAX),
    BlkBy VARCHAR(MAX),
    DBName VARCHAR(MAX),
    Command VARCHAR(MAX),
    CPUTime INT,
    DiskIO INT,
    LastBatch VARCHAR(MAX),
    ProgramName VARCHAR(MAX), 
    SPID_1 INT,
    REQUESTID INT
)

INSERT INTO @AllConnections EXEC sp_who2
SELECT * FROM @AllConnections WHERE DBName = @DB_Name
ORDER BY HostName


ASP.NET MVC Scaffolding Template Files (T4)

The following is where you can find the T4 template files used by ASP.NET MVC Scaffolding:

Visual Studio 2015:
C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web\Mvc\Scaffolding\Templates\

Visual Studio 2017:
C:\Program Files\dotnet\sdk\NuGetFallbackFolder\microsoft.visualstudio.web.codegenerators.mvc\


Friday, July 27, 2018

Database Drop takes a long time when deleting backup history option is selected in SQL Server

Here's a workaround to speed up database drop. When there are a long history of backup in MSDB database, dropping a database with "Delete backup history" option could take a while.

Update statistics on MSDB tables and create an index for backupset table for [database_name] column. 

/* Update statistics in [msdb] database */
   
USE msdb; 
GO
UPDATE STATISTICS backupfile; 
GO
UPDATE STATISTICS backupmediafamily; 
GO
UPDATE STATISTICS backupmediaset; 
GO
UPDATE STATISTICS backupset; 
GO
UPDATE STATISTICS restorefile; 
GO
UPDATE STATISTICS restorefilegroup; 
GO
UPDATE STATISTICS restorehistory; 
GO


/* Create an index on [backupset] table in [msdb] database for [database_name] column */

Create index IX_backupset_database_name on backupset(database_name); 
GO