Pages

Tuesday, July 30, 2013

Check if SQL Authentication is enabled in SQL Server 2008 programmatically

Check if SQL Authentication is enabled in SQL Server 2008 programmatically
There are different ways to check if sql authentication is enabled. We can use sql queries or else we can use C# code. We are going to looking into all the possibilities. We can choose the best possible scenario which fits our requirement.
1)      Using SQL Queries

a.        Using  loginconfig

EXEC master.sys.xp_loginconfig 'login mode'


b.      Using  SERVERPROPERTY

SELECT CASE SERVERPROPERTY('IsIntegratedSecurityOnly')  WHEN 1 THEN 'Windows Authentication' WHEN 0 THEN 'Mixed Mode'  END as [SQL Authentication Mode]



c.       Using  xp_instance_regread registry read


DECLARE @SQLAuthenticationMode INT
EXEC master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'LoginMode', @AuthenticationMode OUTPUT
SELECT CASE @AuthenticationMode
WHEN 1 THEN 'Windows Authentication'
WHEN 2 THEN 'Windows and SQL Server Authentication'
ELSE 'Unknown' END as [Authentication Mode]



2)      Using C# code for checking the registry entry.
The code reads a registry entry of SQL Server 2008 and the key “LoginMode” has a value 2 it’s a mixed mode and if it has a value 1 then it has Windows Authentication. In order to read a registry entry we need to reference the Microsoft.Win32.dll;


using System;
using System.Collections.Generic;
using System.Text;
using System.Security;
using System.Security.AccessControl;
using Microsoft.Win32;


namespace ReadWriteRegistryEntry
{
    class Program
    {
        static void Main(string[] args)
        {
          //  Code to Read the registry entry to check the authentication mode of Sql Server
                        try
                        {
                            string keyName = @"SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQLServer";
                            RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
                            RegistryKey subkey = baseKey.OpenSubKey(keyName);

                            if (subkey == null)
                            {
                                Console.WriteLine("No Key found");
                            }
                            else
                            {
                                try
                                {
                                    if (subkey.GetValue("LoginMode").ToString() == "2")
                                    {
                                        Console.WriteLine("Mixed Mode");
                                    }
                                    else if (subkey.GetValue("LoginMode").ToString() == "1")
                                    {
                                        Console.WriteLine("Windows Authentication");
                                    }

                                }
                                catch (Exception ex)
                                {
                                    Console.WriteLine(ex.Message);
                                }
                            }

                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e.Message);
                        }
                        Console.Read();

                    }

    }
}




Monday, July 29, 2013

Creating a login user in a SQL Server 2008 database and adding permissions to the dbo.schema in SQL Server 2008.

Creating a login user in a SQL Server 2008 database and adding permissions to the dbo.schema in SQL Server 2008.


USE [TestDB]
GO

 
CREATE LOGIN TestUser1
    WITH PASSWORD    = N'TestPassword1#',
    CHECK_POLICY     = OFF,
    CHECK_EXPIRATION = OFF;
   

CREATE USER  TestUser1 FOR LOGIN  TestUser1;


-- add user to db_owner
Exec Sys.sp_addrolemember 'db_owner', 'TestUser1';

-- add user to db_accessadmin
Exec Sys.sp_addrolemember 'db_accessadmin', 'TestUser1';

-- add user to db_datareader
Exec Sys.sp_addrolemember 'db_datareader', 'TestUser1';

-- add user to db_datawriter
Exec Sys.sp_addrolemember 'db_datawriter', 'TestUser1';

-- add user to db_ddladmin
Exec Sys.sp_addrolemember 'db_ddladmin', 'TestUser1';



GRANT INSERT ON SCHEMA :: dbo TO TestUser1;

GRANT Alter ON SCHEMA :: dbo TO TestUser1;

GRANT DELETE ON SCHEMA :: dbo TO TestUser1;

GRANT SELECT ON SCHEMA :: dbo TO TestUser1;

GRANT UPDATE ON SCHEMA :: dbo TO TestUser1;

GRANT INSERT ON SCHEMA :: dbo TO TestUser1;







Generating a proxy using svcutil.exe in WCF

Generating a proxy using svcutil.exe in WCF
Step 1:- When a service is run we can see all the .svc files available in that service.  We will get a command as follows    
Step 2:- Right Click on the Visual Studio Command Prompt (2010) available under the Visual Studio Tools and run it as administrator.
Step 3:- In the command prompt copy paste the
svcutil.exe http://localhost:25016/Service1.svc?wsdl and click on enter it will generate the proxy as well as the config file. The output paths of these files are also mentioned.

C:\Windows\system32>svcutil.exe http://localhost:25016/Service1.svc?wsdl
Microsoft (R) Service Model Metadata Tool
[Microsoft (R) Windows (R) Communication Foundation, Version 4.0.30319.1]
Copyright (c) Microsoft Corporation.  All rights reserved.

Attempting to download metadata from 'http://localhost:25016/Service1.svc?wsdl'
using WS-Metadata Exchange or DISCO.
Generating files...
C:\Windows\system32\Service1.cs
C:\Windows\system32\output.config

C:\Windows\system32>


If we open up the Service1.cs we can see the Service Contracts, Operation Contracts and the DataContracts that We have created in the WCF Service. The contents of the proxy file i.e. Service1.cs is as follows:-
Service1.cs
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.17929
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace DemoWcfService
{
    using System.Runtime.Serialization;
   
   
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")]
    [System.Runtime.Serialization.DataContractAttribute(Name="CompositeType", Namespace="http://schemas.datacontract.org/2004/07/DemoWcfService")]
    public partial class CompositeType : object, System.Runtime.Serialization.IExtensibleDataObject
    {
       
        private System.Runtime.Serialization.ExtensionDataObject extensionDataField;
       
        private bool BoolValueField;
       
        private string StringValueField;
       
        public System.Runtime.Serialization.ExtensionDataObject ExtensionData
        {
            get
            {
                return this.extensionDataField;
            }
            set
            {
                this.extensionDataField = value;
            }
        }
       
        [System.Runtime.Serialization.DataMemberAttribute()]
        public bool BoolValue
        {
            get
            {
                return this.BoolValueField;
            }
            set
            {
                this.BoolValueField = value;
            }
        }
       
        [System.Runtime.Serialization.DataMemberAttribute()]
        public string StringValue
        {
            get
            {
                return this.StringValueField;
            }
            set
            {
                this.StringValueField = value;
            }
        }
    }
}


[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="IService1")]
public interface IService1
{
   
    [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IService1/GetData", ReplyAction="http://tempuri.org/IService1/GetDataResponse")]
    string GetData(int value);
   
    [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IService1/GetDataUsingDataContract", ReplyAction="http://tempuri.org/IService1/GetDataUsingDataContractResponse")]
    DemoWcfService.CompositeType GetDataUsingDataContract(DemoWcfService.CompositeType composite);
}

[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface IService1Channel : IService1, System.ServiceModel.IClientChannel
{
}

[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class Service1Client : System.ServiceModel.ClientBase<IService1>, IService1
{
   
    public Service1Client()
    {
    }
   
    public Service1Client(string endpointConfigurationName) :
            base(endpointConfigurationName)
    {
    }
   
    public Service1Client(string endpointConfigurationName, string remoteAddress) :
            base(endpointConfigurationName, remoteAddress)
    {
    }
   
    public Service1Client(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
            base(endpointConfigurationName, remoteAddress)
    {
    }
   
    public Service1Client(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
            base(binding, remoteAddress)
    {
    }
   
    public string GetData(int value)
    {
        return base.Channel.GetData(value);
    }
   
    public DemoWcfService.CompositeType GetDataUsingDataContract(DemoWcfService.CompositeType composite)
    {
        return base.Channel.GetDataUsingDataContract(composite);
    }
}




The End Points can be found in the output.config file .The endpoint  and the binding informantion which needs to be added in the client can be found in the config file. The file contents will be similar to as follows:-
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.serviceModel>
        <bindings>
            <basicHttpBinding>
                <binding name="BasicHttpBinding_IService1" />
            </basicHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:25016/Service1.svc" binding="basicHttpBinding"
                bindingConfiguration="BasicHttpBinding_IService1" contract="IService1"
                name="BasicHttpBinding_IService1" />
        </client>
    </system.serviceModel>
</configuration>



In a case when you might have added a new operation contract or need to verify if that operation contract is showing in the service then click on the svcutil.exe http://localhost:25016/Service1.svc?wsdl.
The new operation contract should be available in the wsdl otherwise check in the code if there are any tags missing or some other issue. Similarly we can do the same for datacontracts , members of a datacontract.