Showing posts with label Tips and Tricks. Show all posts
Showing posts with label Tips and Tricks. Show all posts

Monday, December 21, 2015

SQL Server DDL Triggers to Track All Database Changes

Problem
In a perfect world, only the DBA would have sa privileges, F5 would only ever be hit on purpose, every change would go through rigorous source control procedures, and we would have full backups of all databases every minute. Of course, in reality, we deal with much different circumstances, and we can find ourselves (or overhear someone else) saying, "Oops... how do I fix that?" One of the more common scenarios I've seen involves someone editing a stored procedure multiple times between backups or within some kind of cycle, and then wishing they had version (current - 1) available. It's not in the backup yet, so can't be restored; and the user, of course, has closed his or her window without saving.
Solution
There are a lot of solutions to this issue, of course. They include tightening down server access, adopting a reliable source control system, and implementing a rigorous and well-documented deployment process. These things do not happen overnight, so in the meantime, DDL Triggers can provide a short-term fix that is both easy to implement and simple to manage. The approach is to take a snapshot of the current objects in the database, and then log all DDL changes from that point forward. With a well-managed log, you could easily see the state of an object at any point in time (assuming, of course, the objects are not encrypted).
 
So where do we start? First, I like to keep housekeeping items (monitoring, administration etc.) in their own database. This allows me to query things centrally and also to control growth separately. For this task, let's use a database called AuditDB:
CREATE DATABASE AuditDB;
GO
To keep things relatively simple, let's assume we are only interested in actions taken on stored procedures - create, alter, drop. We have a set of stored procedures already, and they are in a given state. We will need to capture that state, in addition to any changes that are made to them from that point forward. This way, we will always be able to get back to any state, including the original state.
In addition to the data specific to the actions taken on stored procedures, we can also think of several other pieces of information we would want to store about each event. For example:
  • database name
  • schema / object name
  • login information
  • host name / IP address (useful with SQL auth)
So here is the definition for a table to capture these events and the surrounding information about them:
USE AuditDB;
GO


CREATE TABLE dbo.DDLEvents
(
    EventDate    DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
    EventType    NVARCHAR(64),
    EventDDL     NVARCHAR(MAX),
    EventXML     XML,
    DatabaseName NVARCHAR(255),
    SchemaName   NVARCHAR(255),
    ObjectName   NVARCHAR(255),
    HostName     VARCHAR(64),
    IPAddress    VARCHAR(32),
    ProgramName  NVARCHAR(255),
    LoginName    NVARCHAR(255)
);
Yes, we could keep the table skinnier and use [object_id] instead of schema/object name, also protecting us from resolution problems due to renames. However, often stored procedures are dropped and re-created, in which case the system will generate a new [object_id]. I also prefer to use the database name to make ad hoc queries (and script automation) against specific databases easier. You can choose which metadata to rely on; personally, I'll trade the space for readability and scriptability.
Now that the table exists, we can easily grab a snapshot of our existing stored procedure definitions, leaving out some of the irrelevant auditing data, as follows (replacing 'my name' with whatever you want to display for the initial rows):
USE YourDatabase;
GO


INSERT AuditDB.dbo.DDLEvents
(
    EventType,
    EventDDL,
    DatabaseName,
    SchemaName,
    ObjectName,
    LoginName
)
SELECT
    'CREATE_PROCEDURE',
    OBJECT_DEFINITION([object_id]),
    DB_NAME(),
    OBJECT_SCHEMA_NAME([object_id]),
    OBJECT_NAME([object_id]),
    'my name'
FROM
    sys.procedures;
Now we're ready to start capturing actual changes to these procedures as they happen. You can create a DDL Trigger with the following code, that will record pertinent data to the above table when changes are made to stored procedures:
USE YourDatabase;
GO


CREATE TRIGGER DDLTrigger_Sample
    ON DATABASE
    FOR CREATE_PROCEDURE, ALTER_PROCEDURE, DROP_PROCEDURE
AS
BEGIN
    SET NOCOUNT ON;
    DECLARE
        @EventData XML = EVENTDATA();
 
    DECLARE 
        @ip VARCHAR(32) =
        (
            SELECT client_net_address
                FROM sys.dm_exec_connections
                WHERE session_id = @@SPID
        );
 
    INSERT AuditDB.dbo.DDLEvents
    (
        EventType,
        EventDDL,
        EventXML,
        DatabaseName,
        SchemaName,
        ObjectName,
        HostName,
        IPAddress,
        ProgramName,
        LoginName
    )
    SELECT
        @EventData.value('(/EVENT_INSTANCE/EventType)[1]',   'NVARCHAR(100)'), 
        @EventData.value('(/EVENT_INSTANCE/TSQLCommand)[1]', 'NVARCHAR(MAX)'),
        @EventData,
        DB_NAME(),
        @EventData.value('(/EVENT_INSTANCE/SchemaName)[1]',  'NVARCHAR(255)'), 
        @EventData.value('(/EVENT_INSTANCE/ObjectName)[1]',  'NVARCHAR(255)'),
        HOST_NAME(),
        @ip,
        PROGRAM_NAME(),
        SUSER_SNAME();
END
GO
Note that when you create a DDL Trigger, just like a DML Trigger, it is enabled and will start working immediately. To disable it, you can run the following code:
USE YourDatabase;
GO


DISABLE TRIGGER [DDLTrigger_Sample] ON DATABASE;
And then to re-enable:
USE YourDatabase;
GO


ENABLE TRIGGER [DDLTrigger_Sample] ON DATABASE;
So now you can test the auditing capabilities by altering an existing procedure. Right-click a procedure in Object Explorer and choose Modify. Add the following line somewhere in the body:
-- testing audit
Then you can run a query against the DDLEvents table:
SELECT *
    FROM AuditDB.dbo.DDLEvents
    WHERE EventType = 'ALTER_PROCEDURE';
Assuming your system is relatively quiet, all you should see is the change above. Now to go one step further, you can examine the differences between the initial object and its most recent state using a query like this:
;WITH [Events] AS
(
    SELECT
        EventDate,
        DatabaseName,
        SchemaName,
        ObjectName,
        EventDDL,
        rnLatest = ROW_NUMBER() OVER 
        (
            PARTITION BY DatabaseName, SchemaName, ObjectName
            ORDER BY     EventDate DESC
        ),
        rnEarliest = ROW_NUMBER() OVER
        (
            PARTITION BY DatabaseName, SchemaName, ObjectName
            ORDER BY     EventDate
        )        
    FROM
        AuditDB.dbo.DDLEvents
)
SELECT
    Original.DatabaseName,
    Original.SchemaName,
    Original.ObjectName,
    OriginalCode = Original.EventDDL,
    NewestCode   = COALESCE(Newest.EventDDL, ''),
    LastModified = COALESCE(Newest.EventDate, Original.EventDate)
FROM
    [Events] AS Original
LEFT OUTER JOIN
    [Events] AS Newest
    ON  Original.DatabaseName = Newest.DatabaseName
    AND Original.SchemaName   = Newest.SchemaName
    AND Original.ObjectName   = Newest.ObjectName
    AND Newest.rnEarliest = Original.rnLatest
    AND Newest.rnLatest = Original.rnEarliest
    AND Newest.rnEarliest > 1
WHERE
    Original.rnEarliest = 1;
If you are tracking down a specific object or an object in a specific schema, you could put additional WHERE clauses against Original.ObjectName or Original.SchemaName. From here, you can take the values for "OriginalCode" and "NewestCode" and put them through your favorite diff tool to see what changes there have been. And you can also change the query slightly to retrieve the latest version of any procedure, and the version that preceded it - I'll leave that as an exercise for the reader.
What the above does not capture are other peripheral changes that can happen to a stored procedure. For example, what about moving a procedure to a different schema? You can change the DDL Trigger above in the following way to capture the ALTER_SCHEMA event:
USE YourDatabase;
GO


ALTER TRIGGER DDLTrigger_Sample
    ON DATABASE
    FOR CREATE_PROCEDURE, ALTER_PROCEDURE, DROP_PROCEDURE,
        ALTER_SCHEMA
AS
BEGIN
    -- ...
And how about rename? Unfortunately in SQL Server 2005, DDL Triggers were unable to observe calls to sp_rename (or manual renames through Management Studio). In SQL Server 2008 and above, however, a rename can be captured with the aptly-named RENAME event:
USE YourDatabase;
GO


ALTER TRIGGER DDLTrigger_Sample
    ON DATABASE
    FOR CREATE_PROCEDURE, ALTER_PROCEDURE, DROP_PROCEDURE,
        ALTER_SCHEMA, RENAME
AS
BEGIN
    -- ...
(In a future tip, I'll demonstrate how to restrict these additional auditing rows to specific objects or object types, so that you're not capturing all kinds of irrelevant information about changes to objects other than stored procedures.)
Some other considerations:
  • You may want to put in a cleanup routine that gets rid of "noise" more than <n> days old (but still keeping the set of objects that are important to you).
  • To validate that your auditing process is capturing all changes, you can check modify_date in sys.procedures. Of course this only works for procedures that haven't been dropped - only if they have been created, modified, renamed, or transfered to a different schema.
  • Security might be an issue, depending on what you want to accomplish. Allow me to elaborate: DDL Triggers will not be transparent to users - first of all, they can see them in the Object Explorer tree, so it won't be a big secret that they are there and operational. They also appear in execution plans; if users have this option enabled when they create or modify objects in Management Studio, they will see the query plan for statements such as INSERT AuditDB.dbo.DDLEvents.
    If you want to hide the definition of the DDL Trigger, you can encrypt it as follows:
    USE YourDatabase;
    GO
    
    
    ALTER TRIGGER DDLTrigger_Sample
        ON DATABASE
        WITH ENCRYPTION
        FOR -- ...
    
    This way, when users want to see what the trigger is doing, they will right-click to generate a script, but the following is what will happen:
    TITLE: Microsoft SQL Server Management Studio
    ------------------------------
    Script failed for DatabaseDdlTrigger 'DDLTrigger_Sample'.
    Property TextHeader is not available for DatabaseDdlTrigger
    '[DDLTrigger_Sample]'. This property may not exist for this
    object, or may not be retrievable due to insufficient access
    rights.  The text is encrypted.
    ...
    
    But users with sufficient privileges can still disable the trigger, as described above. And you can't even capture this event, much less prevent it (which DDL Triggers are sometimes used for). For more information, see these Connect items:
    So, assuming SQL Server 2008 or above, you could use an audit specification to capture DDL events as a backup (or instead). But, given all of this, if you have to go to these lengths to prevent people from circumventing your auditing capabilites, then maybe your problems are larger and not all that technical. I suspect that in most reasonable environments, you'll sleep fine at night simply locking down the audit table.

I hope this provides a decent starting point to protect your environment(s) with DDL Triggers. However, given the manual aspect of this approach as well as its limitations, it will likely be best to consider this a short-term plan, and look into more robust source control and recovery techniques in the longer term.


Source : www.mssqltips.com

Tuesday, June 2, 2015

Android UI screen components

we will look at the different UI components of android screen and also covers the tips to make a better UI design and also explains how to design a UI.

UI screen components

A typical user interface of an android application consists of action bar and the application content area.
  1. Main Action Bar
  2. View Control
  3. Content Area
  4. Split Action Bar
These components have also been shown in the image below −
Anroid UI Tutorial

Understanding Screen Components

The basic unit of android application is the activity. A UI is defined in an xml file. During compilation, each element in the XML is compiled into equivalent Android GUI class with attributes represented by methods.

View and ViewGroups

An activity is consist of views. A view is just a widget that appears on the screen. It could be button e.t.c. One or more views can eb grouped together into one GroupView. Example of ViewGroup includes layouts.

Types of layout

There are many types of layout. Some of which are listed below:
  • Linear Layout
  • Absolute Layout
  • Table Layout
  • Frame Layout
  • Relative Layout

Linear Layout

Linear layout is further divided into horizontal and vertical layout. It means it can arrange views in a single column or in a single row. Here is the code of linear layout(vertical) that includes a text view.
<?xml version=”1.0 encoding=”utf-8”?>
<LinearLayout xmlns:android=”http://schemas.android.com/apk/res/android”
   android:layout_width=”fill_parent”
   android:layout_height=”fill_parent”
   android:orientation=”vertical” >
   
   <TextView
      android:layout_width=”fill_parent”
      android:layout_height=”wrap_content”
      android:text=”@string/hello” />
</LinearLayout>

AbsoluteLayout

The AbsoluteLayout enables you to specify the exact location of its children. It can be declared like this.
<AbsoluteLayout
   android:layout_width=”fill_parent”
   android:layout_height=”fill_parent”
   xmlns:android=”http://schemas.android.com/apk/res/android” >
   
   <Button
      android:layout_width=”188dp”
      android:layout_height=”wrap_content”
      android:text=”Button”
      android:layout_x=”126px”
      android:layout_y=”361px” />
</AbsoluteLayout>

TableLayout

The TableLayout groups views into rows and columns. It can be declared like this.
<TableLayout
   xmlns:android=”http://schemas.android.com/apk/res/android”
   android:layout_height=”fill_parent”
   android:layout_width=”fill_parent” >
   
   <TableRow>
      <TextView
      android:text=”User Name:”
      android:width =”120dp”
      />
      
      <EditText
      android:id=”@+id/txtUserName”
      android:width=”200dp” />
   </TableRow>
   
</TableLayout>

RelativeLayout

The RelativeLayout enables you to specify how child views are positioned relative to each other.It can be declared like this.
<RelativeLayout
   android:id=”@+id/RLayout”
   android:layout_width=”fill_parent”
   android:layout_height=”fill_parent”
   xmlns:android=”http://schemas.android.com/apk/res/android” >
</RelativeLayout>

FrameLayout

The FrameLayout is a placeholder on screen that you can use to display a single view. It can be declared like this.
<?xml version=”1.0 encoding=”utf-8”?>
<FrameLayout
   android:layout_width=”wrap_content”
   android:layout_height=”wrap_content”
   android:layout_alignLeft=”@+id/lblComments”
   android:layout_below=”@+id/lblComments”
   android:layout_centerHorizontal=”true” >
   
   <ImageView
      android:src = “@drawable/droid”
      android:layout_width=”wrap_content”
      android:layout_height=”wrap_content” />
</FrameLayout>
Apart form these attributes, there are other attributes that are common in all views and ViewGroups. They are listed below −
Sr.NoView & description
1layout_width
Specifies the width of the View or ViewGroup
2layout_height
Specifies the height of the View or ViewGroup
3layout_marginTop
Specifies extra space on the top side of the View or ViewGroup
4layout_marginBottom
Specifies extra space on the bottom side of the View or ViewGroup
5layout_marginLeft
Specifies extra space on the left side of the View or ViewGroup
6layout_marginRight
Specifies extra space on the right side of the View or ViewGroup
7layout_gravity
Specifies how child Views are positioned
8layout_weight
Specifies how much of the extra space in the layout should be allocated to the View

Units of Measurement

When you are specifying the size of an element on an Android UI, you should remember the following units of measurement.
Sr.NoUnit & description
1dp
Density-independent pixel. 1 dp is equivalent to one pixel on a 160 dpi screen.
2sp
Scale-independent pixel. This is similar to dp and is recommended for specifying font sizes
3pt
Point. A point is defined to be 1/72 of an inch, based on the physical screen size.
4px
Pixel. Corresponds to actual pixels on the screen

Screen Densities

Sr.NoDensity & DPI
1Low density (ldpi)
120 dpi
2Medium density (mdpi)
160 dpi
3High density (hdpi)
240 dpi
4Extra High density (xhdpi)
320 dpi

Optimizing layouts

Here are some of the guidelines for creating efficient layouts.
  • Avoid unnecessary nesting
  • Avoid using too many Views
  • Avoid deep nesting

Friday, August 1, 2014

How to find SQL Server Version,Edition,Server Name?

SQL Server provides a System Defined function SERVERPROPERTY(propertyname) .


By using this function you can find a number of things
Property Name
Description
syntax
Edition
Return SQL Server edition installed on machine.
select ServerProperty('edition')
EditionID
return Edition ID
select ServerProperty('editionid')
InstanceName
Return instance name if it is not default.In case of default return Null.
select ServerProperty('InstanceName')
ProductVersion
return Product version
select ServerProperty('ProductVersion')
BuildClrVersion
return version of the .NET framework Common Language Runtime (CLR)
select ServerProperty('BuildClrVersion')
EngineEdition
return
1 = Desktop
2 = Standard
3 = Enterprise
4 = Express
5 = SQL Azure


select ServerProperty('EngineEdition')
IsClustered
Server instance is configured in a failover cluster.
1 = Clustered.
0 = Not Clustered.
NULL = Input is not valid, or an error.


select ServerProperty('IsClustered')
MachineName
Return machine name
select ServerProperty('MachineName')
ResourceLastUpdateDateTime
Returns the date and time that the Resource database was last updated
select ServerProperty('ResourceLastUpdateDateTime')
ProductLevel
Returns Level of the version of SQL Server instance
'RTM' = Original release version
'SPn' = Service pack version
'CTP', = Community Technology Preview version


select ServerProperty('ProductLevel')





Friday, June 28, 2013

Android Tips and Tricks

Tips
  • Visual cue for scrolling: When you are in a scrollable list (like your Gmail inbox) and you reach the end of the list it shows an orange hue—a visual cue that you can’t scroll anymore.
  • Notification bar icons (Wi-Fi, network coverage bars, etc.): Turn green when you have an uninhibited connection to Google, white when you don't. Hint: if you're in a hotel or airport using Wi-Fi, the bars won't turn green until you launch the browser and get past the captive portal.
  • Voice actions: Tell your phone what to do by pressing the microphone icon next to the search box on the home screen, or long press the magnifying glass. You can tell it to send an email or text message (“send text to mom, see you for pizza at 7”), call someone ("call mom"), navigate somewhere (“navigate to pizza”), or listen to music ("listen to Mamma Mia").
  • Find things you’ve downloaded from your browser: Your downloads are now neatly collected in a Downloads manager, which you can find in the apps drawer.
  • Turn a Gallery stack into a slideshow: In Gallery, when you are looking at a stack of photos, put two fingers on the stack and spread them. The stack spreads out and the pictures flow from one finger to the other, a moving slideshow that lets you see all of the photos.
  • Walk, don’t drive: Once you’ve gotten directions within Google Maps, click on the walking person icon to get walking directions.
  • Easy text copy/paste from a webpage: To copy/paste from a webpage, long press some text, drag the handles around to select the text you want to copy, and press somewhere in the highlighted region. To paste, simply long press a text entry box and select paste. Gmail is a bit different: you need to go to Menu > More > Select Text.
  • Turn your phone into a Wi-Fi hotspot: Go to Settings > Wireless & Networks > Tethering & Portable Hotspot. (You may have to pay extra for this feature.)
  • Look at Maps in 3D: With the latest release of Google Maps , you can now look at 3D maps. Tilt the map by sliding two fingers vertically up/down the screen, and rotate it by placing two fingers on the map and sliding in a circular motion, e.g., from 12 and 6 o’clock to 3 and 9.
  • Cool shutdown effect: When you put the phone to sleep, you’ll see an animation that resembles an old cathode tube TV turning off.
Keyboard tricks
  • Shift+Key to capitalize a word: In Gingerbread (and supported hardware), you can Shift+Key to capitalize a letter instead of going to a separate all caps keyboard.
  • Auto-complete: The space bar lights up when auto-complete can finish a word.
  • Quick replace: Tap on any previously typed word, then tap on a suggestion to automatically replace it with the suggested word.
  • Easy access to special characters (like numbers, punctuation): Press and hold any key to go to the special character keyboard. You can also press and hold the "," key for an extensive punctuation keyboard.
Applications
  • Angry Birds: Popular game that lets you knock down blocks by slingshotting birds.
  • Astro: Awesome file explorer app. Browse and access the directories on your phone, and take full advantage of its capabilities. Great if you’re a power user.
  • Chrome to Phone: This one is really useful for Chrome users. You can send anything you browse on your computer to your phone. So if you are heading out to a restaurant or party and look up directions on your computer, just click the “send to phone” button (requires Chrome to Phone extension) and that exact page will open on your phone. Same with virtually any webpage.
  • Flash: Install from Android Market to watch Flash videos embedded throughout the web. Runs even better on Gingerbread.
  • Fruit Ninja: A juicy action game that tests your ability to smash flying fruit. A fun time-killer on the bus or train.
  • FXCamera: Popular photo sharing app with slick effects and filters.
  • Google Maps: Use your device as a GPS navigation system with free turn-by-turn voice guidance, and take advantage of other Google Maps features like Street View, Latitude and Places.
  • Instant Heart Rate: Measure your heart rate using your camera.
  • Phoneanlyzr: Track your phone usage: who you text most, call most, average call length distribution, etc.
  • RemoteDroid: Control your computer from your phone. Gives you a mobile wireless mouse and keyboard. Great if you’re using your computer for music or movies.
  • Shazam: Identifies virtually any song you are listening to.
  • SoundHound: Record a snippet of a song and get it identified instantly. You can even hum (if you can carry a tune!).
  • Tango: A free, high-quality video call app that works on both 3G and Wi-Fi. If your device has a front facing camera (e.g., Nexus S), you will love this app.
  • YouTube: New UI. Plus, portrait-mode player, and view comments and drop-down box video information