August 20, 2015

Call inline C# from PowerShell


Windows PowerShell is a shell for task automation and configuration management. The shell is based on the .NET framework and it includes a command-line shell and a scripting language. Features include built-in commands (cmdlets) to manage computers in your network. Cmdlets perform common system administration tasks such as managing the registry; managing event logs; controlling services and processes; and using Windows Management Instrumentation.

Apart from shell's cmdlets, there is also flexibility to use C# code, because the shell is based on .Net framework. In this post I demonstrate a way to call inline C# code from the PowerShell script. Following is the script to do so.


$Source = @"
namespace TestNamespace
{
    public static class MyClass
    {
        public static string GetMessage()
        {
            return "Text from C#";
        }
      
        public static int Add(int a, int b)
        {
            return a + b;
        }
    }
}
"@

Add-Type -TypeDefinition $Source -Language CSharp

[TestNamespace.MyClass]::GetMessage()

[TestNamespace.MyClass]::Add(3, 5)

Let review this script:
  • The first statement here you see that we put our C# code in a variable named $source (in PowerShell we define variable by placing $ sign with it).
  • Next we call PowerShell cmdlet Add-Type, here we define -TypeDefinition is our C# class code, and telling the shell that this script is actually C# code defined by the argument -Language CSharp
    These two steps are required, lets say, to register our C# code, so PowerShell can understand it.
    Now its the time to actually call our code and that is pretty straight forward.
  • [TestNamespace.MyClass]::GetMessage() will call our Method which only returns a string.
  • [TestNamespace.MyClass]::Add(3, 5) will accept two integer parameters and return the output as integer.
So here we get C# action in PowerShell.

August 18, 2015

5(Access is denied.)' while attempting 'RestoreContainer'

While restoring SQL backup file from one machine to another, I got this error message:

System.Data.SqlClient.SqlError: The operating system returned the error '5(Access is denied.)' while attempting 'RestoreContainer::ValidateTargetForCreation' on 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.x\MSSQL\DATA\x.ldf'. (Microsoft.SqlServer.Smo)

Here is what solution I found for this problem.
Carefully check the path showing in error, while backup file is created at first machine it stores the file path of that machine. Now when you are restoring on new machine if the path is same (i.e. server name, and also version etc.) then you get the file restore successfully otherwise you will get this error. So simply change the path according to new machine in "Restore As" option, and you will get fix to this error.

August 28, 2012

SQL Server Indexes - Definition

One of the most important technique to high performance queries in a SQL Server database is the index. Like we have index in books for fast searching, indexes speed up the querying process by providing fast access to rows in the data tables.

Indexes are of two types, clustered and nonclustered indexes.

Clustered Index

A clustered index is an index that stores the actual data. It is a special type of index that reorders the way records in the table are physically stored. Therefore table can have only one clustered index. The leaf nodes of a clustered index contain the data pages. A clustered index stores the actual data rows at the leaf level of the index. An important characteristic of the clustered index is that the indexed values are sorted in either ascending or descending order. As a result, there can be only one clustered index on a table or view. In addition, data in a table is sorted only if a clustered index has been defined on a table. A table that has a clustered index is referred to as a clustered table. A table that has no clustered index is referred to as a heap.

Non-Clustered Index

A non-clustered index is just a pointer to the data. It is a special type of index in which the logical order of the index does not match the physical stored order of the rows on disk. The leaf nodes of a nonclustered index does not consist of the data pages. Instead, the leaf nodes contain index rows. Unlike a clustered indexed, the leaf nodes of a nonclustered index contain only the values from the indexed columns and data row pointers , rather than contain the data rows themselves. This means that the query engine must take an additional step in order to locate the actual data.

A row pointer depends on whether it points to a clustered table or to a heap. If referencing a clustered table, the row locator points to the clustered index, using the value from the clustered index to navigate to the correct data row. If referencing a heap, the row locator points to the actual data row.

July 27, 2012

VS 2010, shortcut keys to Enable/Disable All Breakpoints


In Visual Studio, you can create or delete a single breakpoint by hitting F9, and can delete all breakpoints by Ctrl+Shift+F9 shortcut. It does not provide shortcut keys to disable or enable all breakpoints, but you can define that by yourself.
  • Go to Tools > Options popup.
  • Enter "DisableAllBreakpoints" in the textbox for Show commands containing:.
  • I am using Global option from User new shortcut in: combobox.
  • Set focus on Press shortcut keys textbox and hit your shortcut keys you want to set. (e.g. I am using Alt+1)
  • Press Assign button
  • Now press OK and use your new shortcut keys.(Make sure your newly created shortcut key is selected in Shortcuts for selected command) combobox while hitting OK button.
vs2010-enable-breakpoints-shortcut Similary you can set shortcut key for EnableAllBreakPoints or any other command.

June 27, 2012

Error: 26 - Error Locating Server/Instance Specified

I have installed SQL Server and Management Studio on new machine and facing issues while connecting to SQL Server through remote machines on my local area network. After thorough searching and experimenting I have got resolved the error. Following are the steps(not necessary all) to resolve the issue.

SQL Server should be running

Go to All Programs > Microsoft SQL Server 2005 > Configuration Tools > SQL Server Configuration Manager. Select node SQL Server 2005 Services, under SQL Server Configuration Manager parent node. SQL Server's state should be Running. SQL Server Browser service should also be Running (you can Start/Stop by right click on service name)

Enable TCP/IP in SQL Server Configuration

Go to All Programs > Microsoft SQL Server 2005 > Configuration Tools > SQL Server Configuration Manager. Select node Protocols for SQLServer(your server's instance name) , under SQL Server 2005 Network Configuration.
TCP/IP's state should be Enabled. (can be Enabled/Disabled by right click on Protocol Name)

App Exception for SQL Server TCP Port in Windows Firewall

Go to Conctrol Panel > Windows Firewall > Exceptions (tab). Click button Add Port, enter name and port number 1433. Make sure your entered name is displaying in Programs and Services section, and should be checked while pressing OK button on the tab.

App Exception for sqlbrowser.exe in Windows Firewall

In Firewall window > Exceptions tab, click on Add Program. Locate the sqlbrowser.exe by Browse button. Click OK. At my system, it is located at C:\Program Files\Microsoft SQL Server\90\Shared\sqlbrowser.exe.

App Exception for sqlservr.exe in Windows Firewall

Similarly add sqlservr.exe in Firewall Exceptions. At my system, it is located at C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\sqlservr.exe.

Enable Remote Connection

Right click on SQL Server main node in Management Studio, and go to Properties. Select Connections page from Select a Page section. Allow remote connections to this server should be checked.

References