Exit single-user mode

How do I exit out of single-user mode? I don't have any user using this database. I was trying to restore a database from a different instance into a new database that I just created. Then I see it says it's in Single User mode after the restore failed.

The solution is this:

-- Start in master
USE MASTER;

-- Add users
ALTER DATABASE [my_db] SET MULTI_USER
GO

 

SQL Server principal "dbo" does not exist

You get this message when trying to create a SQL Database diagram

Cannot execute as the database principal because the principal "dbo" 
does not exist, this type of principal cannot be impersonated,
or you do not have permission.

After restoring a database from another server you see this

Solution

use [YourDatabaseName] EXEC sp_changedbowner 'sa'


503.0 – Server has been Shutdown

When developing an ASP.NET Core Web application, you MUST NOT call the CreateBuilder more than once! This should only be in the Program.cs file only. Otherwise, you will get this HTTP Error 503.0 - Server has been shutdown. This error might now show up right away but after a few clicks around then app where CreateBuilder is called, will result in this error.

The main issue with this error is calling the CreateBuilder more than once in the application. I used this to get to the Configuration file. Avoid this by using the IConfiguration interface on the Controller. You can also use a static class as well, for the other classes that can’t really inject an interface into. Also the static method is good for JSON calls! See below.

The problem is explained here: ASP.NET Core: 503 Server has been shutdown

This is how to use the Configuration: Configuration in ASP.NET Core | Microsoft Learn

Static Method

public static class AppExtensions
{
public static IConfiguration Configuration;
}

Then in Program.cs add the following line.
AppExtensions.Configuration = builder.Configuration;

Controller Method

For the Controller

public VersionsController(ModelDbContext context, IConfiguration configuration)
{
// Need to ensure that the connection is changed/set in the Constructor!
var id = AppExtensions.Connection;
var connectionString = configuration.GetConnectionString(id);
}

I discovered this method in this Stack Overflow post: c# - How do I access Configuration in any class in ASP.NET Core? - Stack Overflow

 

UNC path is not supported error

I recently had an issue running a batch file using a UNC path and discovered that UNC paths are not always supported. This failed in the following line.

ForFiles /p "\\Server\folder\username\SQLBackups" /s /d -13 /c "cmd /c del /q @file"

The solution was to use PUSHD and POPD as shown here

:: Create a temporary drive letter mapped to your UNC root location
:: and effectively CD to that location
pushd \\Server\folder\username

:: Do your work
ForFiles /p "SQLBackups" /s /d -13 /c "cmd /c del /q @file"

:: Remove the temporary drive letter and return to your original location
popd

Explained here: windows - How to run batch file from network share without "UNC path are not supported" message? - Stack Overflow

Upload File to SharePoint

You can upload documents to SharePoint libraries using the Object Model or SharePoint Webservices.

Upload using Object Model:

String fileToUpload = @"C:\YourFile.txt";
String sharePointSite = "http://yoursite.com/sites/Research/";
String documentLibraryName = "Shared Documents";

using (SPSite oSite = new SPSite(sharePointSite))
{
    using (SPWeb oWeb = oSite.OpenWeb())
    {
        if (!System.IO.File.Exists(fileToUpload))
            throw new FileNotFoundException("File not found.", fileToUpload);                    

        SPFolder myLibrary = oWeb.Folders[documentLibraryName];

        // Prepare to upload
        Boolean replaceExistingFiles = true;
        String fileName = System.IO.Path.GetFileName(fileToUpload);
        FileStream fileStream = File.OpenRead(fileToUpload);

        // Upload document
        SPFile spfile = myLibrary.Files.Add(fileName, fileStream, replaceExistingFiles);

        // Commit 
        myLibrary.Update();
    }
}

 

Refer to Form and Subform properties and controls

This resource is priceless! © 1998-2010, Dev Ashish & Arvin Meyer, All rights reserved. - Thank You! I have pasted the matrix here incase this link ever disappears.

Forms: Refer to Form and Subform properties and controls

For these examples:
Mainform is the name of the top level form
Subform1 is the name of the subform CONTROL on mainform
Subform2 is the name of the subform CONTROL on the 1st subform.

If you are on  
  Main form Sub 1
To refer to a form property, like RecordSource    
On Mainform Me.RecordSource Me.Parent.RecordSource
On Sub 1 Me!Subform1.Form.RecordSource Me.RecordSource
On Sub 2 Me!Subform1.Form!Subform2.Form.RecordSource Me!Subform2.Form.RecordSource
To refer to a control    
On Mainform Me!ControlName Me.Parent!ControlName
On Sub 1 Me!Subform1.Form!ControlName Me!ControlName
On Sub 2 Me!Subform1.Form!Subform2.Form!ControlName Me!Subform2.Form!ControlName
To refer to a control property, like Enabled    
On Mainform Me!ControlName.Enabled Me.Parent!ControlName.Enabled
On Sub 1 Me!Subform1.Form!ControlName.Enabled Me!ControlName.Enabled
On Sub 2 Me!Subform1.Form!Subform2.Form!ControlName.Enabled Me!Subform2.Form!ControlName.Enabled
To refer to a subform control property, like SourceObject    
On Mainform N/A N/A
On Sub 1 Me!Subform1.SourceObject N/A
On Sub 2 Me!Subform1.Form!Subform2.SourceObject Me!Subform2.SourceObject
     
  If you are on  
  Sub2 Not in these forms
To refer to a form property, like RecordSource    
On Mainform Me.Parent.Parent.RecordSource Forms!Mainform.RecordSource
On Sub 1 Me.Parent.RecordSource Forms!Mainform!Subform1.Form.RecordSource
On Sub 2 Me.RecordSource Forms!Mainform!Subform1.Form!Subform2.Form.RecordSource
To refer to a control    
On Mainform Me.Parent.Parent!ControlName Forms!Mainform!ControlName
On Sub 1 Me.Parent!ControlName Forms!Mainform!Subform1.Form!ControlName
On Sub 2 Me!ControlName Forms!Mainform!Subform1.Form!Subform2.Form!ControlName
To refer to a control property, like Enabled    
On Mainform Me.Parent.Parent!ControlName.Enabled Forms!Mainform!ControlName.Enabled
On Sub 1 Me.Parent!ControlName.Enabled Forms!Mainform!Subform1.Form!ControlName.Enabled
On Sub 2 Me!ControlName.Enabled Forms!Mainform!Subform1.Form!Subform2.Form!ControlName.Enabled
To refer to a subform control property, like SourceObject    
On Mainform N/A N/A
On Sub 1 N/A Forms!Mainform!Subform1.SourceObject
On Sub 2 N/A Forms!Mainform!Subform1.Form!Subform2.SourceObject

Delete Files Older Than X Days with ForFiles Command

Delete Files Older Than X Days with ForFiles Command

You can quickly delete files older than X days with ForFiles Command. Follow the given steps below to use CMD delete files older than x days:

Step 1. Left-click the Windows main menu and search for Command Prompt. Right-click the result and select the "Run as administrator" option.

Step 2. Type in ForFiles /p "C:\path\to\folder" /s /d -X /c "cmd /c del /q @file" to delete files on Windows that haven't been modified in the last X days and press Enter. In the command, change "C:\path\to\folder" specifying the path to the folder you want to delete files and change /d -X to select files with a last modified date.

ForFiles command breakdown

/p - indicates the pathname to start searching.

/s - instructs ForFiles to search inside subdirectories.

/d -specifies the last modified date for a file.

/c - instructs ForFiles to execute the command (must be wrapped in double quotes). The default is "cmd /c del @file".

/q -allows deleting folders without requiring confirmation.

OneDrive File State Change

It is possible to have 3 states when it comes to OneDrive files.

  • Always available
  • Locally available
  • Online-only

See this link for full details: Set Files On-Demand states in Windows - SharePoint in Microsoft 365 | Microsoft Learn

I'm backing up some files that would fill up the C drive so each time I backup a file I unpin it. My OneDrive can hold 5TB so now I can keep lots more data when unpinned.

This is an example of how to unpin locally and save space. This is excellent in batch files for multiple files/folders.

attrib +u "C:\Users\[username]\OneDrive - [Company Name]\[FolderName]\*.*"

This can also be accomplished by using the right click menu in Windows Explorer.

SQL Server Max ID and Row Count

This is how to get the Max ID and the Row Count for all tables in a SQL Database. It's a good way to check that things look OK!

The MaxValues should not be wildly, more than the row count unless you know that rows have been deleted constantly, like the use of a temp table for example.

SELECT DISTINCT 
	   SchemaName = SCHEMA_NAME(CAST(OBJECTPROPERTYEX(sc.object_id,'SchemaId')AS INT))
      ,ObjectName = OBJECT_NAME(sc.object_id)
      ,ColumnName = sc.name
      ,DataType = TYPE_NAME (sc.system_type_id)
      ,MaxValue = sc.last_value
	  ,NoOfRows = p.rows
  FROM sys.identity_columns sc
  INNER JOIN 
    sys.partitions p ON sc.object_id = p.OBJECT_ID 
 WHERE OBJECTPROPERTYEX(sc.object_id,'IsTable') = 1
   AND SCHEMA_NAME(CAST(OBJECTPROPERTYEX(sc.object_id,'SchemaId')AS INT)) LIKE 'dbo'
 ORDER BY MaxValue DESC, ObjectName

 

The remote certificate is invalid according to the validation procedure.

I was adding e-mail code to my ASP.NET Core MVC web app and got this error when trying to send an e-mail using my O365 account.

The remote certificate is invalid according to the validation procedure.

The solution was to add the following routine.

private bool RemoteServerCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    //Console.WriteLine(certificate);
    return true;
}

Then call it from the e-mail code like this.

//Added this line here
System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback);
SmtpClient smtp = new SmtpClient();

So altogether it looks like this.

private void sendAMail(String toAddress, String messageBody)
        {
            String msg = "Sending mail to : " + toAddress;

            MailMessage mail = new MailMessage();
            mail.To.Add(toAddress);
            mail.From = new MailAddress("from@mydomain.com");
            mail.Subject = "Subject: Test Mail";
            mail.Body = messageBody;
            mail.IsBodyHtml = true;            

            //Added this line here
            System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback);
            SmtpClient smtp = new SmtpClient();

            smtp.Host = "myhostname.com";            
            smtp.Credentials = new System.Net.NetworkCredential("sender@sample.com", "");
            smtp.EnableSsl = true;
            smtp.Port = 587;            
            smtp.Send(mail);            
        }


private bool RemoteServerCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
{
    //Console.WriteLine(certificate);
    return true;
}

I found the solution here: c# - "The remote certificate is invalid according to the validation procedure." using Gmail SMTP server - Stack Overflow