Pages

Saturday, December 14, 2013

Visual Studio 2013 community Launch - BDotNet user group

Today I had a very good experience going to the BDotnet Visual studio 2013 launch . I dont know what makes it special the passion of the people who present or the softwares that microsoft has developed. What ever may be the reason the BDotnet attendees are the gainers.

The day started at 8.30 A.M saturday at an early morning going early is always a trouble but  I was sure this effort would be worth. I reached the microsoft office and grabbed my chair.

One after another the presenters started their presentations and there was seeing with astonishment that these we had never thought off and the technology has changed so much.

The features of Visual Studio 2013 from agile profile management, kanban management, windows phone develeopment & game development ,Cloud computing all were awesome.
I never had thought that people will be coding from browsers and the windows app support for developing games was really interesting with me eagerly waiting to get a hands after Jan 15.

The fillers by Lohith and Vic were good too ;).

The day ended at 6.00 and lots of things to learn as usual. I have a request for the people who are not attending you guys are missing a lot of opportunities learning. Take some time for the event people charge heavily to give those kind of sessions here we are learning for free. Make use of it. Its just once in a month.

Visual studio 2013 rocks!!!!

Early looking for the next meet.

Monday, August 5, 2013

Is your software smart

There has been a lot of research on ontology and the semantic web has been in the news for quiet a while now.Its the next big thing in the future, making the web as intelligent as possible. I have been doing some research on this and I am not very sure if thats going to be true. Atleast not for all the products. Global gaints like Microsoft, Google etc can achieve a great success on intelligent tooling.

There are few projects where I worked and we developed million dollar tools with all the intelligent functionalities but simply wouldn't be successful. We did a lot of brain storming and found out that the clients were not willing to use it.The reason was that they didnt want to make their resources feel bad. The client said to use to make suggestions, not to validate or say that the analysis or the data their resources had collected was not just correct. Another important reason why intelligent tooling will not work is that the users wont understand the tool at all and any failures they just blame it on the software. "The software is not correct" thats what they say. Its true that people dont like to be said that they are wrong that too by a software.

In my view a software success  just doesn't depend on how intelligent you have made it but how much its accepted in the user community. Big software giants like Microsoft,Google can try these options but for companies which are not reputed will have tough time convincing their clients to try their software.

On the contrary intelligent tooling empowers software to be more powerful and cutting edge than it is now.

It will take still some time for the intelligent tools to come into lime light. As of now the developers have to be happy in building applications or products just to do some trivial tasks. Typically thats the mind set right now we have on softwares. It has to be still seen whether intelligent tooling will be success.As of  now I leave it for the time to tell.

Saturday, August 3, 2013

setting the TCP Port using WMI or using regsitry in C#


The TCP port is already enabled during the installation using the parameter TCPENABLED="1” in the SQLDemoConfig.ini file in silent Installation.Once the installation is complete we will change the TCP Port number using Windows Management Instrumentation (WMI). The WMI does not work on the Default SQL Instance it only works on the Instance we have installed. If we try it on the default instance we will get a “Alter() failed” error. One more reason why you may get “Alter() failed” is the Visual Studio is not run in administrator mode. Right click and “Run as administrator”.


The following references should be added to your Project/Solution.
 

1.    Microsoft.SqlServer.ConnectionInfo.dll

2.    Microsoft.SqlServer.Management.Sdk.Sfc.dll

3.    Microsoft.SqlServer.Smo.dll

4.    Microsoft.SqlServer.SmoExtended.dll

5.    Microsoft.SqlServer.SqlWmiManagement.dll


Use the Namespaces as below
 

using System.ServiceProcess;
using Microsoft.SqlServer.Server;
using Microsoft.SqlServer.Management.Smo.Wmi;
using System.Diagnostics;

 

The code to update the TCP Port number using WMI is as follows:-

  

ManagedComputer mg = new ManagedComputer();
 
//Get the service by service name
ServiceController service = new ServiceController("MSSQL$DEMOSQLEXP");
 
//Stop the service if its running
if (service.Status == ServiceControllerStatus.Running)
{
     service.Stop();
}
 
//Get the SQLEXPRESS instance
ServerInstance serverInstance = mg.ServerInstances["DEMOSQLEXP"];
ServerProtocolCollection prot = serverInstance.ServerProtocols;
ServerProtocol serverProtocol = serverInstance.ServerProtocols["Tcp"];
//Change the TCP port number to 1433 or desired port
serverProtocol.IPAddresses["IPALL"].IPAddressProperties["TcpPort"].Value = "1433";
 
//Change the TCP Dynamic port number to blank             serverProtocol.IPAddresses["IPALL"].IPAddressProperties["TcpDynamicPorts"].Value = String.Empty;
 
 
//Commit the changes
serverProtocol.Alter();
 
 
//Start the service which is already stopped
if (service.Status == ServiceControllerStatus.Stopped)
{
     service.Start();
}
 

 
It is important that we stop the service before making the changes and start the service once the change is done as the changes won’t take effect unless we restart the service. That is the reason we are using the ServiceController class.

There is one more way to enable the TCP Port and update TCP Port number is to write the Registry entry but that approach is not recommended.

The code to update the TCP port number is as follows:-

string keyNameTcp = @"SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQLServer\SuperSocketNetLib\Tcp";
                  
string keyNameTcpIP = @"SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQLServer\SuperSocketNetLib\Tcp\IPAll";
 
 
RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
                  
RegistryKey subkeyTcp = Registry.LocalMachine.OpenSubKey(keyNameTcp, true);
 
subkeyTcp.SetValue("Enabled", "00000002", RegistryValueKind.DWord);
subkeyTcp.Close();
 
RegistryKey subkeyTcpIP = Registry.LocalMachine.OpenSubKey(keyNameTcpIP, true);
subkeyTcpIP.SetValue("TcpPort", "1433");
subkeyTcpIP.Close();
 

 

 

Integrating the silent or unattended installation of SQL Server 2008 R2 in the C# code base


The code to integrate the silent installation in to the C# code base is very simple. We will start the process of setup and attach the arguments which are required. The code to do so is as follows:-

 
//Creating a process to do the silent installation
Process p = new Process();
 
//File names and File Path along with the process arguments
p.StartInfo.FileName = @"C:\DemoSetup\SQLEXPRWT_x86_ENU.exe";
p.StartInfo.Arguments = @"/q /ConfigurationFile=C:\DemoSetup\SQLDemoConfig.ini";
 
p.StartInfo.UseShellExecute = false;
p.Start();
 
//Waiting for the process to complete
p.WaitForExit();
 

 

Note:- To know the contents of the SQLDemoConfig.ini file please refer my earlier blogs.

This step p.WaitForExit(); is very important because we need to wait till the sql server installation is complete before setting the TCP port otherwise as there is no sql server and the service is not available an exception is thrown.

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.