Quantcast
Channel: Karthick P.K – SQLServerScribbles.COM
Viewing all 89 articles
Browse latest View live

Trace waits in SQLServer (SQLTRACE_BUFFER_FLUSH,TRACEWRITE,SQLTRACE_WAIT_ENTRIES,SQLTRACE_LOCK)

$
0
0

When you run Profiler trace from client systems or on server with large number of events you will see below wait types.

SQLTRACE_WAIT_ENTRIES
SQLTRACE_LOCK
SQLTRACE_BUFFER_FLUSH
TRACEWRITE

There is no way to completely avoid this wait type without stopping all the traces. We can reduce this waitypes by configuring server side trace instead of client side trace.

select * from sys.traces will give you information about all the traces. ( Status column 0 stopped and 1 active)

For the traces collected using profiler you will find a NULL Path. Profiler traces can cause large number of above waittypes.

Thread which raises the trace event is responsible to Get buffers to write event and write event. So collecting the trace on network share or on slow disk or using profiler can slow down the trace write and make the threads wait, sometimes we may also end with dead locked schedulers.

So ideally you have to avoid running profiler when you see below waits and use sp_trace_create if you like to capture the trace and pass the local path for tracefile parameter.


Filed under: MSSQLWIKI, SQLServer engine, SQLServer performance, SQLServer tools Tagged: Client side trace, SQLTRACE_BUFFER_FLUSH, SQLTRACE_LOCK, SQLTRACE_WAIT_ENTRIES, TRACEWRITE

SQL Server assert in Location: purecall.cpp:51

$
0
0

SQL Server assert in purecall.cpp:51

BEGIN STACK DUMP:

spid 231

Location: purecall.cpp:51

Expression: !”purecall”

SPID: 200

Process ID: 5125

Description: Pure virtual function call

Server Error: 17065, Severity: 16, State: 1.

Server SQL Server Assertion: File: <purecall.cpp>, line = 51 Failed Assertion = ‘!”purecall”‘ Pure virtual function call. This error may be timing-related. If the error persists after rerunning the statement, use DBCC CHECKDB to check the database for structural integrity, or restart the server to ensure in-memory data structures are not corrupted.

Possible causes for above assert are

1. Antivirus softwares which detours in sqlserver address space can inject their instruction in sqlserver modules and can cause this Ex. Sophos etc..

Run select * from sys.dm_os_loaded_modules and check if there are DLL’d loaded from Antivirus (Company column will have the AV company name). If you see any antivrus exclude SQLServer from them.

(or)

Run lm command in the dump and see if there are any Antivirus DLL’s loaded in sqlserver process memory.

2. If you don’t see any Antivirus dll then run windows memory diagnostic tool and check if there are any memory problems on your system( %windir%\system32\MdSched.exe).

3. If there is no antivirus or memory errors follow the steps in http://mssqlwiki.com/2012/10/16/sql-server-exception_access_violation-and-sql-server-assertion/


Filed under: SQLServer engine, SQLServer memory Tagged: Description: Pure virtual function call, line = 51 Failed Assertion = '!"purecall"', purecall.cpp:51, Server SQL Server Assertion: File:

Builtin\Administrators cannot login in to SQL Server

$
0
0

 

If you add a windows login to administrators group and even though administrators group is part of SQL Server login you may not be able to login in to SQL Server using the windows login.

Similarly

1. You remove a windows login from a windows group and assume windows group is part of SQL server login had deny on certain objects in database.

2. Now you add the windows login explicitly to SQL Server logins and grant permissions on objects which had deny for windows group. Still the login will not be able to access the objects which have deny for the group and may raise 229  similar to one below

{The SELECT permission was denied on the object ”, database mssqlsystemresource’, schema ‘sys’. (Microsoft SQL Server, Error: 229) }

 

This can happen when SQL is creating the logintoken from LSACache.  (LSA Cache is not refreshed after the Admin2 is added to Administrators group)

1. Disable LSACache on the machine. Steps are included in http://support.microsoft.com/kb/946358.
2. Restart the machine.
3. Connect using the problematic login and try again.


Filed under: SQLServer security Tagged: (Microsoft SQL Server, Error: 229), The permission was denied on the object database

SQLServer LooksAlive and IsAlive Check

$
0
0

The resource DLL for the SQL Server service uses two functions that are used by MS Cluster service to check for availability of the SQL Server resource.

A simple check LooksAlive and more rigorous check called IsAlive

LooksAlive check: Cluster service calls looksAlive function every 5 seconds and LookAlive function Queries the service status by using the Windows NT Service Control Manager. When the LooksAlive test fails ISAlive test is called immediately.

ISalive Check: A more rigorous IsAlive function is called every 60 second and monitors the health of the SQL Server by opening up a connection to SQL Server and issuing “select @@servername” query over the connection. If the checks fail the online Thread reports this failure to the Cluster Service.

For example Assume SQL Server resource is initially in the offline state. Cluster service calls the routine in SQL Server resource DLL to bring the resource to an Online state. First the resource state is set as OnlinePending and then initiates the process of starting up the SQL Server resource. It starts the SQL Server, opens a connection to SQL Server and issues the “select @@servername” query, if this succeeds the resource is put in the Online state. If for some reason SQL Server is not able to start or the connection/query fails and SQL Server is not able to come Online within PendingTimeout, the cluster service tries to restart (or failover) the resource. If after repeated attempt SQL Server cannot be brought online, it is put in the failed state. If the SQLServer Resource DLL encounters an unrecoverable failure like failing to open cluster registry key etc. then resource DLL will put the SQL Server resource in Failed state. Once the resource is put in Failed state Cluster service will not attempt to restart/failover the resource and user intervention is required to diagnose and correct the issue.

By default, LooksAlive is fired every 5 seconds and IsAlive is fired every 60 seconds. The LooksAlive and IsAlive polling intervals can be changed in Cluster Administrator or failover cluster manager from the Advanced tab for the SQL Server resource or using the cluster.exe command prompt utility.


Filed under: SQLServer Cluster Tagged: SQLServer cluster, SQLServer IsAlive Check, SQLServer LooksAlive check

Removing database mirroring

$
0
0

When you try to recover and open mirrored database using dbcc dbrecover([DBNAME])

You would get below error

{

Msg 7930, Level 20, State 1, Line 1

Mirroring must be removed from the database for this DBCC command.

}

When you try to recover and open the database using “restore database [DBNAME] with recovery”

{

Msg 3104, Level 16, State 1, Line 1

RESTORE cannot operate on database dbname because it is configured for database mirroring. Use ALTER DATABASE to remove mirroring if you intend to restore the database.

Msg 3013, Level 16, State 1, Line 1

RESTORE DATABASE is terminating abnormally.

}

When you try to drop the database

Msg 3743, Level 16, State 1, Line 1

The database ‘dbname’ is enabled for database mirroring. Database mirroring must be removed before you drop the database.

Resolution

1 . ALTER DATABASE [databasename] SET partner OFF

Note: Above command will remove the mirroring .

2. restore database [databasename] with recovery


Filed under: SQLServer mirroring Tagged: Database mirroring must be removed before you drop the database, Mirroring must be removed from the database for this DBCC command, RESTORE cannot operate on database 'dbname' because it is configured for database mirroring. Use ALTER DATABASE to remove mirroring if you intend to restore the database., The database ‘dbname' is enabled for database mirroring. Database mirroring must be removed before you drop the database

SQL Server monitoring

$
0
0

Every SQL Server DBA would have faced situations similar to SQL Server not accepting connections for few minutes, SQL Server not responding for few minute or Applications not able to connect with SQL Server for few minutes. Before DBA’s gets alerted about the situation and starts troubleshooting the issue. Everything becomes normal. Challenge in this situations is it becomes very difficult to understand where the underlying problem was, It could be a network connectivity, Application server problem or It might be an issue with SQL Server itself. How do we collect diagnostic data to prove that SQL Server was stable at the time of issue (or) If the issue is with SQL Server then how to collect data we need for diagnosing the issue when there is issue?

SQL Monitor to monitor SQL Server Services

SQL Monitor monitors the SQL Server services and creates log if SQL Server service is down (or) If SQL Server is not accepting (or) SQL Server is not responding to Queries

How it works?

SQL Monitor checks the SQL Server in 3-Phases

1. Check the status of SQL Server service through the windows service control manager

2. If the service is running then check if SQL Server is accepting connections

3. If SQL Server is accepting Connections then probe to perform a simple query and see if SQL Server is responding properly.

4. If SQL Server is not accepting Connections then connect to SQL Server using DAC and take a stack dump.

How to Configure

1. Create a folder call SQLMonitor in C:\

2. Create a Text file called serverlist.txt to fill all the SQLServer information in your account.

Format:

Servername [TAB] Servicename;

Ex:

Server1 MSSQLServer;

Server2 MSSQL$Prod;

3. Invoke command prompt and open attached SQLmonitor.EXE.

Advantage:

1. Multi-threaded . Each server and service is verified using its own thread so retrieving information from one server will not affect the pooling interval to other server.

2. Single exe can be scaled to monitor more than 1000 servers and 1000 services.

3. Uses few MB of memory and system resources.

You can Download SQL Monitor from this link


Filed under: SQLServer engine, SQLServer tools Tagged: Monitoring SQL Server, SQLServer not accepting connections, Troubleshooting SQLServer hung

Error 601 : Could not continue scan with NOLOCK due to data movement.

$
0
0

When there is corruption in database (or) When scanning the data with the NOLOCK locking hint (or) with the transaction isolation level set to READ UNCOMMITTED, it is possible for the page at the current position of the scan would have deleted or moved by page splits caused by Inserts/Updates/Deletes making SQL Server not able to scan further and cause Error 601 : Could not continue scan with NOLOCK due to data movement.

Resolution
Unless the database has been explicitly marked as ‘read only’ there is no way to guarantee that there are no data modification operations going on.
The possible solutions are:
1. Check for 601 errors from the application and retry the query automatically if the error occurs.
2. Improve the indexes supporting the query or modify the query so that it has a smaller lock footprint and runs more quickly. If the query touches less data it will be less likely to encounter the problem.
3. Avoid use of NOLOCK hint and if necessary have a retry logic 601 error . Improving the indexes as mentioned above might make it possible to get this data without doing large scans that would be likely to cause blocking.
If you don’t use NOLOCK hint or to READ UNCOMMITTED Isolation level then check the database for corruption (Dbcc checkdb)


Filed under: SQLServer engine Tagged: Could not continue scan with NOLOCK due to data movement, Error 601, line Could not continue scan with NOLOCK due to data movement

How to stimulate a SQL Server resource failure in cluster

$
0
0

How to stimulate a SQL Server resource  failure in cluster?

If you like to perform a check in SQL Server cluster to identify if the SQL Server resources are failing over properly follow the below steps. you can use Step 2 to create a SQL Server hang and deadlocked scheduler dump in standalone server as well.

 

 

1.       Create a instance failures scenario by  issuing “shutdown” command to SQL Server which will terminate/Shutdown SQL Server. SQL Server resource DLL in cluster should detect that the SQL Server have failed and start the SQL Server resource automatically.

 

Steps

a.       Connect to SQL Server using an account which has Sysadmin privilege and execute Shutdown command.

 

 

2.       Create a SQL Server hang scenario by creating excessive blocking, once SQL Server exhaust all the available threads SQL Server will stop accepting connections and will go unresponsive. SQL Server resource in the cluster should detect that the SQL Server resource have failed and restart/failover SQL Server.

Steps

a.        Connect to SQL Server and below SQL Statements. (Do not close the session)

{

 

Create database test;

go

use test;

go

create table block  (a char(10));

go

insert into block values (‘Test’);

go

begin transaction

update block set a =’Test’

 

}

b.      Download the Ostress.exe from This link

 

c.       Execute the following command in ostress.exe

 

ostress.exe -Sservername\Instancename -E -d tempdb -Q “select * from tempdb..block” -n 2000

Note: Replace servername\instancename with your server name and instance name. Above Ostress command creates 2000 connections and execute “select * from tempdb..block” which will in turn cause excessive blocking and make SQLServer exhaust all the available worker threads.

Is Alive check will fail once the threads are exhausted causing SQL Server to reach hung state. SQL Server resource DLL’s should detect that SQL Server is hung and restart/failover SQL Server.

 

 If you do not know what is SQL Server LooksAlive and IsAlive Check follow This blog


Filed under: SQLServer Cluster Tagged: How to create dead locked scheduler dump, How to hang SQL Server, how to test SQLServer cluster

SSIS package fails when executed as job using proxy account

$
0
0

Issue

The SQL server Integration package which transfers the data from data source like excel to SQL Server database fails when executed from SQL Agent job using proxy account

ERROR

Date                      4/25/2013 4:16:34 PM

Log                         Job History (SSISTest)

Step ID                 1

Server                   Myserver\SQL2008STD

Job Name                            SSISTest

Step Name                         SSISJob1

Duration                              00:00:01

Sql Severity                        0

Sql Message ID                 0

Operator Emailed                           

Operator Net sent                          

Operator Paged                               

Retries Attempted                          0

Message

Executed as user: MyDomain\MyUser1. Microsoft (R) SQL Server Execute Package Utility  Version 10.50.4276.0 for 32-bit  Copyright (C) Microsoft Corporation 2010. All rights reserved.    Started:  4:16:34 PM  Info: 2013-04-25 16:16:34.81     Code: 0x4004300A     Source: Data Flow Task to move data from MS Excel to SQL server database SSIS.Pipeline     Description: Validation phase is beginning.  End Info  Error: 2013-04-25 16:16:35.04     Code: 0xC0202009     Source: Package Connection manager “Excel Connection Manager 1″     Description: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0×80004005.  An OLE DB record is available.  Source: “Microsoft Access Database Engine”  Hresult: 0×80004005  Description: “The Microsoft Access database engine cannot open or write to the file ”. It is already opened exclusively by another user, or you need permission to view and write its data.”.  End Error  Error: 2013-04-25 16:16:35.05     Code: 0xC020801C     Source: Data Flow Task to move data from MS Excel to SQL server database Excel Source [1]     Description: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER.  The AcquireConnection method call to the connection manager “Excel Connection Manager 1″ failed with error code 0xC0202009.  There may be error messages posted before this with more information on why the AcquireConnection method call failed.  End Error  Error: 2013-04-25 16:16:35.07     Code: 0xC0047017     Source: Data Flow Task to move data from MS Excel to SQL server database SSIS.Pipeline     Description: component “Excel Source” (1) failed validation and returned error code 0xC020801C.  End Error  Error: 2013-04-25 16:16:35.07     Code: 0xC004700C     Source: Data Flow Task to move data from MS Excel to SQL server database SSIS.Pipeline     Description: One or more component failed validation.  End Error  Error: 2013-04-25 16:16:35.09     Code: 0xC0024107     Source: Data Flow Task to move data from MS Excel to SQL server database      Description: There were errors during task validation.  End Error  DTExec: The package execution returned DTSER_FAILURE (1).  Started:  4:16:34 PM  Finished: 4:16:35 PM  Elapsed:  0.764 seconds.  Process Exit Code 1.  The step failed.

Cause:

Missing permission on PROFILE directory of SQL server Agent service account for Proxy account .

BufferTEMPstorage path and BlobTempstoragepath are defaulted to TEMP and TMP environment variables for SQL Server agent start up account by default.

When you use proxy account to execute a package then proxy account should have access to temp and TMP folder of SQL Server agents start up account profile.

TEMP=C:\Users\StartupaccountofSQLAgent\AppData\Local\Temp

TMP=C:\Users\ StartupaccountofSQLAgent\AppData\Local\Temp

If your start up account of SQL Server agent is Local service or Network service then proxy account should have permission for TMP and TEMP folder located under C:\Windows\ServiceProfiles for Local service and Network service

If the proxy account doesn’t have access to this location SSIS job would produce the below error:

Date,Source,Severity,Step ID,Server,Job Name,Step Name,Notifications,Message,Duration,Sql Severity,Sql Message ID,Operator Emailed,Operator Net sent,Operator Paged,Retries Attempted

04/08/2013 11:26:19,ExcelTC,Error,0,UKLONDT642483,ExcelTC,(Job outcome),,The job failed.  The Job was invoked by User MyDomain\MyUser1.  The last step to run was step 1 (ExcelTC\Package).,00:00:01,0,0,,,,0

04/08/2013 11:26:19,ExcelTC,Error,1,UKLONDT642483,ExcelTC,ExcelTC\Package,,Executed as user: MyDomain\MyUser1. Microsoft (R) SQL Server Execute Package Utility  Version 10.0.5500.0 for 32-bit  Copyright (C) Microsoft Corp 1984-2005. All rights reserved.   

Started:  11:26:19  Info: 2013-04-08 11:26:19.94     Code: 0x4004300A     Source: Data Flow Task SSIS.Pipeline     Description: Validation phase is beginning.  End Info  Error: 2013-04-08 11:26:19.98     Code: 0xC0202009     Source: Package Connection manager “Excel Connection Manager”     Description: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0×80004005.  An OLE DB record is available.  Source: “Microsoft Office Access Database Engine”  Hresult: 0×80004005  Description: “Unspecified error”.  End Error  Error: 2013-04-08 11:26:19.98     Code: 0xC020801C     Source: Data Flow Task Excel Source [1]     Description: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER.  The AcquireConnection method call to the connection manager “Excel Connection Manager” failed with error code 0xC0202009.  There may be error messages posted before this with more information on why the AcquireConnection method call failed.  End Error  Error: 2013-04-08 11:26:19.98     Code: 0xC0047017     Source: Data Flow Task SSIS.Pipeline     Description: component “Excel Source” (1) failed validation and returned error code 0xC020801C.  End Error  Error: 2013-04-08 11:26:19.98     Code: 0xC004700C     Source: Data Flow Task SSIS.Pipeline     Description: One or more component failed validation.  End Error  Error: 2013-04-08 11:26:19.98     Code: 0xC0024107     Source: Data Flow Task      Description: There were errors during task validation.  End Error  DTExec: The package execution returned DTSER_FAILURE (1).  Started:  11:26:19  Finished: 11:26:19  Elapsed:  0.405 seconds.  Process Exit Code 1.  The step failed.,00:00:01,0,0,,,,0

04/08/2013 11:10:11,ExcelTC,Error,0,UKLONDT642483,ExcelTC,(Job outcome),,The job failed.  The Job was invoked by User MyDomain\MyUser1.  The last step to run was step 1 (ExcelTC\Package).,00:00:01,0,0,,,,0

04/08/2013 11:10:11,ExcelTC,Error,1,UKLONDT642483,ExcelTC,ExcelTC\Package,,Executed as user: MyDomain\MyUser1. Microsoft (R) SQL Server Execute Package Utility  Version 10.0.5500.0 for 32-bit  Copyright (C) Microsoft Corp 1984-2005. All rights reserved.    Started:  11:10:12  Info: 2013-04-08 11:10:12.65     Code: 0x4004300A     Source: Data Flow Task SSIS.Pipeline     Description: Validation phase is beginning.  End Info  Error: 2013-04-08 11:10:12.78     Code: 0xC0202009     Source: Package Connection manager “Excel Connection Manager”     Description: SSIS Error Code DTS_E_OLEDBERROR.  An OLE DB error has occurred. Error code: 0×80004005.  An OLE DB record is available.  Source: “Microsoft Office Access Database Engine”  Hresult: 0×80004005  Description: “Unspecified error”.  End Error  Error: 2013-04-08 11:10:12.78     Code: 0xC020801C     Source: Data Flow Task Excel Source [1]     Description: SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER.  The AcquireConnection method call to the connection manager “Excel Connection Manager” failed with error code 0xC0202009.  There may be error messages posted before this with more information on why the AcquireConnection method call failed.  End Error  Error: 2013-04-08 11:10:12.79     Code: 0xC0047017     Source: Data Flow Task SSIS.Pipeline     Description: component “Excel Source” (1) failed validation and returned error code 0xC020801C.  End Error  Error: 2013-04-08 11:10:12.79     Code: 0xC004700C     Source: Data Flow Task SSIS.Pipeline     Description: One or more component failed validation.  End Error  Error: 2013-04-08 11:10:12.79     Code: 0xC0024107     Source: Data Flow Task      Description: There were errors during task validation.  End Error  DTExec: The package execution returned DTSER_FAILURE (1).  Started:  11:10:12  Finished: 11:10:12  Elapsed:  0.593 seconds.  Process Exit Code 1.  The step failed.,00:00:01,0,0,,,,0


Filed under: SQLServer security, SSIS Tagged: AcquireConnection method call failed, Description: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80004005, SSIS Error Code DTS_E_CANNOTACQUIRECONNECTIONFROMCONNECTIONMANAGER. The AcquireConnection method call to the connection manager

Capture context switches from dm_os_ring_buffers

$
0
0

You can use the below query to extract the context switches information from ring buffers and time each thread spend owning the scheduler.

SELECT  
dateadd (ms, (a.[timestamp] - tme.ms_ticks), GETDATE()) as Time_Stamp,
a.*
FROM
(SELECT 
	  y as timestamp,	
      x.value('(//Record/@id)[1]', 'bigint') AS [Record Id],
      x.value('(//Record/@type)[1]', 'varchar(30)') AS [Type],
      x.value('(//Record/@time)[1]', 'bigint') AS [Time],
      x.value('(//Record/Scheduler/@address)[1]', 'varchar(30)') AS [Scheduler Address],
      x.value('(//Record/Scheduler/Action)[1]', 'varchar(30)') AS [Scheduler Action],
      x.value('(//Record/Scheduler/CPUTicks)[1]', 'bigint') AS [Scheduler CPUTicks],
      x.value('(//Record/Scheduler/TickCount)[1]', 'bigint') AS [Scheduler TickCount],
      x.value('(//Record/Scheduler/SourceWorker)[1]', 'varchar(30)') AS [Scheduler SourceWorker],
      x.value('(//Record/Scheduler/TargetWorker)[1]', 'varchar(30)') AS [Scheduler TargetWorker],
      x.value('(//Record/Scheduler/WorkerSignalTime)[1]', 'bigint') AS [Scheduler WorkerSignalTime],
      x.value('(//Record/Scheduler/DiskIOCompleted)[1]', 'bigint') AS [Scheduler DiskIOCompleted],
      x.value('(//Record/Scheduler/TimersExpired)[1]', 'bigint') AS [Scheduler TimersExpired]
FROM
      (SELECT CAST (record as xml),timestamp  
      FROM sys.dm_os_ring_buffers 
      WHERE ring_buffer_type = 'RING_BUFFER_SCHEDULER' ) AS R(x,y)) a
	  cross join sys.dm_os_sys_info tme 
WHERE a.[Scheduler Action] = 'SCHEDULER_SWITCH_CONTEXT'
ORDER BY       a.[Scheduler Address] , [Time_stamp]


Filed under: SQLServer engine, SQLServer Query Tagged: context switch, context switches, dm_os_ring_buffers, ring buffer

CreateFileMapping or MapViewOfFileEx example

$
0
0

CreateFileMapping or MapViewOfFileEx example

#include <windows.h> 
#include <string> 
#include <winbase.h> 
#include <iostream> 
using namespace std;

void main()
{
	HANDLE  h;

	CHAR *filename;
 
	filename =new CHAR[2500];
	wcout<<"enter the file name:";
	cin.getline (filename,2500);
	h= CreateFile( filename,GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_FLAG_SEQUENTIAL_SCAN,NULL);
	cout<<filename;
	if (h!=INVALID_HANDLE_VALUE)
	{
	printf("\nFile is opened/created");
	DWORD size = GetFileSize(h, NULL);
	HANDLE hFileMapping = CreateFileMapping(h, NULL,PAGE_READONLY, 0, 0, NULL);	
	
	CloseHandle(h);

	MapViewOfFileEx(hFileMapping, FILE_MAP_READ, 0,  0,0,NULL);           
		system("Pause");

	UnmapViewOfFile(hFileMapping);
	
	}
	else
	{
	printf("\nUnable to open or create file");
	}
	system ("pause");

}
		


Filed under: Programming Tagged: CreateFileMapping, MapViewOfFileEx

CreateProcess example

$
0
0

CreateProcess example

#include <windows.h> 
#include <string> 
#include <winbase.h> 
#include <iostream> 
using namespace std;

void main()
{
	int N=5;	
	cout<<"Enter count for process:";
	cin>>N;

	PROCESS_INFORMATION *x;
	STARTUPINFO *startup_info;

	startup_info = new STARTUPINFO[N];
	x =new  PROCESS_INFORMATION[N]; 
    HANDLE *h;
	h = new HANDLE[N];
	for (int i=0;i<N;i++)
		{
			memset((char *)&startup_info[i], 0, sizeof(STARTUPINFO));
			startup_info[i].cb = sizeof(STARTUPINFO);
			startup_info[i].dwFlags = STARTF_USESTDHANDLES;
			startup_info[i].hStdInput = GetStdHandle(STD_INPUT_HANDLE);
			printf("\nProcess creation starting:%d",i);
			CreateProcess("c:\\windows\\notepad.exe",NULL,NULL,NULL,FALSE,0x00010000,NULL,NULL,startup_info,&x[i]);
			h[i]= x[i].hProcess;
		
		}
		
	WaitForMultipleObjects(N, h,TRUE,INFINITE);
	
	for (int i=0;i<N;i++)
		{
		CloseHandle(x[i].hProcess);
		CloseHandle(x[i].hThread);
		}

}


Filed under: Programming Tagged: CreateProcess

Criticalsection example

$
0
0

Criticalsection and CreateThread example (EnterCriticalSection LeaveCriticalSection)

#include <windows.h> 
#include <string> 
#include <iostream> 
#include <process.h>    /* _beginthread, _endthread */
long a=0;
long b=0;
int Threadcount=64;
int s=Threadcount;
CRITICAL_SECTION  gcs; 
void Submain(void *x)
{
	for (int L=0;L<1000;L++) 
		{

			a=a++;
			EnterCriticalSection(&gcs);
						b=b++;
			LeaveCriticalSection(&gcs);
		}

/*
    s=s-1;  //Simple synchronization technique. May be useful if you like to increase the thread count WaitForMultipleObjects support value defined for MAXIMUM_WAIT_OBJECTS 64
	if(s==0)
	{
		d=TRUE;
	}
*/
_endthread();
}

 
void main()

{

HANDLE *hThreads;
hThreads = new HANDLE[Threadcount] ;
InitializeCriticalSection(&gcs);
for (int i=0;i<Threadcount;i++)
{
hThreads[i]=	CreateThread(NULL,NULL,(LPTHREAD_START_ROUTINE  )Submain,  NULL,  0,  NULL);
 	
		if (hThreads[i]==NULL)
		{
			printf("\nThread creation failed for thread %d with error %d",i,GetLastError());
		}

}

DWORD rw=WaitForMultipleObjects(Threadcount,hThreads,true,INFINITE);
DeleteCriticalSection(&gcs);
//while(!d); //Simple synchronization technique 

printf("Value of a is:%d\n" ,a);
printf("Value of b is:%d\n" ,b);
system("pause");
}


Filed under: Programming Tagged: CreateThread, EnterCriticalSection, LeaveCriticalSection

CryptAcquireContext and CryptReleaseContext example

$
0
0

CryptAcquireContext and CryptReleaseContext example

#include <windows.h> 
#include <string> 
#include <winbase.h> 
#include <iostream> 
using namespace std;
#include <Wincrypt.h >
  
                                      
void main()
{
LPCSTR rgwchKeyContName = "Test123456";  
HCRYPTPROV m_hCryptoProviderFB;
BOOL ret;
BOOL ret2;

ret=CryptAcquireContext(&m_hCryptoProviderFB, rgwchKeyContName, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_SILENT);
	
if (!ret && GetLastError() == NTE_BAD_KEYSET)

{
	
	printf("\nUnable to open Keyset.CryptAcquireContext failed with error: 0x%X . \nWe will try creating key",GetLastError());

	ret2=CryptAcquireContext(&m_hCryptoProviderFB, rgwchKeyContName, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_NEWKEYSET | CRYPT_SILENT);
		if (!ret2)
		{
		printf("\nCryptAcquireContext failed creating key.Error: 0x%X",GetLastError());
		}
		else
		{
		printf("\nKey created");
		}
	exit;
}


else if (!ret && GetLastError() == NTE_BAD_KEYSET)
{
printf("CryptAcquireContext failed with error: 0x%X",GetLastError());
}

else
{

	printf("CryptAcquireContext opened key. Return value is 0x%X.",ret);
}


	if (CryptReleaseContext(m_hCryptoProviderFB,0))
	{
	//printf("\nHandle has been released.\n");
	}
	else
	{
	printf("\nHandle could not be released.\n");
	}

}


Filed under: Programming Tagged: CryptAcquireContext, CryptReleaseContext

Bulk insert fails with error 4861 Cannot bulk load because the file could not be opened

$
0
0

When you do bulk insert in SQL Server it may fail with below error because of double hop .

Error :

Msg 4861, Level 16, State 1, Line 3

Cannot bulk load because the file “\\path\” could not be opened. Operating system error code 5(failed to retrieve text for this error. Reason: 15105).

Steps to fix the above error

1. Connect to SQL Server using SSMS (With account you run bulk insert) and execute below query and check if it is using Kerberos authentication

select net_transport,auth_scheme from sys.dm_exec_connections where session_id=@@spid

2. If the session is not using Kerberos authentication then fix the SPN issues (startup account of SQL Server should have read and write SPN permissions). Account which is running bulk inser should have read SPN permission. Setpn exe or adsiedit can be used to add or display all the SPN’s. If the SPn’s are registered properly and still connection fails to NTLM then get the output of SSPIClient.exe and verify why Kerberos authentication fails.

3. Make sure the account which is running bulk insert is trusted for delegation in Active Directory.

4. Account which is running bulk insert should have access to the shared directory in which BCP files are placed.

Reference  BULK INSERT (Transact-SQL) 

http://msdn.microsoft.com/en-us/library/ms188365.aspx

Security Account Delegation (Impersonation)

If a SQL Server user is logged in using Windows Authentication, the user can read only the files accessible to the user account, independent of the security profile of the SQL Server process.

When executing the BULK INSERT statement by using sqlcmd or osql, from one computer, inserting data into SQL Server on a second computer, and specifying a data_file on third computer by using a UNC path, you may receive a 4861 error.

To resolve this error, use SQL Server Authentication and specify a SQL Server login that uses the security profile of the SQL Server process account, or configure Windows to enable security account delegation. For information about how to enable a user account to be trusted for delegation, see Windows Help.

For more information about this and other security considerations for using BULK INSERT, see Import Bulk Data by Using BULK INSERT or OPENROWSET(BULK…) (SQL Server).


Filed under: SQLServer engine, SQLServer security Tagged: Cannot bulk load because the file, Cannot bulk load because the file could not be opened. Operating system error code 5(failed to retrieve text for this error. Reason: 15105), could not be opened. Operating system error code 5(failed to retrieve text for this error. Reason: 15105), Msg 4861 Level 16 State 1 Line 3

windows cluster freezes at “waiting for notification that node ‘‘ is a fully functional member of the cluster”

$
0
0
Adding node in windows cluster freezes at “waiting for notification that node ‘‘ is a fully functional member of the cluster” When you try to add a node to cluster in windows2008 or windows2008 R2 or windows 2012 it may get stuck in the below screen With message “waiting for notification that node is a […]

SQL Server Error while enabling Windows feature : NetFx3, Error Code : -2146498298

$
0
0
SQL Server 2012 setup might fails with below error when you do not have .Net frame work 3.5 features. {TITLE: Microsoft SQL Server 2012 Setup——————————The following error has occurred:Error while enabling Windows feature : NetFx3, Error Code : -2146498298 , Please try enabling Windows feature : NetFx3 from Windows management tools and then run setup […]

A SQL product other than SQL Server 2014 CTP1 is detected. You cannot install this release until the existing instances of SQL products are uninstalled

$
0
0
When you install SQL Server 2014 set support rules would fail in “SQL product installation rule” with below error —————————Rule Check Result————————— Rule “Previous SQL product installation” failed.  A SQL product other than SQL Server 2014 CTP1 is detected. You cannot install this release until the existing instances of SQL products are uninstalled. —————————OK […]

PREEMPTIVE_OS_AUTHORIZATIONOPS waits in SQL Server

$
0
0
SQL Server threads which are controlled by SOS (SQL Server operating system) are Non preemptive but at times they switch preemptive when they can’t obey the rules of SOS. Some common places when SOS thread is switched preemptive are when we call extended proc’s, few Windows API etc.   Let us assume you use “execute […]

SQL Server cluster installation checklist

$
0
0
List of checks you may need to perform before you install SQL Server Cluster. 1. Verify your system meets the minimum requirements 910228 SQL Server 2005 Readme and installation requirements http://support.microsoft.com/default.aspx?scid=kb;EN-US;910228907284 Changes to the readme file for SQL Server 2005 http://support.microsoft.com/default.aspx?scid=kb;EN-US;907284327518 The Microsoft support policy for a SQL Server Failover cluster – Please note that […]
Viewing all 89 articles
Browse latest View live