Friday, May 9, 2014

Maintain Scroll Position on Postback in ASP.NET

After a long time googling I have got a good solutions to maintain scroll position. See the post given below.

This article shows how to allows pages to automatically maintain the current scroll position across postbacks.
The MaintainScrollPositionOnPostback page directive attribute allows to do that.
This feature is useful for large pages where scrolling is necessary to view input controls down further on the page.
There are three ways of applying the property to a web page.

  1. You can set it programmatically 
    Page.MaintainScrollPositionOnPostBack = true;
  2. In the page declaration 
    <%@ Page MaintainScrollPositionOnPostback="true" %>
  3. Or in the web.configs <system.web> section. 
    <pages maintainScrollPositionOnPostBack="true" />
I have used 3 point & It's working absolutely fine.
 
This feature is an absolute must-have on large web pages built for postback scenarios.
A simple but very useful feature.

Smartnavigation = true  implemented the same feature in 1.1 framework SmartNavigation only had "issues" and it only worked in IE but the new MaintainScrollPositionOnPostback apparently works in most common browsers.


Monday, March 31, 2014

Generate a unique alphanumeric password using SQL



DECLARE @PwdLen SMALLINT,
@Chr TINYINT,
@Password VARCHAR(20)

-- Seed
SET @Chr = RAND(DATEPART(ms, GETDATE())) * 0
SET @Password = ''

SET @PwdLen = 1
WHILE @PwdLen < 8
BEGIN
SET @Chr = RAND() * 62
SET @Password = @Password + CHAR(
CASE WHEN @Chr < 10 THEN @Chr + 48 
WHEN @Chr BETWEEN 10 AND 35 THEN @Chr + 55 
ELSE @Chr + 61 
END)

SET @PwdLen = @PwdLen + 1
END

SELECT @Password [Password]

Wednesday, March 19, 2014

SQL statement which will give me all the days of a given month as individual rows

Hi friends,

I have searched a lot in Google and finally I found that its too easy to get the result. Check the query given below.

DECLARE @month    INT
DECLARE @year    INT
SET @month=2
SET @year = 2016

SELECT CAST(CAST(@year AS VARCHAR) + '-' + CAST(@Month AS VARCHAR) + '-01' AS DATETIME) + Number 'date'
FROM master..spt_values WHERE type = 'P'
AND
(CAST(CAST(@year AS VARCHAR) + '-' + CAST(@Month AS VARCHAR) + '-01' AS DATETIME) + Number )
<
DATEADD(mm,1,CAST(CAST(@year AS VARCHAR) + '-' + CAST(@Month AS VARCHAR) + '-01' AS DATETIME) )

 

Saturday, February 22, 2014

Last modified Tables & Stored Procedures details in Microsoft SQL Server

Let's find out the last modified Tables & Stored Procedures details in MSSQL by writting a simple Query.

For User Tables
SELECT * FROM sys.objects WHERE type='U' ORDER BY modify_date DESC

For Stored Procedures
SELECT * FROM sys.objects WHERE type='P' ORDER BY modify_date DESC

These Queries fetching records from system object table order by last modified date & time.  

Friday, February 21, 2014

Enable remote connections for SQL Server Express 2012

  1. Run SQL Server Configuration Manager.
  2. Go to SQL Server Network Configuration > Protocols for SQLEXPRESS.
  3. Make sure TCP/IP is enabled.
So far, so good, and entirely expected. But then:
  1. Right-click on TCP/IP and select Properties.
  2. Verify that, under IP2, the IP Address is set to the computer's IP address on the local subnet.
  3. Scroll down to IPAll.
  4. Make sure that TCP Dynamic Ports is blank. (Mine was set to some 5-digit port number.)
  5. Make sure that TCP Port is set to 1433. (Mine was blank.)
(Also, if you follow these steps, it's not necessary to enable SQL Server Browser, and you only need to allow port 1433, not 1434.)

Monday, January 27, 2014

Files on External/Flash Drive Changed to Shortcuts Virus

Issue

I caught a virus on my flash drive at work and it appears to have changed all my file names to short cuts. I believe I’ve cleaned the virus but how do i get my files back so that I can view them?

Solution

  1. If you did not format your flash drive, then check whether the files are not in hidden mode.
  2. Click on “Start” –>Run–>type cmd and click on OK.
  3. Check your external Drive letter in My Computer
  4. Here I assume your external drive as G:
  5. Enter this command.attrib -h -r -s /s /d g:*.* 
  6. Delete the unnecessary shortcuts.
Note: Replace the letter g with your flash drive letter.
Still problem? Write down in comments section.


Tuesday, December 10, 2013

Want 5 digit string which is incremented automatic (A0001 - Z9999)

The first thing you need is a table to hold your generated keys:


CREATE TABLE [dbo].[IdGenerator](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Pk] [varchar](5) NOT NULL
)
 
-- Insert the first key
INSERT INTO IdGenerator (Pk) VALUES ('A0001')

It contains 2 columns. Id (the primary key, used to order your keys) and the key you want!

Then you need this script to generate a new Key base on the previous one:

-- Declare some variables we need
DECLARE @PK varchar(5)
DECLARE @Character char(1)
DECLARE @Number int
 
-- Get the last generated key (I'll call it @PK)
SET @PK = (SELECT TOP 1 PK FROM IdGenerator Order by Id desc)
-- Extract the character (A,B,C ...)
SET @Character = (SELECT SUBSTRING (@PK ,1, 1))
-- Extract the number (4 last characters. "0001", "0002"....)
SET @Number = (SELECT SUBSTRING (@PK ,2, 4))
 
-- Increase the number by 1
SET @Number = @Number + 1
 
-- Check if the number has reached the top (9999)
IF @Number > 9999
BEGIN
   -- If it has, set it to 1
   SET @Number = 1
   -- And find the next character in the alphabet (A->B, B->C...)
   SET @Character = char(ascii(@Character)+1)
END
 
-- Pad your number (1->0001, 2->0002...) and set you newly generated key
SET @PK = @Character + REPLACE(STR(@Number, 4), SPACE(1), '0')
 
-- Insert it to the IdGenerator table so we can use it for the next key
INSERT INTO IdGenerator (PK) VALUES (@PK)
 
-- And heres your new unique key :)
SELECT @PK

For this to work, you will have to add the first value (A0001) manually. And you
You can put this code in a stored procedure.


Reference : http://www.codeproject.com/Questions/441365/want-7-digit-string-which-is-incremented-automatic

Friday, November 29, 2013

How to know last updated Tables / Stored Procedures in Microsoft SQL Server 2008

Very simple query will return the result. How to know the last updated Tables / Stored Procedures in Microsoft SQL Server 2008.

Here is the query given below.

 

For Stored Procedures 

 

SELECT * FROM sys.objects WHERE type='P' ORDER BY modify_date DESC 

And for Tables 

 

SELECT * FROM sys.objects WHERE type='U' ORDER BY modify_date DESC 



Hope this will help !!!!!

Thanks
Solomon S.
(http://www.solomonsarkar.com)

Saturday, March 9, 2013

Sending a DataTable to a Stored Procedure

I found this beautiful article from  CodeProject written by _Amy

Introduction

This is a small article explaining how to send an entire data-table to a Stored Procedure in the database server as an input parameter. 

Background 

It uses a logic which allows us to do add, modify, and delete operations on a set of records in the database using a simple form. The details also need to be shown after adding, updating, and deleting of records in a table. And the data-table should be given to a stored procedure to perform the operations. This feature will work with SQL Server 2008.

Advantages  

  1. For each event on the page the form will not be interacting with the database. This reduces server round trips. 
  2. All necessary operations such as:
    1. Inserting a new record
    2. Updating an existing record
    3. Deleting an existing record
    are performed on client side only. They will be persisted in the database only after getting confirmation from the user. So, the performance of the application will improve.
  3. After performing a certain action (such as Insert, Update, or Delete) on the grid-view the data will be saved in “Session”. And whenever the data is required, it is be fetched from the Session. 
  4. We send the entire data-table from the session to the database for manipulation, and with the use of a Stored Procedure we can do operations such as insert, delete, and update.
  5. It is easier to perform all operations on a set of rows at a time.
  6. The user can deal with thousands of data-rows at the same time without a connection.
  7. Extends the functionality of programming in a database engine.

Using the code

When a page is getting loaded the first time, data from the database is loaded to a data-table. In that data-table a column is added (named Operation). Whenever the user performs an action on the grid-view, the indicator bit is added to that column for that record (Insert 0, Update 1, and Delete 2). If the user clicks on a delete link on a particular row then the operation column of that row is updated to 2, and in the RowDataBound event of the grid-view we hide the records whose operation bit is 2. The temporary table is stored in session state. Before performing any operation, the session table will be called and the action will be performed on that table and again that table will be stored in the session. After performing all the necessary operations, when the user clicks on the Save button, the functionfnMangeOperations is called which will filter all the rows on which the operation was performed and the Save button will send only those details in which the operation has to be performed (you can find the functionfnMangeOperations in the source code from the attached files). 

Step 1: Declaring global variables:  

private clsEmpDetails _objEmpDetails;
private DataTable _dtEmpDetails;
private DataTable _dtEmpDetailsVals;
Step 2: Initializing the data members when page loads.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        _objEmpDetails = new clsEmpDetails();
        _dtEmpDetails = _objEmpDetails.fnGetDetails();
        if(_dtEmpDetails != null){
           //Adding a new column to the table which will store the operation details
           //For new insert it will store 1
           //For updating the existing record it will store 0
           _dtEmpDetails.Columns.Add("Operation", typeof(string));
           Session["EmpDetails"] = _dtEmpDetails;
           gvEmpDetails.DataSource = _dtEmpDetails;
           gvEmpDetails.DataBind();
        }       
    }
}
Just store the data in session and maintain the indicator for each operation. The operation will be like this:
protected void gvEmpDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "AddNew") 
    {
       try{
            _dtEmpDetails = Session["EmpDetails"] as DataTable;
            string strID = (TextBox)gvEmpDetails.FooterRow.Cells[0].FindControl("txtInsID")).Text;
            string strName = (TextBox)gvEmpDetails.FooterRow.Cells[1].FindControl("txtInsName")).Text;
            string strAddress = (TextBox)gvEmpDetails.FooterRow.Cells[1].FindControl("txtInsAddress")).Text;
            _dtEmpDetails.Rows.Add(strID, strName, strAddress, "0");
            Session["EmpDetails"] = _dtEmpDetails;
            fnBindEmpDetails(); //This function will bind the data to the gridview by fetching the data from session
        }
        catch(Exception ex){            
             //Handle your exception
        }
    }
}
On click of the Save button, call the following function by passing your DataTable as a parameter.
public string fnStoredProc(DataTable dtDetails)
{
    string strMsg = "";
    try
    {
        fnConOpen();//Function for opening connection
        SqlCommand cmdProc = new SqlCommand("spEmpDetails", con);
        cmdProc.CommandType = CommandType.StoredProcedure;
        cmdProc.Parameters.AddWithValue("@Type", "InsertDetails");
        cmdProc.Parameters.AddWithValue("@Details", dtDetails);
        cmdProc.ExecuteNonQuery();
        strMsg = "Saved successfully.";
    }
    catch (SqlException e) {
        //strMsg = "Data not saved successfully.";
        strMsg = e.Message.ToString();
    }
    finally 
    {
        fnConClose();//Function for closing connection

    }
    return strMsg;
}

Procedure structure

First create a table type with matching columns which comes from the front-end. In this case:
/*Creating type for the procedure parameter*/
CREATE TYPE EmpType AS TABLE 
(
    ID INT, Name VARCHAR(3000), Address VARCHAR(8000), Operation SMALLINT
)
Write the procedure for the operations.
ALTER PROCEDURE spEmpDetails
@Type VARCHAR(15),
@Details EmpType READONLY
AS
BEGIN
    IF(@Type='FetchDetails')
        SELECT * FROM EmployeeDetails
    ELSE
        BEGIN
            --For deleting the details from the table
            DELETE FROM EmployeeDetails WHERE ID IN(SELECT ID FROM @Details WHERE Operation=2)
            
            --For updating the details in the table
            UPDATE e SET e.Name=d.Name, e.Address=d.Address FROM EmployeeDetails e, @Details d 
            WHERE d.ID=e.ID and d.Operation=1
            
            --For inserting the new records in the table
            INSERT INTO EmployeeDetails(ID, Name, Address) 
            SELECT ID, Name, Address FROM @Details WHERE Operation=0;
        END
    END
GO
Note: This procedure takes a datatabe as its parameter and performs insert, update, and delete operations based on the table data.

Monday, September 17, 2012

SQL SERVER – SHRINKFILE and TRUNCATE Log File in SQL Server 2008

Note: Please read the complete post before taking any actions.
This blog post would discuss SHRINKFILE and TRUNCATE Log File. The script mentioned in the email received from reader contains the following questionable code:
“Hi Pinal,
If you could remember, I and my manager met you at TechEd in Bangalore.
We just upgraded to SQL Server 2008. One of our jobs failed as it was using the following code.
The error was:
Msg 155, Level 15, State 1, Line 1
‘TRUNCATE_ONLY’ is not a recognized BACKUP option.
The code was:
DBCC SHRINKFILE(TestDBLog, 1)BACKUP LOG TestDB WITH TRUNCATE_ONLYDBCC SHRINKFILE(TestDBLog, 1)GO
I have modified that code to subsequent code and it works fine. But, are there other suggestions you have at the moment?
USE [master]
GO
ALTER DATABASE [TestDb] SET RECOVERY SIMPLE WITH NO_WAITDBCC SHRINKFILE(TestDbLog, 1)ALTER DATABASE [TestDb] SET RECOVERY FULL WITH NO_WAIT
GO
Configuration of our server and system is as follows:
[Removed not relevant data]“
An email like this that suddenly pops out in early morning is alarming email. Because I am a dead, busy mind, so I had only one min to reply. I wrote down quickly the following note. (As I said, it was a single-minute email so it is not completely accurate). Here is that quick email shared with all of you.
“Hi Mr. DBA [removed the name]
Thanks for your email. I suggest you stop this practice. There are many issues included here, but I would list two major issues:
1) From the setting database to simple recovery, shrinking the file and once again setting in full recovery, you are in fact losing your valuable log data and will be not able to restore point in time. Not only that, you will also not able to use subsequent log files.
2) Shrinking database file or database adds fragmentation.
There are a lot of things you can do. First, start taking proper log backup using following command instead of truncating them and losing them frequently.
BACKUP LOG [TestDb] TO  DISK = N'C:\Backup\TestDb.bak'GO
Remove the code of SHRINKING the file. If you are taking proper log backups, your log file usually (again usually, special cases are excluded) do not grow very big.
There are so many things to add here, but you can call me on my [phone number]. Before you call me, I suggest for accuracy you read Paul Randel‘s two posts here and here and Brent Ozar‘s Post here.
Kind Regards,
Pinal Dave”
I guess this post is very much clear to you. Please leave your comments here. As mentioned, this is a very huge subject; I have just touched a tip of the ice-berg and have tried to point to authentic knowledge.
Update: Small typo correction and small detail corrected based on feedback.
Reference: Pinal Dave (http://blog.SQLAuthority.com)