Wednesday, December 15, 2010
How Create a Unique Constraints in SQL Server 2008
You can do this with a filtered index in SQL 2008:
Syntax..................
CREATE UNIQUE NONCLUSTERED INDEX idx_col1 ON dbo.MyTable(col1) WHERE col1 IS NOT NULL;
Example.................
CREATE TABLE [dbo].[sav_acc_mcg](
[acc_id] [bigint] NOT NULL,
[br_id] [nvarchar](10) NOT NULL,
[scheme_id] [nvarchar](50) NOT NULL,
[acc_no_alias] [nvarchar](50) NOT NULL,
[acc_no] [nvarchar](50) NOT NULL
);
CREATE UNIQUE NONCLUSTERED INDEX idx_unique_acc_no_alias ON dbo.sav_acc_mcg(acc_no_alias) WHERE acc_no_alias IS NOT NULL;
Run above query in SQL Server 2008
Which will add the unique constrain in the column called "acc_no_alias" on the table name "sav_acc_mcg"
Does 'static' cause Memory Leak in Java?
What's memory leak? In simple terms, it's unused but referenced (somehow because the programmer probably unintentionally forgot to remove the references once the use of the object was over) part of the memory. Before we start discussing if 'static' can cause memory leak in Java, let me assure you that whatever you've read about Garbage Collectors in Java, is still valid and it certainly takes care of most (almost all) of the memory allocation/reclaimation of Java objects. But, that alone doesn't remove the possibility of the presence of memory leak in a Java program - just for example, you might not only be using only Java objects in your Java program. Putting it differently, what if you have used some native objects and forgot to reclaim the memory explicitly because that's anyway not going to be taken care by the GC (which takes care of heap memory management only)... right?
Now that we agree with the possibility of a Java program having potential memory leaks, let's see if using 'static' can also be one of the potential reasons for memory leaks in Java.
How to find if your Java program contains Memory Leaks?
Well... the programmer should have kept their eyes open while development itself. Once the app is ready, one may like to use Profilers (available from many vendors) to analyze the object graphs.
If your Java app is usually crashing with 'OutOfMemoryError' after executing for a while then it should ring an alarm for the possibility of memory leaks in your app. Though, this doesn't necessarily mean your app is having memory leaks, it might be possible that the allocated heap space is not enough for the proper functioning of your app.
Does 'static' cause memory leak in Java?
'static' can't straightway be blamed for causing memory leaks. But, if the programmer has not well thought the usage and has not taken care of the setting the references to 'null' explicitly after using the static objects then they can definitely cause memory leaks. Let's see how.
As you know 'static' members will by default live for the entire life of an app unless they are explicitly set to 'null'. So, always make it a point to nullify the references as soon as you reach at a point in your code where the use of the static member is over. For example: suppose you have created a 'Statement' object from a DB Connection and the connection is a pooled one. Now as you know calling close() method on a pooled connection will not actually close the connection instead it will return the Connection object to the pool to be re-used. So, in such a case unless you explicitly close the 'Statement' object, it would keep consuming precious memory space for no real use. Just think the scenario where you have declared the 'Statement' object as a static member, it'll be maintained in the memory for the entire life time of the app even when the control is out of the scope. It's just a sample scenario and many of you might never have used 'Statement' object in such an irresponsible manner. It's just an attempt to show how the 'static' can be misused to cause memory leaks in Java.
Not that if your Statement object is non-static you should reply on the out-of-scope nullification (i.e., as soon as control is out of scope the local objects would be marked for re-claimation) as in case you still have a significant amount of code (in terms of time/space) after using the Statement last and before reaching the end of the local scope, it would be a sheer wastage of memory if you don't explicitly nullify the 'Statement' after its use is over. Such a scenario should also be thought of as memory leaks only and one should always make sure the nullification of resources is as close to their last usage as possible.
Therefore, in summary we can say that one should/must :-
- always think if you really need to make this variable/member a 'static' one?
- always try to confine the scope of an object to restrict its usage only to the section it's actually needed
- always make a conscious effort to explicitly nullify objects once you finish using them (especially the large objects)
Why wait(), notify() and notifyAll() methods have been defined in the Object class?
Java concurrency model uses locks to implement mutually exclusive access to objects in a multi-threaded environment and locks are associated with every object in Java (of type 'Object'), not only with Threads.
wait, notify/notifyAll methods are used by threads to communicate with each other while trying to access a common object. Putting it differently, objects become a medium via which threads communicate with each other. For example: suppose there is a 'telephone' object, which at one point of time can be used by only one thread. Like every other object in Java, 'telephone' object would also have an intrinsic lock (monitor) associated with it which at one point of time can be acquired by only one thread. Suppose the 'telephone' object requires activation before it can be used and suppose only a few admin threads can activate the 'telephone' object.
As soon as a thread needs access to the 'telephone' object, it checks if the lock on that 'telephone' object is available or not, if yes, it acquires that and checks if the 'telephone' is active or not. If yes, it starts using it otherwise it calls 'wait()' on the telephone object which effectively releases the monitor of the 'telephone' object (eventually to be acquired by one of the admin threads for its activation) and puts the requester thread into the wait-set of the 'telephone' object. The requester thread goes into WAITING state. The way every object in Java has an intrinsic lock associated with it, it has an intrinsic wait-set associated with it as well.
Every other non-admin requester thread goes through the same process as discussed above till one of the admin threads acquire lock on the 'telephone' object and eventually activates it and subsequently calls 'notify()' or 'notifyAll()' on the 'telephone' object. 'notify()' will simply pick one of the threads from the wait-set of the 'telephone' object (which one will be picked is an implementation dependent stuff and Java Language specification doesn't enforce any restriction on which one to be picked) and the chosen thread will now get out of WAITING mode and start trying to acquire the monitor/lock of the 'telephone' object along with any other thread that might be vying to access the 'telephone' at that point of time.
The only difference between 'notify' and 'notifyAll' is that in case of the latter all the threads of the corresponding wait-set are picked and they all start trying to acquire the lock on the object (with any other incoming requester thread) at the same time.
Evidently you see that these three methods are essentially object-related and not thread-related and hence the designers of Java Language considered it wise to put them in the Object class instead of putting them into the Thread class. The usage of the 'object' (in our case 'telephone') is the particular object's prerogative and not that of the requester threads'. Putting these three methods in the Object class helps the objects owning/controlling their usage in a better way as in that case a thread needs to first acquire the lock on the object (kind of getting a license to use the object) and then calling either wait (in case the thread doesn't find the object in the state it would have wished it to be in and hence thought of waiting for some time to let the object become useful for it) or notify/notifyAll to alert other threads waiting on the object once it finishes using the object (of course in the case when the thread find the object useful in its current state).
Additionally, the communication among the interested threads becomes far too easier when the control is kept at the object's level - one common shared resource/medium and all interested threads communicating via it. Not that the communication won't be possible if these methods are kept in the Thread class, but the handling of the communication and usage of the objects in a multi-threaded environment will probably become more complex and less flexible in that case.
Why String has been made immutable in Java?
Though, performance is also a reason (assuming you are already aware of the internal String pool maintained for making sure that the same String object is used more than once without having to create/re-claim it those many times), but the main reason why String has been made immutable in Java is 'Security'. Surprised? Let's understand why.
Suppose you need to open a secure file which requires the users to authenticate themselves. Let's say there are two users named 'user1' and 'user2' and they have their own password files 'password1' and 'password2', respectively. Obviously 'user2' should not have access to 'password1' file.
As we know the filenames in Java are specified by using Strings. Even if you create a 'File' object, you pass the name of the file as a String only and that String is maintained inside the File object as one of its members.
Had String been mutable, 'user1' could have logged into using his credentials and then somehow could have managed to change the name of his password filename (a String object) from 'password1' to 'password2' before JVM actually places the native OS system call to open the file. This would have allowed 'user1' to open user2's password file. Understandably it would have resulted into a big security flaw in Java. I understand there are so many 'could have's here, but you would certainly agree that it would have opened a door to allow developers messing up the security of many resources either intentionally or un-intentionally.
With Strings being immutable, JVM can be sure that the filename instance member of the corresponding File object would keep pointing to same unchanged "filename" String object. The 'filename' instance member being a 'final' in the File class can anyway not be modified to point to any other String object specifying any other file than the intended one (i.e., the one which was used to create the File object).
ThreadLocal in Java - what is it used for?
As the name suggests this Java library class is used for supporting thread-local variables - the variables which are local to the particular thread instance and hence each thread will have their own copy of such variables which will be initialized every time a new thread is spawned.
To be more clear, let's take one simple example. If you have a class having some private/public static fields defined in it then all the objects created in all threads will share the same instances of those static fields. What if you want every thread to have a separate copy of it? ThreadLocal class will be of use in such cases, in fact they are mainly used for this purpose only. You can't just switch to a non-static field as in that case all the objects (even those created in the same thread) will have their own copies. You may come across situations asking you to have copies based on threads and not based on instances. This is where you will probably like to use ThreadLocal.
This class was introduced to Java in the version 1.2 and it has only three methods - one protected (initialValue()) and two public (get() and set()). The method set() is only rarely used as for most of the applications use the initialValue() method does the trick.
- protected Object initialValue() - as the name suggests this method returns the initial value of the ThreadLocal variable for the current thread and it's invoked at most once per thread. This method will be executed only if the thread calls the get() method on the ThreadLocal variable for the time and also only if the thread doesn't call set() method on the ThreadLocal variable prior to calling get() on it. As already mentioned that initialValue() method is called only when get() is called for the first time and hence if the thread calls set() method before get() then the initialValue() will never be executed on that ThreadLocal variable.
- public Object get() - evidently it will return the value of the ThreadLocal variable for the current thread. As discussed above, if it's called for the first time then the ThreadLocal variable is created and initialized by calling the initialValue() method internally.
- public void set(Object value) - like any other setter this method will also set the current thread's copy of the ThreadLocal variable to the passed 'value'. This method is used only rarely as in most of the cases initialValue() method solves the purpose in a better way.
initialValue() method v/s set() method for a ThreadLocal variable
- initialValue() method is called at most once and it's called only implicitly whereas set() method can be called any number of times and every time the call will be an explicit call.
- initialValue() is called when get() method is called for the first time on the ThreadLocal variable in the current thread and that too only when set() method has not been called before the first get() call (in which case initialValue() method is never called in that thread on that ThreadLocal variable).
Overriding the initialValue() method and using it in an application
initialValue() method is a protected method which initializes the ThreadLocal variable with 'null' in its default implementation and almost every time we need to override this method to initialize the ThreadLocal variable as per our requirements. Anonymous inner classes are normally used for this overriding to make the code more readable and maintainable. Let's walk through the sample code given in the Sun Javadoc for ThreadLocal.
public class SerialNum {
// The next serial number to be assigned
private static int nextSerialNum = 0;
private static ThreadLocal serialNum = new ThreadLocal() {
protected synchronized Object initialValue() {
return new Integer(nextSerialNum++);
}
};
public static int get() {
return ((Integer) (serialNum.get())).intValue();
}
}
In the above example, changes made to the private static int field named 'nextSerialNum' will be reflected in all the threads using the 'SerialNum' class as it's a normal static field and will be shared across all the instances created in all the threads, but the static ThreadLocal field named 'serialNum' will be created and maintained separately for all the threads and will not be shared across all the threads.
As you can see that anonymous inner class has been used to override the initialValue() method which sets the initial value of the ThreadLocal variable 'serialNum' to the Integer object created with the current value of the static field 'nextSerialNum'.
A call to the get method of the 'SerialNum' class will ultimately call the get() method on the ThreadLocal variable 'serialNum' and if the first outer get (of the SerialNum class) call will obviously make the first inner get (of the ThreadLocal class) call on the ThreadLocal instance 'serialNum' which will subsequently invoke the initialValue() on the ThreadLocal variable in the current thread.
InheritableThreadLocal - what's this and when to use it?
Suppose you have a requirement of setting the value of a ThreadLocal variable in a child thread as a function of the value of a ThreadLocal variable in the parent thread, then using a normal ThreadLocal variable won't do the needful as for ThreadLocal variables the initial values are set independently in every thread including any child threads as well.
InheritableThreadLocal which subclasses ThreadLocal class is used in such situations. This class has only one method 'protected Object childValue(Object parentValue)' which is used to set the initial value of the InheritableThreadLocal variable in the child thread as a function of a ThreadLocal variable (passed as a parameter) in the parent thread. This method is called from within the parent thread before the child thread is created and the default implementation will make the child values identical to parent's, but we can override the childValue() method to set the child value as a function of the parent value for those ThreadLocals which have values in the parent thread. By default the childValue() returns the same input argument, but again an override of the childValue method might change this behavior as well.
Usage of ThreadLocal: per-thread Singleton and per-thread Logging
Should you require a refresh of what ThreadLocals in Java are and how they work, refer to this article first. You can then proceed with the current article for understanding two of the most common uses of ThreadLocals in Java.
per-thread Singleton impl using ThreadLocal
Suppose you have a need of having a JDBC Connection objects per thread of your application. The moment you hear the term 'per-thread', ThreadLocal automatically comes into mind as that's what it's primarily meant for. Below is a sample implementation of how easily can you actually use ThreadLocal for a per-thread JDBC Connection object in Java.
public class ConnectionDispenser {
private static class ThreadLocalConnection extends ThreadLocal {
public Object initialValue() {
return DriverManager.getConnection(ConfigurationSingleton.getDbUrl());
}
}
private static ThreadLocalConnection conn = new ThreadLocalConnection();
public static Connection getConnection() {
return (Connection) conn.get();
}
}
Most of the code is self-explanatory and you can easily see how overriding the 'initialValue()' method of ThreadLocal is doing the trick of getting a Connection object by calling 'getConnection' method of the 'DriverManager' class. As you know the 'initialValue()' method is called only once for a ThreadLocal object and hence the Connection object will be obtained only once per thread (as a ThreadLocal object is created per thread only). From then on, whenever the particular thread requires the Connection object it simply calls the static 'getConnection' method of the your 'ConnectionDispenser' class, which in turn calls the 'get()' method of ThreadLocal to fetch the Connection object associated with that particular thread.
per-thread Debug Logging impl using ThreadLocal
Ever thought of having a per-thread DEBUG logging for any of your applications? Few multi-threading applications do get trickier at times and having per-thread DEBUG logs might be of great help in such situations as you probably can't visualize the actual order in which the threads might have executed and changed the shared objects. Here goes a sample implementation of per-thread DEBUG logging in Java using ThreadLocal.
public class DebugLogger {
private static class ThreadLocalList extends ThreadLocal {
public Object initialValue() {
return new ArrayList();
}
public List getList() {
return (List) super.get();
}
}
private ThreadLocalList list = new ThreadLocalList();
private static String[] stringArray = new String[0];
public void clear() {
list.getList().clear();
}
public void put(String text) {
list.getList().add(text);
}
public String[] get() {
return list.getList().toArray(stringArray);
}
}
As you can identify we are using an ArrayList object to store the logging info for a thread. 'initialValue' has been overridden to initialize every thread with a new ArrayList object. Whenever your multi-threaded application calls the 'put' method of your 'DebugLogger' class then all that method does is that it adds the logging info (passed as an String parameter to the 'put' call) to the corresponding ArrayList object of the current thread. Similarly a 'get' call of your 'DebugLogger' class simply returns the associated ArrayList object of the current thread in form of an String array. Evidently the 'clear' method of your 'DebugLogger' class is for clearing the logging info captured so far for the current thread - it'll simply clear the ArrayList object holding logging info for the current thread. This might help you getting rid of the non-essential logging info, maybe based on some condition, when you know for sure that all that you need for your debugging is what you are going to capture next and now what has already been captured so far.
Source: a nice article on ThreadLocals in Java, which I thoroughly enjoyed.
Source: Nice Articile at
http://geekexplains.blogspot.com/2009/08/per-thread-singleton-and-per-thread.html
Friday, November 26, 2010
How to Convert ResultSet into ArrayList
Converting ResultSet into ArrayList
public ArrayList resultSetToArrayList(ResultSet rs) throws SQLException{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
ArrayList results = new ArrayList();
while (rs.next()){
HashMap row = new HashMap();
results.add(row);
for(int i=1; i<=columns; i++){
row.put(md.getColumnName(i),rs.getObject(i));
}
}
return results;
}
Monday, November 15, 2010
TCP Provider: No connection could be made because the target machine actively refused it
TCP Provider: No connection could be made because the target machine actively refused it
In this post, I am trying to list out potential cause and general solution to this specific error when you are making connection to SQL Server 2005.
First, It is due to TCP connection fail, since you can tell from the title, "TCP Provider: .xx", which indicates that either your connection string explicitly use 'tcp:" prefix, say "Server=tcp:<machinename> ...." or your client protocol setting ask for first try Named Pipe connection, if fails, then fallback to TCP connection. For eg, in "Client NetworkUtility", you see the protocol order is "np on top of tcp".
Secondly, this error is winsock error "WSAECONNREFUSED - 10061". You'd better go through the following checklist to fix the "connection refused" problem.
1) Are you connecting to the right server? Check out whether your target machine name is valid.
2) Whether the <machinename> you specified in your connection string resolve to the correct ipaddress? do:
ping <machinename> (if your remote server has ipv6 enabled, it might return ipv6 address). Go to the remote machine to see whether it returned the correct ipaddress.
Then do ping -a <ipaddress>, can it be resolved to correct target machine name?
3) Are you connecting to default instance or named instance? Please go to the target machine, to check whether the instance started successfully, you can go to "Service Control Manager", find out "MSSQLSERVER" or "MSSQL$<instancename>" whether they are running?
4) Does your target SQL instance enabled TCP and listening on a valid TCP port?
a. If it is default instance, on your client machine, try : "telnet <ipaddress> 1433", remember, SQL Server 2005 default instance always use the reserved port 1433, namely, if you modify it to any other port number, the client app can not connect to the sql instance.
b. If it is named instance, on your target server machine, go to "SQL Server Configuration Manager", open "Protocols for MSSQL$<instancename>", check TCP enabled, and right click TCP, find out the tcp port number under 'IPAll". Then on your client machine, do " telnet <hostname> <portnumber>", see whether it succeeds.
5) Is your browser service running on the target server?
If you connect to named instance, then on your target server machine do "net start sqlbrowser".
6) Are your target server behind firewall?
If so, go to " SQL Server 2005 Surface Area configuration", click "Surface Area configuration for service and connection", then click the instance name, enable its remote connection.
You should be able to see the sql tcp port and udp port(1434 for browser service) is opened in Firewall, which enable you can telnet from client.
7) Does your client app set any alias that cause the connection redirect to an invalid port?
a. If you are using MDAC: on your client machine, click "cliconfig.exe", check out alias, whether it points to some other port that you can not telnet, if so, correct it or remove alias, since you should be able to connect through servername by sqlbrowser service automatcally respond to the correct port which server is listening on.
b. If you are using SNAC/SqlClient, go to SQL Configuration Manager, check out client protocols, see alias setting.
8) Check out IPSec setting if you still face problem. See whether IPSec specification make dropping any packets.
9) If you still face problem, please use "Evenvwr" on the client machine, try to look up the remote server application log, see any info from SQL Server that indicates the sql instance reject client connection. Under this situation, it probably due to invalid client request. Open SQL Profile also can help you dig out which client data operation make server terminate the connection.
A network-related or instance-specific error occurred while establishing a connection to SQL Server…”
SQL Server 2005 Error:
"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 – Error Locating Server/Instance Specified) "
Things to check:
1. Make sure your database engine is configured to accept remote connections
• Start > All Programs > SQL Server 2005 > Configuration Tools > SQL Server Surface Area Configuration
• Click on Surface Area Configuration for Services and Connections
• Select the instance that is having a problem > Database Engine > Remote Connections
• Enable local and remote connections
• Restart instance
2. Check the SQL Server service account
• If you are not using a domain account as a service account (for example if you are using NETWORK SERVICE), you may want to switch this first before proceeding
3. If you are using a named SQL Server instance, make sure you are using that instance name in your connection strings in your ASweb P.NET application
• Usually the format needed to specify the database server is machinename\instancename
• Check your connection string as well
<connectionStrings>
<add name="SampleConnectionString" connectionString="Data Source=machinename\instancename;Initial Catalog=AdventureWorks;Integrated Security=SSPI;Min Pool Size=5;Max Pool Size=60;Connect Timeout=30″ providerName="System.Data.SqlClient"/>
</connectionStrings>
4.You may need to create an exception on the firewall for the SQL Server instance and port you are using
• Start > Run > Firewall.cpl
• Click on exceptions tab
• Add the sqlservr.exe (typically located in C:\Program Files (x86)\Microsoft SQL Server\MSSQL.x\MSSQL\Binn), and port (default is 1433)
• Check your connection string as well
5. If you are using a named SQL Server instance, make sure you are using that instance name in your connection strings
6. Check SQLBrowser; check that it is running. You may also need to create an exception in your firewall for SQLBrowser.
7. Check that you have connectivity to the SQL Server. Note what you are using to connect: machine name, domain name or IP address? Use this when checking connectivity. For example if you are using myserver
• Start > Run > cmd
•netstat -ano| findstr 1433
•telnet myserver 1433
•ping -a myserver
Check what ports are IP addresses are being returned.
Alternative:
If you still can't get any connection, you may want to create a SQL account on the server, a corresponding SQL user on the database in question, and just use this username/password combo in your web application.
Related posts:
- Connection to target machine could not be made in a timely fashion ...
- SQL Server-Related Cheat Sheets That Can Save You Time ...
- SQL Server PowerShell : How to Audit Your SQL Server Instance Properties Using PowerShell and SMO ...
- Broken MDF, Broker, SSIS Ragged Right, SSRS Remote Error, Amazon S3, DBA Skills ...
- How to Connect to an Instance Name Using SMO ...
- SSRS Error: configuration file contains an element that is not valid ...
Configure Surface Area Configuration for SQL Server 2008 and 2005
Surface area reduction is a security measure that involves stopping or disabling unused components. Surface area reduction helps to improve security by providing fewer avenues for potential attacks on a system.
For new installations of SQL Server 2008, some features, services, and connections are disabled or stopped to reduce the SQL Server surface area. For upgraded installations, all features, services, and connections remain in their pre-upgrade state.
Use SQL Server Configuration Manager to enable, disable, start, or stop services and configure the remote connectivity of your Database Engine.
Use Policy-Based Management to enable and disable optional features.
The SQL Server Configuration Manager is installed with all editions of SQL Server.
To open the SQL Server Configuration Manager
On the Start menu, point to All Programs, point to Microsoft SQL Server 2008 R2, point to Configuration Tools, and then click SQL Server Configuration Manager.
To configure a service to start automatically
In SQL Server Configuration Manager, expand SQL Server Services.
In the details pane, right-click one of the SQL Server services, and then click Properties.
In the Properties dialog box, set Start Mode to Automatic.
To configure the Database Engine to accept remote connections
In SQL Server Configuration Manager, expand SQL Server Network Configuration, and then click Protocols for <instancename>.
In the details pane, right-click one of the available protocols, and then click Properties.
Note The shared memory protocol cannot be enabled for remote connections.
To enable a protocol for remote connections, set the Enabled box to Yes.
For help with SQL Server Configuration Manager, view the SQL Server Configuration Manager help file, or see SQL Server Books Online. To configure SOAP and Service Broker endpoints, use CREATE ENDPOINT and ALTER ENDPOINT.
Policy-Based Management is configured using SQL Server Management Studio. If Management Studio is not installed, run setup and install the client tools. Management Studio is not part of the installation of SQL Server Express. Download Management Studio Express from Microsoft.com. The features of Policy-Based Management are described in SQL Server Books Online.
To open the SQL Server Management Studio
On the Start menu, point to All Programs, point to Microsoft SQL Server 2008 R2, and then click SQL Server Management Studio.
To configure Policy-Based Management
In Management Studio, connect to an instance of Database Engine, expand Management, and then expand Policy Management.
Configure Policy-Based Management by using the following three facets:
Surface Area Configuration
Surface Area Configuration for Analysis Services
Surface Area Configuration for Reporting Services
The surface area configuration features that are turned off by default should not be turned on unless they are required for a specific business need.
Recommended Settings:
Recommended settings for the Database Engine
Set all properties of the Surface Area Configuration facet to false.
Recommended settings for Analysis Services
Set all properties of the Surface Area Configuration for Analysis Services facet to false.
Recommended settings for Reporting Services
Use the Surface Area Configuration for Reporting Services to disable any Reporting Services features that you do not need.
SQL Server Surface Area Configuration 2005
Surface area reduction is a security measure that involves stopping or disabling unused components. Surface area reduction helps to improve security by providing fewer avenues for potential attacks on a system.
For new installations of Microsoft SQL Server 2005, some features, services, and connections are disabled or stopped to reduce the SQL Server surface area. For upgraded installations, all features, services, and connections remain in their pre-upgrade state.
Use SQL Server Surface Area Configuration to enable, disable, start, or stop the features, services, and remote connectivity of your SQL Server 2005 installations. You can use SQL Server Surface Area Configuration on local and remote servers.
SQL Server Surface Area Configuration uses Window Management Instrumentation (WMI) to view and change server settings. WMI provides a unified way for interfacing with the API calls that manage registry operations that configure SQL Server. For information about configuring permissions related to WMI, see the topic How to: Configure WMI to Show Server Status in SQL Server Tools.
After you install SQL Server 2005 or upgrade to SQL Server 2005, you should run SQL Server Surface Area Configuration to verify which features and services are enabled and running, and to verify which types of connections SQL Server 2005 will accept. After initial configuration, you can use SQL Server Surface Area Configuration to verify or change the state of features, services, and connections.
SQL Server Surface Area Configuration is available on the SQL Server Start menu:
- On the Start menu, point to All Programs, Microsoft SQL Server 2005, Configuration Tools, and then click SQL Server Surface Area Configuration.
The first page to appear is the SQL Server Surface Area Configuration start page. On the start page, specify which server you want to configure:
- Click the change computer link adjacent to Configure Surface Area for. The default value is localhost. If you previously selected a named server, you would see the server name.
- In the Select Computer dialog box, do one of the following:
- To configure SQL Server 2005 on the local computer, click Local computer.
- To configure SQL Server 2005 on another computer, click Remote computer, and then enter the computer name in the text box.
- To configure a failover cluster, click Remote computer, and then enter the failover cluster instance name in the text box.
- To configure SQL Server 2005 on the local computer, click Local computer.
- Click OK.
After selecting the computer to configure, you can launch two tools:
- Use Surface Area Configuration for Services and Connections to enable or disable Windows services and remote connectivity.
For descriptions of the service and connectivity settings and defaults for those settings, see Surface Area Configuration for Services and Connections.
- Use Surface Area Configuration for Features to enable and disable features of the Database Engine, Analysis Services, and Reporting Services.
For descriptions of the features and information about default feature settings, see Surface Area Configuration for Features.
To import and export surface area settings, use the sac command-prompt utility. Using this utility, you can configure the surface area on one computer, and then apply the same settings to other computers.
The easiest way to use the sac utility is to use SQL Server Surface Area Configuration to configure one computer, and then use the sac utility to export the settings of that computer to a file. You can use that file to apply the same settings to SQL Server 2005 components on other computers.
For more information, see sac Utility.
Other Resources
Surface Area Configuration for FeaturesSurface Area Configuration for Services and Connections
Configure Surface Area Configuration for SQL Server 2008
Written By: Ashish Kumar Mehta -- 4/29/2010 -- read/post comments -- print -- Rating: (not rated yet) Rate
Problem
I have installed a new instance of SQL Server 2008 Analysis Services and I am unable to find the Surface Area Configuration tool that I used to use in SQL Server 2005. How can I manage the Analysis Services features in SQL Server 2008?
Solution
Surface Area Configuration was a great tool which was introduced by Microsoft in SQL Server 2005 to help SQL Server DBA's to quickly turn ON / OFF many of the features which are turned fff by default in the product. However, Microsoft has removed Surface Area Configuration tool in SQL Server 2008. Now the question is how do you manage the Surface Area Configuration for Analysis Services? Database administrator can now use Policy Based Management to enable or disable feature for Analysis Services. Let's go through the steps to enable or disable Analysis Services features using Policy Based Management.
Configure Surface Area Configuration for SQL Server 2008 Analysis Services
1. Connect to SQL Server 2008 Analysis Services Instance using SQL Server Management Studio.
2. In Object Explorer, right click the SQL Server 2008 Analysis Services Instance and select Facets from the drop down list as shown in the below snippet to open up the Facets window.
3. In View Facets window you will be able to see the list of Facet which are available for SQL Server 2008 Analysis Services. You can select any of the Facet Properties and then select the value as True to enable the feature and choose the value as False to disable the feature as shown in the below snippet.
Once you have changed the values click OK to save the Surface Area Configuration changes. It is advised to keep the unwanted features turned off as this helps to protect your Analysis Services instance from potential attacks.
Analysis Services 2008 features which can be managed using Policy Based Management are:
- AdHocDataMiningQueriesEnabled: - The Data Mining Extension (DMX) OPENROWSET statement basically supports the use of ad hoc queries using external providers. Enable ad hoc data mining queries only if your applications and scripts use these statements, otherwise it is better to turn off this feature.
- AnonymousConnectionsEnabled: - Anonymous connections allow unauthenticated users to establish connections with your Analysis Services instance. Enable anonymous connections only if your applications require unauthenticated users to connect to the Analysis Service instance, otherwise it is better to turn off this feature.
- LinkedObjectsLinksFromOtherInstancesEnabled: - Analysis Services can supports linked objects, which link dimensions and measure groups between different instances. Enable linked objects - links from other instances, only if other instances of analysis services link to objects of the current instance.
- LinkedObjectsLinksToOtherInstancesEnabled: -Analysis Services supports linked objects, which link dimensions and measure groups between instances. Enable linked objects - links to other instances, only if this Analysis Services instance link to objects on other Analysis Services instances.
- ListenOnlyOnLocalConnections: - Enabling remote connections for Analysis Services opens a TCP/IP port on the server. Enable remote connections only if you want to allow connections for remote computers, otherwise it is better to turn off this feature.
- UserDefinedFunctionsEnabled: - Analysis Services can load assemblies that contain user defined functions. These functions can be based on the common language runtime (CLR) or can be Component Object Model (COM) objects. CLR based objects can be secured using the CLR security model, but COM objects cannot be secured. Enable loading of COM functions only if your applications require them, otherwise it is better to turn off this feature.
Next Steps
- Review tips on Policy Based Management.
- Review Policy Based Management in Books Online.
- http://msdn.microsoft.com/en-us/library/bb510667.aspx
- Review using Policy Based Management with Central Management Servers to ease administration across database servers.
- http://msdn.microsoft.com/en-us/library/bb895144.aspx
- Review SQL Server Surface Area Configuration for Features (SAC) Option Selection
- Review Using the SQL Server Surface Area Configuration Command Line Tool
- Review SQL Server security settings using the Surface Area Configuration tool (SAC)
- Read all my previous tips.
- Using XMLA Command to Clear Cache of a SQL Server Analysis Service Database
- How to Detach and Attach a SQL Server 2008 Analysis Services Database
- Using a Parent Child Hierarchy in SQL Server to Implement a Custom Security Scheme
- How to restore a SQL Server Analysis Services Database
- Using the SQL Server Analysis Services (SSAS) Deployment Wizard
- More...
Saturday, November 6, 2010
postgresql cursor loop example,
Execution result of the query in Postgresql Function
CREATE TABLE mem_reg_mcg
(
id serial NOT NULL,
br_id character varying(3) NOT NULL,
mid character varying(50) NOT NULL,
"name" character varying(200)
);
RETURNS character varying AS
$BODY$
DECLARE
_record RECORD;
alert_mesg character varying(2000);
IN_VAR1 character varying(50);
BEGIN
alert_mesg := '';
--Define output columns
FOR _record IN select m.name from mem_reg_mcg m where id> $1
LOOP
IN_VAR1 := _record.name;
--Build output string
alert_mesg := alert_mesg||IN_VAR1||', ';
END LOOP;
RETURN subString(alert_mesg,0,char_length(alert_mesg)-1);
--EXCEPTION -- WHEN OTHERS THEN -- RETURN 'No troubleshooting information at this time.';
END;
$BODY$ LANGUAGE 'plpgsql' VOLATILE
COST 100;
ALTER FUNCTION get_all_single_row_mem(m_id integer) OWNER TO postgres;
See Cursor example
CREATE OR REPLACE FUNCTION MYCURSOR (VARINA VARCHAR) RETURNS VARCHAR AS $$
declare
--cur1 cursor is select A1, A2 from A;
cur1 refcursor;
cid integer;
_A1 varchar (10) ;
_A2 varchar (10) ;
alert_mesg VARCHAR(2000) := '';
BEGIN
--open cur1;
OPEN cur1 FOR execute('select * from A');
loop
fetch cur1 into _A1, _A2;
if not found then
exit ;
end if;
alert_mesg := alert_mesg||rpad(_A1,20)||rpad(_A2,20);
end loop;
close cur1;
return alert_mesg;
END;
$$ LANGUAGE plpgsql
Supporting URL help from Postgresql
http://archives.postgresql.org/pgsql-sql/2005-04/msg00052.php
Tuesday, October 26, 2010
Issuing the own private certificate lik
Since a lot of people have asked about this in the past, I just wanted to give you an alternative to buying a certificate from for example Thawte or Verisign. If you only need a cert for your own users, i.e. no public certificate, then this way is a ok. The difference is that Thawte and Verisign (among others) are trusted by most web browsers by default. Your own issued one will not be by default, but you can add it to trusted root CA's and it'll work just as good.
This is a PDF document that I put together, and it focuses on creating a certificate for use with mail access, i.e. Outlook Web Access or between Outlook client and Exchange on the local network.
Thursday, October 14, 2010
Embedding SSL on Tomcat For Web application.
Setting Up SSL on Tomcat In 3 Easy Steps
Setting up SSL on Tomcat is easy and you don't have to do much for converting your web application to work with the Https protocol. But however, the problem you would find to set up SSL is the documentation available over the web. The documentation source is available on the Apache site but it starts off good and ends with a lot of confusion. Especially I was confused on the OpenSSL part where it says to use OpenSSL.
It might be good in a production environment to use OpenSSL but if you just want to test out SSL with Tomcat alone then it is more than enough to just have your JDK and Tomcat setups. So I would make you walk through the same steps which I did while getting SSL up and running and building a secured web app within a matter of minutes.
The things which I have used to setup SSL consists of:
- JDK 1.6
- Tomcat 6
Even though I have used the latest version I don't see any problems which you might face in carrying out the same set of steps for JDK 1.5 which I am about to explain. JDK comes shipped with a keytool executable which is required to generate a keystore. The keytool can be found in the earlier version of JDK too. The 3 steps which would make you to get started with setting up SSL are:
- Generating the Keystore file
- Configuring Tomcat for using the Keystore file
- Configuring your web application to work with SSL
Let's get this party started now.
1. Generating the KeyStore file
The keystore file is the one which would store the details of the certificates necessary to make the protocol secured. Certificates contain the information as to who is the source from which you are receiving the application data and to authenticate whether it is the intended party or not. To make this keystore you would have to use the keytool. So open command prompt in Windows or the shell in Linux and type:
cd %JAVA_HOME%/bin on Windows
cd $JAVA_HOME/bin on Linux
You would land up in the Java bin directory. Now time to run the keytool command. You have to provide some parameters to the command as follows :
keytool -genkey -alias techtracer -keypass ttadmin -keystore techtracer.bin -storepass ttadmin
The highlighted words are the ones which you would have to change according to your requirements. But keep one thing in mind that both the keypass and storepass passwords should be the same. The .bin file is actually your keystore file. It would now start a questionnaire. So fill in the relevant details accordingly. Look below for a reference as to what to answer for the questions.
What is your first and last name?
[Unknown]: nitin pai
What is the name of your organizational unit?
[Unknown]: home
What is the name of your organization?
[Unknown]: techtracer
What is the name of your City or Locality?
[Unknown]: mumbai
What is the name of your State or Province?
[Unknown]: maharashtra
What is the two-letter country code for this unit?
[Unknown]: IN
Is CN=nitin pai, OU=home, O=techtracer, L=mumbai, ST=maharashtra, C=IN correct?
[no]: yes
The command would then conclude. It would make a .bin file with the name you had provided inside the bin directory itself. In my case it was techtracer.bin which was located in
C:\Program Files\Java\jdk1.6.0_02\bin\
Put the .bin file in the webapps directory of Tomcat. This is required to avoid the need to give an absolute path of the file in the next step.
2. Configuring Tomcat for using the Keystore file
Here we would be making some changes to the server.xml file inside tomcat to tell it to use the keystore which was created in the earlier step for configuring SSL. Open the file server.xml which can be found as:
<CATALINA_HOME>/conf/server.xml
Now you have to modify it. Find the Connector element which has port="8443″ and uncomment it if already not done. Add two lines. The highlighted lines are the newly added ones.
<Connector port="8443″
maxThreads="150″ minSpareThreads="25″ maxSpareThreads="75″
enableLookups="true" disableUploadTimeout="true"
acceptCount="100″ debug="0″ scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS"
keystoreFile="../webapps/techtracer.bin"
keystorePass="ttadmin" />
You can notice that I have given the path to the keystoreFile property as relative to tomcat bin directory because the startup command will look for the .bin file. Now all you have to do is start your server and check the working of SSL by pointing your browser to the URL to:
https://localhost:8443/
Now that you have your tomcat running in the SSL mode you are ready to deploy an application to test its working. You must note that still your tomcat can run in normal mode too at the same time i.e on port 8080 with http. So it is but obvious that any application deployed to the server will be running on http and https at the same time. This is something that we don't want. We want our application to run only in the secured mode.
3. Configuring your web application to work with SSL
In order to do this for our test, take any application which has already been deployed successfully in Tomcat and first access it through http and https to see if it works fine. If yes, then open the web.xml of that application and just add this XML fragment before web-app ends i.e </web-app>
<security-constraint>
<web-resource-collection>
<web-resource-name>securedapp</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
Explanation of the fragment is beyond the scope of this tutorial but all you should notice is that the /* indicates that now, any resource in your application can be accessed only with https be it Servlets or JSP's. The term CONFIDENTIAL is the term which tells the server to make the application work on SSL. If you want to turn the SSL mode for this application off then just turn don't delete the fragment. Just put the value as NONE instead of CONFIDENTIAL. That's it!
Conclusion
These were the 3 easy steps in which you can make Tomcat to work in the SSL mode and also it tells you how easily you can turn the SSL mode on and off. If you find any difficulty or are not clear on any of the above steps feel free to drop in your queries. If you like this tutorial it would be nice of you to drop in a comment of appreciation or feedback as to how this tutorial can be improved.
Sunday, October 10, 2010
multiple instances of the same view be made to appear at the same time
Can multiple instances of the same view be made to appear at the same time?
- Yes. See IWorkbenchPage.showView(String primaryId, String secondaryId, int mode).
- The <view> element in the plugin.xml must also specify allowMultiple="true".
- Be sure to use a different
secondaryId
for each instance, otherwiseshowView
will find any existing view with the same primaryId and secondaryId rather than showing a new one. - To pass instance-specific data to the view, you will need to cast the resulting IViewPart down to the concrete view class and call your own setData method.
- Note that views with a secondaryId will not match placeholders specifying just the primaryId. In a perspective factory, placeholders can be added for multi-instance views using the format
primaryId + ':' + secondaryId
, where '*' wildcards are supported.
Friday, October 8, 2010
Why Developers Should Not Write Programs That Call 'sun' Packages
Why Developers Should Not Write Programs
That Call 'sun' Packages
In general, writing java programs that rely on sun.* is risky: they are not portable, and are not supported.
The java.*, javax.* and org.* packages documented in the Java 2 Platform Standard Edition API Specification make up the official, supported, public interface.
If a Java program directly calls only API in these packages, it will operate on all Java-compatible platforms, regardless of the underlying OS platform.
The sun.* packages are not part of the supported, public interface.For these reasons, there is no documentation available for the sun.* classes. Platform-independence is one of the great advantages of developing in the Java programming language. Furthermore, Sun and our licensees of Java technology are committed to maintaining backward compatibility of the APIs for future versions of the Java platform. (Except for code that relies on serious bugs that we later fix.) This means that once your program is written, the class files will work in future releases.
A Java program that directly calls into sun.* packages is not guaranteed to work on all Java-compatible platforms. In fact, such a program is not guaranteed to work even in future versions on the same platform.
Each company that implements the Java platform will do so in their own private way. The classes in sun.* are present in the SDK to support the Sun implementation of the Java platform: the sun.* classes are what make the Java platform classes work "under the covers" for the Sun Java 2 SDK. These classes will not in general be present on another vendor's Java platform. If your Java program asks for a class "sun.package.Foo" by name, it may fail with ClassNotFoundError, and you will have lost a major advantage of developing in Java.
Technically, nothing prevents your program from calling into sun.* by name. From one release to another, these classes may be removed, or they may be moved from one package to another, and it's fairly likely that their interface (method names and signatures) will change. (From the Sun point of view, since we are committed to maintaining the Java platform, we need to be able to change sun.* to refine and enhance the platform.) In this case, even if you are willing to run only on the Sun implementation, you run the risk of a new version of the implementation breaking your program.
In general, writing java programs that rely on sun.* is risky: they are not portable, and are not supported.
Wednesday, October 6, 2010
Fwd: Creates a tabbed display in Eclipse RCP application
Creates a tabbed display in Eclipse RCP application
step-----------
1. Create View in the project.
2. Assign the view Id in the perspective addView(4 parameter...); method and add the this(Member View);
package com.magnus.tabbedpane;
import org.eclipse.swt.SWT;
import java.io.*;
import org.eclipse.swt.events.*;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.ui.part.ViewPart;
public class MemberTabView extends ViewPart {
public static final String MEM_VIEW_ID="com.magnus.tabbedPane.MemberTab";
public MemberTabView() {
// TODO Auto-generated constructor stub
}
@Override
public void createPartControl(Composite parent) {
// Create the containing tab folder
final TabFolder tabFolder = new TabFolder(parent, SWT.NONE);
// Create each tab and set its text, tool tip text,
// image, and control
TabItem one = new TabItem(tabFolder, SWT.NONE);
one.setText("General Info");
one.setToolTipText("Member General Informaion");
one.setControl(getTabOneControl(tabFolder));
TabItem two = new TabItem(tabFolder, SWT.NONE);
two.setText("Financial Info");
two.setToolTipText("Enter Financial Information");
two.setControl(getTabTwoControl(tabFolder));
TabItem three = new TabItem(tabFolder, SWT.NONE);
three.setText("Education Info");
three.setToolTipText("Edutaion Information");
three.setControl(getTabThreeControl(tabFolder));
// Select the third tab (index is zero-based)
tabFolder.setSelection(0);
// Add an event listener to write the selected tab to stdout
tabFolder.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(org.eclipse.swt.events.SelectionEvent event) {
System.out.println(tabFolder.getSelection()[0].getText() + " selected");
}
});
}
/**
* Gets the control for tab one
*
* @param tabFolder the parent tab folder
* @return Control
*/
private Control getTabOneControl(TabFolder tabFolder) {
// Create some labels and text fields
Composite composite = new Composite(tabFolder, SWT.NONE);
composite.setLayout(new RowLayout());
new Label(composite, SWT.LEFT).setText("Label One:");
new Text(composite, SWT.BORDER);
new Label(composite, SWT.RIGHT).setText("Label Two:");
new Text(composite, SWT.BORDER);
return composite;
}
@Override
public void setFocus() {
// TODO Auto-generated method stub
}
/**
* Gets the control for tab two
*
* @param tabFolder the parent tab folder
* @return Control
*/
private Control getTabTwoControl(TabFolder tabFolder) {
// Create a multi-line text field
return new Text(tabFolder, SWT.BORDER | SWT.MULTI | SWT.WRAP);
}
/**
* Gets the control for tab three
*
* @param tabFolder the parent tab folder
* @return Control
*/
private Control getTabThreeControl(TabFolder tabFolder) {
// Create a composite and add four buttons to it
Composite composite = new Composite(tabFolder, SWT.NONE);
composite.setLayout(new FillLayout(SWT.VERTICAL));
new Button(composite, SWT.PUSH).setText("Button one");
new Button(composite, SWT.PUSH).setText("Button two");
new Button(composite, SWT.PUSH).setText("Button three");
new Button(composite, SWT.PUSH).setText("Button four");
return composite;
}
}
Perspective Vs IPerspectiveDescriptor RCP
org.eclipse.ui
Interface IPerspectiveDescriptor
public interface IPerspectiveDescriptor
A perspective descriptor describes a perspective in an IPerspectiveRegistry
.
A perspective is a template for view visibility, layout, and action visibility within a workbench page. There are two types of perspective: a predefined perspective and a custom perspective.
- A predefined perspective is defined by an extension to the workbench's perspective extension point (
"org.eclipse.ui.perspectives"
). The extension defines a id, label, andIPerspectiveFactory
. A perspective factory is used to define the initial layout for a page. - A custom perspective is defined by the user. In this case a predefined perspective is modified to suit a particular task and saved as a new perspective. The attributes for the perspective are stored in a separate file in the workbench's metadata directory.
Within a page the user can open any of the perspectives known to the workbench's perspective registry, typically by selecting one from the workbench's Open Perspective
menu. When selected, the views and actions within the active page rearrange to reflect the perspective.
This interface is not intended to be implemented by clients.
- See Also:
IPerspectiveRegistry
- Restriction:
- This interface is not intended to be implemented by clients.
Method Summary | |
---|---|
String | getDescription() Returns the description of this perspective. |
String | getId() Returns this perspective's id. |
ImageDescriptor | getImageDescriptor() Returns the descriptor of the image to show for this perspective. |
String | getLabel() Returns this perspective's label. |
Method Detail |
---|
getDescription
String getDescription()
- Returns the description of this perspective. This is the value of its
"description"
attribute. - Returns:
- the description
- Since:
- 3.0
getId
String getId()
- Returns this perspective's id. For perspectives declared via an extension, this is the value of its
"id"
attribute. - Returns:
- the perspective id
getImageDescriptor
ImageDescriptor getImageDescriptor()
- Returns the descriptor of the image to show for this perspective. If the extension for this perspective specifies an image, the descriptor for it is returned. Otherwise a default image is returned.
- Returns:
- the descriptor of the image to show for this perspective
getLabel
String getLabel()
- Returns this perspective's label. For perspectives declared via an extension, this is the value of its
"label"
attribute. - Returns:
- the label
Sunday, September 26, 2010
Make the ENTER key act like the TAB key In java.
import java.awt.event.KeyEvent;
To make the ENTER key act like the TAB key In java.
Changing the Focus When Pressing the Enter Key same as Tab key.
Swing Java code is.........................as follows.
import javax.swing.JTextField;
class MyTextField extends JTextField {
MyTextField(int len) {
super(len);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER)
transferFocus();
}
});
}
}
Friday, September 24, 2010
SQl Server Case in Query Exmple
case rp.Adds when 1 then 'Yes' else 'on' End as AllowAdd,
case rp.Views when 1 then 'Yes' else 'on' End as ViewAllow,
case rp.Deletes when 1 then 'Yes' else 'on' End as DeleteAllow,
case rp.Disapprove when 1 then 'Yes' else 'on' End as DisapproveAllow,
case rp.Approve when 1 then 'Yes' else 'on' End as ApprovedAllow
from RolePrivilege rp, RoleInfo ri, ModuleOperation mo
where rp.RoleID=ri.RoleID and rp.OPerationID=mo.OperationID and ri.RoleId=2;