Total Pageviews

Saturday, January 30, 2010

Main Differences between ASP.NET 3.5 and ASP.NET 4.0

As we all know, ASP.NET 3.5 has introduced with the following main new features

1) AJAX integration
2) LINQ
3) Automatic Properties
4) Lambda expressions

I hope it would be useful for everyone to know about the differences about asp.net 3.5 and its next version asp.net 4.0

Because of space consumption I’ll list only some of them here.

1) Client Data access:



ASP.NET 3.5: There is no direct method to access data from client side. We can go for any of these methods

1) Pagemethods of script manager
2) ICallbackEventHandler interface
3) XMLHttphanlder component

ASP.NET 4.0: In this framework there is an inbuilt feature for this. Following are the methods to implement them.

1) Client data controls
2) Client templates
3) Client data context

i.e we can access the data through client data view & data context objects from client side.

2) Setting Meta keyword and Meta description:



Meta keywords and description are really useful for getting listed in search engine.

ASP.NET 3.5: It has a feature to add meta as following tag
&ltmeta name="keywords" content="These, are, my, keywords" /> 
  &ltmeta name="description" content="This is the description of my page" /> 


ASP.NET 4.0: Here we can add the keywords and description in Page directives itself as shown below.
< %@ Page Language="C#"  CodeFile="Default.aspx.cs" 
  Inherits="_Default" 
  Keywords="Keyword1,Key2,Key3,etc" 
  Description="description" %>


3) Enableviewstage property for each control



ASP.NET 3.5: this property has two values “True” or “false”

ASP.NET 4.0: ViewStateMode property takes an enumeration that has three values: Enabled, Disabled, and Inherit.
Here inherit is the default value for child controls of a control.

4) Setting Client IDs



Some times ClientID property creates head ach for the programmers.

ASP.NET 3.5: We have to use ClientID property to find out the id which is dynamically generated

ASP.NET 4.0: The new ClientIDMode property is introduced to minimize the issues of earlier versions of ASP.NET.

It has following values.

AutoID – Same as ASP.NET 3.5
Static – There won’t be any separate clientid generated at run time
Predictable-These are used particularly in datacontrols. Format is like clientIDrowsuffix with the clientid vlaue
Inherit- This value specifies that a control's ID generation is the same as its parent. 



--
happy programming.

Monday, January 25, 2010

.Net Memory Management & Garbage Collection

The Microsoft .NET common language runtime requires that all resources be allocated from the managed heap. Objects are automatically freed when they are no longer needed by the application.
When a process is initialized, the runtime reserves a contiguous region of address space that initially has no storage allocated for it. This address space region is the managed heap. The heap also maintains a pointer. This pointer indicates where the next object is to be allocated within the heap. Initially, the pointer is set to the base address of the reserved address space region.
Garbage collection in the Microsoft .NET common language runtime environment completely absolves the developer from tracking memory usage and knowing when to free memory. However, you’ll want to understand how it works. So let’s do it.
Topics Covered
We will cover the following topics in the article

  1. Why memory matters
  2. .Net Memory and garbage collection
  3. Generational garbage collection
  4. Temporary Objects
  5. Large object heap & Fragmentation
  6. Finalization
  7. Memory problems

1) Why Memory Matters

Insufficient use of memory can impact
  • Performance
  • Stability
  • Scalability
  • Other applications
Hidden problem in code can cause

  • Memory leaks
  • Excessive memory usage
  • Unnecessary performance overhead

2) .Net Memory and garbage collection

.Net manages memory automatically
  • Creates objects into memory blocks(heaps)
  • Destroy objects no longer in use
Allocates objects onto one of two heaps
  • Small object heap(SOH) – objects < 85k
  • Large object heap(LOH) – objects >= 85k
You allocate onto the heap whenever you use the “new” keyword in code
Small object heap (SOH)

  • Allocation of objects < 85k – Contiguous heap – Objects allocated consecutively
  • Next object pointer is maintained – Objects references held on Stack, Globals, Statics and CPU register
  • Objects not in use are garbage collected
Figure-1
SOH_1
Next, How GC works in SOH?
GC Collect the objects based on the following rules:

  • Reclaims memory from “rootless” objects
  • Runs whenever memory usage reaches certain thresholds
  • Identifies all objects still “in use”

    • Has root reference
    • Has an ancestor with a root reference

  • Compacts the heap

    • Copies “rooted” objects over rootless ones
    • Resets the next object pointer

  • Freezes all execution threads during GC

    • Every GC runs it   hit the performance of your app

Figure-2
SOH2

3) Generational garbage collection


Optimizing Garbage collection
  • Newest object usually dies quickly
  • Oldest object tend to stay alive
  • GC groups objects into Generations

    • Short lived – Gen 0
    • Medium – Gen 1
    • Long Lived – Gen 2

  • When an object survives a GC it is promoted to the next generation
  • GC compacts Gen 0 objects most often
  • The more the GC runs the bigger the impact on performance
Figure-3
Generations_3
Figure-4
Generations_4
Here object C is no longer referenced by any one so when GC runs it get destroyed & Object D will be moved to the Gen 1 (see figure-5). Now Gen 0 has no object, so when next time when GC runs it will collect object from Gen 1.

Figure-5
Generations_5
Figure-6
Generations_6
Here when GC runs it will move the object D & B to Gen 2 because it has been referenced by Global objects & Static objects.
Figure-7
Generations_7

Here when GC runs for Gen 2 it will find out that object A is no longer referenced by anyone so it will destroy it & frees his memory. Now Gen 2 has only object D & B.
Garbage collector runs when
  • Gen 0 objects reach ~256k
  • Gen 1 objects reach ~2Meg
  • Gen 2 objects reach ~10Meg
  • System memory is low
Most objects should die in Gen 0.
Impact on performance is very high when Gen 2 run because
  • Entire small object heap is compacted
  • Large object heap is collected

4) Temporary objects

  • Once allocated objects can’t resize on a contiguous heap
  • Objects such as strings are Immutable


    • Can’t be changed, new versions created instead
    • Heap fills with temporary objects

Let us take example to understand this scenario.
Figure – 8
TempObj_8
After the GC runs all the temporary objects are destroyed.
Figure–9

TempObj_9

5) Large object heap & Fragmentation

Large object heap (LOH)
  • Allocation of object >=85k
  • Non contiguous heap

    • Objects allocated using free space table


  • Garbage collected when LOH Threshold Is reached
  • Uses free space table to find where to allocate
  • Memory can become fragmented
Figure-10
LOH_10
After object B is destroyed free space table will be filled with a memory address which has been available now.
Figure-11
LOH_11

Now when you create new object, GC will check out which memory area is free or available for our new object in LOH. It will check out the Free space table & allocate object where it fit.
Figure-12
LOH_12

6) Object Finalization

  • Disk, Network, UI resources need safe cleanup after use by .NET classes
  • Object finalization guarantees cleanup code will be called before collection
  • Finalizable object survive for at least 1 extra GC & often make it to Gen 2
  • Finalizable classes have a

    • Finalize method(c# or vb.net)
    • C++ style destructor (c#)

Here are the guidelines that help you to decide when to use Finalize method:
  • Only implement Finalize on objects that require finalization. There are performance costs associated with Finalize methods.
  • If you require a Finalize method, you should consider implementing IDisposable to allow users of your class to avoid the cost of invoking the Finalize method.
  • Do not make the Finalize method more visible. It should be protected, not public.
  • An object’s Finalize method should free any external resources that the object owns. Moreover, a Finalize method should release only resources that are held onto by the object. The Finalize method should not reference any other objects.
  • Do not directly call a Finalize method on an object other than the object’s base class. This is not a valid operation in the C# programming language.
  • Call the base.Finalize method from an object’s Finalize method.
Note: The base class’s Finalize method is called automatically with the C# and the Managed Extensions for C++ destructor syntax.
Let see one example to understand how the finalization works.
Each figure itself explain what is going on & you can clearly see how the finalization works when GC run.

Figure-13
Final_13
Figure-14
Final_14
Figure-15
Final_15
Figure-16
Final_16
Figure-17

Final_17
For more information on Finalization refer the following links:
http://www.object-arts.com/docs/index.html?howdofinalizationandmourningactuallywork_.htm
http://blogs.msdn.com/cbrumme/archive/2004/02/20/77460.aspx
How to minimize overheads
Object size, number of objects, and object lifetime are all factors that impact your application’s allocation profile. While allocations are quick, the efficiency of garbage collection depends (among other things) on the generation being collected. Collecting small objects from Gen 0 is the most efficient form of garbage collection because Gen 0 is the smallest and typically fits in the CPU cache. In contrast, frequent collection of objects from Gen 2 is expensive. To identify when allocations occur, and which generations they occur in, observe your application’s allocation patterns by using an allocation profiler such as the CLR Profiler.
You can minimize overheads by:
  • Avoid Calling GC.Collect
  • Consider Using Weak References with Cached Data
  • Prevent the Promotion of Short-Lived Objects
  • Set Unneeded Member Variables to Null Before Making Long-Running Calls
  • Minimize Hidden Allocations
  • Avoid or Minimize Complex Object Graphs
  • Avoid Preallocating and Chunking Memory
Read more: http://www.guidanceshare.com/wiki/.NET_2.0_Performance_Guidelines_-_Garbage_Collection

7) Common Memory Problems

  • Excessive RAM footprint

    • App allocates objects too early or for too long using more memory than needed
    • Can affect other app on system

  • Excessive temporary object allocation

    • Garbage collection runs more frequently
    • Executing threads freeze during garbage collection

  • Memory leaks


    • Overlooked root references keep objects alive (collections, arrays, session state, delegates/events etc)
    • Incorrect or absent finalization can cause resource leaks

References & other useful articles related to this topic:
Hope this help

Thursday, January 7, 2010

Backing Up MySQL Database


Backing Up MySQL Database
MySQL database backup can be accomplished in two ways:
a) Copying the raw mysql database files &
b) Exporting tables to text files



Copying the MySQL database files
MySQL uses the same table format on different platforms, so it's possible to copy MySQL table and index files from one platform and use them on another without any difficulties (assuming, of course, that you're using the same version of MySQL on both platforms).


Exporting tables to text files
The MySQLDump is handy utility that can be used to quickly backup the MySQL Database to the text files. To use the MySQLDump utility it is required to logon to the System running the MySQL Databse. You can use Telnet to remotely logon to the system if you don't have the physical access to the machine.

The syntax for the command is as follows.

mysqldump -u [Username] -p [password] [databasename] > [backupfile.sql]
[username] - this is your database username
[password]- this is the password for your database
[databasename] - the name of your database
[backupfile.sql] - the filename for your database backup


Let's discuss the example of backing up MySQL Database named "accounts" into text file accounts.sql. Here are the scenarios of taking the backup assuming that both user name and password of the database is "admin".

a) Taking the full backup of all the tables including the data.
 

Use the following command to accomplish this:
mysqldump -u admin -p admin accounts > accounts.sql


b) Taking the backup of table structures only.
 

Use the following command to accomplish this:
mysqldump -u admin -p admin --no-data accounts > accounts.sql


c) Taking the backup data only.
 

Use the following command to accomplish this:
mysqldump -u admin -p admin --no-create-info accounts > accounts.sql



Restoring MySQL Database
Restoring the MySQL is very easy job. You can use the following to command to restore the accounts database from accounts.sql backup file.

mysql - u admin -p admin accounts < accounts.sql

In this tutorial you learned how to take the backup of your MySQL Database and restore the same in the event of some database crash or on some other machine.


-----------
Enjoy Programming



Monday, January 4, 2010

Uploading Multiple Files in ASP.NET 2.0

In ASP.NET We can upload more than one file using the following classes:

HttpFileCollection
HttpPostedFile
Request.Files
System.IO.Path

HttpFileCollection:

HttpFileCollection will provide access to the files uploaded by a client.

HttpPostedFile:

HttpPostedFile will provide access to individual files uploaded by a client. Through this class we can access the content and properties of each individual file, and read and save the files.

Request.Files :

The Request.Files will return collection of all files uploaded by user and store them inside the HttpFileCollection.

Follow these steps mentioned below to do so:

Step 1:

Drag and drop multiple (in our case four) FileUpload controls on to the designer.

Step 2:

Drop a Button control and rename it to “Upload”
<asp:Button ID=”btnUpload” runat=”server” Text=”Upload” />

Step 3:

Double click the Upload Button to add an event hander to the code behind.
protected void btnUpload_Click(object sender, EventArgs e)
{

}

Step 4: Import the System.IO namespace.
using System.IO;

Step 5:

Use the ‘HttpFileCollection’ class to retrieve all the files that are uploaded. Files are encoded and transmitted in the content body using multipart MIME format with an HTTP Content-Type header. ASP.NET extracts
this information from the content body into individual members of an HttpFileCollection.

The code would look as follows:
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
hpf.SaveAs(Server.MapPath(”MyFiles”) + “\\” +
Path.GetFileName(hpf.FileName));

}
}
}
catch (Exception ex)
{
// Handle your exception here
}

}
Some important points to consider while uploading

1.    To save a file to the server, the account associated with ASP.NET must have sufficient permissions on the folder, where the files are being uploaded. This would usually be the ‘ASPNET’ account for Windows XP or a similar OS. In Windows Server 2003, the account used is ‘NETWORKSERVICE’. So you would be required to explicitly grant write permissions to these accounts on the folder.

2.    While uploading the files to a remote server, the default ASPNET user account used by ASP.NET does not have network permissions by default. The solution is to either give the account such permissions or
use impersonation to have it run under a different account that has the permissions.

3.    By default, you can upload no more than 4096 KB (4 MB) of data. However there is a workaround for this limitation. You can change the maximum file size by changing the maxRequestLength attribute of the
httpRuntime element in the web.config file. You can also increase the ‘executionTimeout’. By default it is 110 seconds. I would encourage you to experiment with the other attributes of the httpRuntime element.

<configuration>
<system.web>
<httpRuntime
executionTimeout=”200″
maxRequestLength=”8192″
requestLengthDiskThreshold=”256″
useFullyQualifiedRedirectUrl=”false”
minFreeThreads=”8″
minLocalRequestFreeThreads=”4″
appRequestQueueLimit=”5000″
enableKernelOutputCache=”true”
enableVersionHeader=”true”
requireRootedSaveAsPath=”true”
enable=”true”
shutdownTimeout=”90″
delayNotificationTimeout=”5″
waitChangeNotification=”0″
maxWaitChangeNotification=”0″
enableHeaderChecking=”true”
sendCacheControlHeader=”true”
apartmentThreading=”false”/>
</system.web>
</configuration>

References

There are a number of good resources I referred to, for this article. A few of them are:

http://www.wrox.com/WileyCDA/Section/id-292160.html
http://msdn2.microsoft.com/en-US/library/aa479405.aspx
http://msdn2.microsoft.com/en-us/library/system.web.httpfilecollection.aspx

Wednesday, December 30, 2009

Some Sql Server Interview Questions

* Difference between Set and Select
Ans:
1) Set is a ANSI standard for variable assignment.
   Select is a Non-ANSI standard when assigning variables.We can assign only one variable at a time

2) We can assign multiple variable at a time.When assigning from a query that returns more than one value, SET will fail with an error.
   When assigning from a query that returns more than one value, SELECT will assign the last value returned by the query and hide the fact that the query returned

* What is Network Packet Size in SQL
Ans:
NPS(Network Packet Size) is the size of the TDS (tabular data stream) packets used to communicate between your applications and your relational database engine and default packet size is 4 kilobytes and its manily depends on network packet size configuration option.


* How many different locks in SQL SERVER
Ans:
(1)Intent
(2)shared
(3)Update
(4)Exclusive
(5)Schema
(6)Bulk Update

* Diffrence between temp table and table variable
Ans:
(1)Temp Tables are created in the SQL Server TEMPDB database and therefore require more IO resources and locking. Table Variables and Derived Tables are created in memory.

(2)Temp Tables will generally perform better for large amounts of data that can be worked on using parallelism whereas Table Variables are best used for small amounts of data (I use a rule of thumb of 100 or less rows) where parallelism would not provide a significant performance improvement.

(3)You cannot use a stored procedure to insert data into a Table Variable or Derived Table. For example, the following will work: INSERT INTO #MyTempTable EXEC dbo.GetPolicies_sp whereas the following will generate an error: INSERT INTO @MyTableVariable EXEC dbo.GetPolicies_sp.

(4)Derived Tables can only be created from a SELECT statement but can be used within an Insert, Update, or Delete statement.

(5) In order of scope endurance, Temp Tables extend the furthest in scope, followed by Table Variables, and finally Derived Tables.

* What is Cursor
Ans:
  Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis, instead of the typical SQL commands that operate on all the rows in the set at one time. For example, you can use cursor to include a list of all user databases and make multiple operations against each database by passing each database name as a variable

* Write some disadvantage of Cursor
Ans:
  Cursor plays there row quite nicely but although there are some disadvantage of Cursor . Because we know cursor doing roundtrip it will make network line busy and also make time consuming methods. First of all select query gernate output and after that cursor goes one by one so roundtrip happen.Another disadvange of cursor are ther are too costly because they require lot of resources and temporary storage so network is quite busy.

* Can you tell me the difference between DELETE and TRUNCATE commands
Ans:
  Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command.

Thursday, December 24, 2009

How to pad a numeric type column with leading zeros?

Execute the following Microsoft SQL Server T-SQL example scripts to demonstrate SQL padding of numbers and strings with leading and trailing zeros as well as with other designated characters, and techniques
for removing (trim) leading zeros. 



-- SQL Server leading zero - T-SQL padding numbers - lpad tsql - sql pad zero

SELECT ListPrice,

  Padded=RIGHT('0000000000' + CONVERT(VARCHAR,ListPrice), 10)

FROM AdventureWorks2008.Production.Product WHERE ListPrice > 0.0

------------

-- T SQL pad leading zeros - transact sql leading zeros

SELECT ProductID, ReorderPoint = REPLACE(STR(ReorderPoint, 6), SPACE(1), '0')

FROM AdventureWorks2008.Production.Product

/* ProductID            ReorderPoint

      1                 000750

      2                 000750

      3                 000600  */

 ------------

-- SQL Server leading zero - SQL leading zeros - sql server pad leading zero

USE AdventureWorks2008;

DECLARE @Number int = 789

SELECT RIGHT ('000000'+ CAST (@Number AS varchar), 6)

-- 000789

------------

USE AdventureWorks;

-- SQL padding salary pay rate money data type with leading zeroes

-- SQL left pad number - prefix number with zeros - sql server leading zero

-- SQL convert number to text - cast number to varchar string

SELECT EmployeeID,

       Rate,

       PaddedRate = RIGHT(REPLICATE('0',8) + CAST(Rate AS VARCHAR(8)),8)

FROM   HumanResources.EmployeePayHistory
/* Partial results

EmployeeID        Rate              PaddedRate

1                 12.45             00012.45

2                 13.4615           00013.46

3                 43.2692           00043.27

*/


-- SQL zero padding ListPrice money data type - t sql leading zero

-- SQL left pad - T-SQL string concatenation - sql concat

-- SQL convert number to string - pad numeric with zeros

SELECT ProductID,

       ListPrice,

       PaddedListPrice = RIGHT(REPLICATE('0', 8) + CAST(ListPrice AS VARCHAR(8)),8)

FROM Production.Product

/* Results sample

ProductID               ListPrice               PaddedListPrice

965                     742.35                  00742.35

*/


-- SQL month leading zero - sql pad month number with zero

SELECT RIGHT('0' + convert(varchar(2), month(GetDate())), 2)

-- 06
----------

-- trim leading zeros - sql trim leading zeros - remove leading zeros sql

USE AdventureWorks2008;

DECLARE @num  varchar(32)= '00091234560'

SELECT      right(@num, len(@num)+1 - patindex('%[^0]%', @num))

-- 91234560

------------

-- SQL pad numeric data type - SQL pad digits - transact sql leading zeros

-- SQL pad with leading zeroes - append leading zeros - T-SQL top function

-- SQL pad with trailing zeroes - MSSQL append trailing zeros

-- SQL cast money to numeric - cast numeric to string - mssql newid function

SELECT TOP (5)

      ProductName = Name,

      ListPrice = RIGHT(REPLICATE('0', 10)

      + CAST(CAST(ListPrice AS NUMERIC(9,3)) AS VARCHAR) ,10)  

FROM AdventureWorks.Production.Product

ORDER BY NEWID()

/* ProductName                      ListPrice

LL Mountain Frame - Black, 40       000249.790

HL Touring Frame - Yellow, 46       001003.910

Bike Wash - Dissolver               000007.950

Metal Sheet 7                       000000.000

HL Road Frame - Red, 56             001431.500

*/

----------


-- PAD leading zeros function - sql server leading zeros - UDF

USE AdventureWorks2008;

GO

CREATE FUNCTION fnPadNumber

               (@n      DECIMAL(26,2),

                @length TINYINT)

RETURNS VARCHAR(32)

AS

  BEGIN

    RETURN ( replicate('0',@length - len(convert(VARCHAR(32),@n))) +

             convert(VARCHAR(32),@n))

  END

GO


SELECT dbo.fnPadNumber(1234567890.12,16)

-- 0001234567890.12
------------

-- T SQL computed column zero padding - sql generate alphanumeric sequence

USE tempdb; -- SQL Server 2008 T-SQL

CREATE TABLE Celebrity (

  ID           INT    IDENTITY ( 1 , 1 )    PRIMARY KEY,

  CelebrityID  AS 'CEL' + RIGHT('0000' + CAST( ID as varchar),5), -- computed column

  FirstName    VARCHAR(32),

  LastName     VARCHAR(32),

  ModifiedDate DATE    DEFAULT getdate())

GO


INSERT Celebrity

      (FirstName,

       LastName)

VALUES('Jennifer','Aniston'),

      ('Drew','Barrymore'),

      ('Diana','Princess of Wales'),

      ('Tom','Jones'),

      ('Lucille','Ball'),

      ('Frank','Sinatra'),

      ('Elvis','Presley')


SELECT * FROM   Celebrity

GO

-- CelebrityID is zero padded alphanumeric sequence

/* 

ID    CelebrityID       FirstName  LastName          ModifiedDate

1     CEL00001          Jennifer    Aniston          2012-07-04

2     CEL00002          Drew        Barrymore        2012-07-04

3     CEL00003          Diana       Princess of Wales 2012-07-04

4     CEL00004          Tom         Jones             2012-07-04

5     CEL00005          Lucille     Ball              2012-07-04

6     CEL00006          Frank       Sinatra          2012-07-04

7     CEL00007          Elvis       Presley          2012-07-04

*/

-- Cleanup demo

DROP TABLE Celebrity

GO
------------

-- SQL removing leading zeros when no spaces in string - trimming Leading Zeros

USE AdventureWorks2008;

DECLARE @NumberString varchar(16)='000000246'

SELECT REPLACE(LTRIM(REPLACE(@NumberString, '0', ' ')), ' ', '0')

-- 246

------------

-- SQL remove leading zeros - sql trim leading zeros - numeric test

DECLARE @StringWithLeadingZeros    VARCHAR(12) = '000000654321'

SELECT CAST(CAST(@StringWithLeadingZeros AS INT) AS VARCHAR(10))

WHERE ISNUMERIC (@StringWithLeadingZeros)=1

-- 654321

------------

-- LPAD & RPAD string scalar-valued user-defined functions (UDF)

USE AdventureWorks;

GO

-- Left pad string function

CREATE FUNCTION LPAD

               (@SourceString VARCHAR(MAX),

                @FinalLength  INT,

                @PadChar      CHAR(1))

RETURNS VARCHAR(MAX)

AS

  BEGIN

    RETURN

      (SELECT Replicate(@PadChar,@FinalLength - Len(@SourceString)) + @SourceString)

  END

GO


-- T-SQL Test left padding

SELECT LeftPaddedString = dbo.LPAD(Cast(84856 AS VARCHAR),12,'0')

GO

-- 000000084856


-- MSSQL right pad string function

CREATE FUNCTION RPAD

               (@SourceString VARCHAR(MAX),

                @FinalLength  INT,

                @PadChar      CHAR(1))

RETURNS VARCHAR(MAX)

AS

  BEGIN

    RETURN

      (SELECT @SourceString + Replicate(@PadChar,@FinalLength - Len(@SourceString)))

  END

GO


-- Test right padding

SELECT RightPaddedString = dbo.RPAD(Cast(84856 AS VARCHAR),12,'*')

GO

-- 84856*******

----------


-- Padding a money column with leading zeroes - sql convert leading zero

-- SQL convert money data type to string

SELECT PaddedUnitPrice = RIGHT(replicate('0',20) +

                         convert(varchar,UnitPrice,1), 20)

FROM Northwind.dbo.Products

/* Partial results


PaddedUnitPrice

00000000000000018.00

00000000000000019.00

00000000000000010.00

00000000000000022.00

*/


/**************** Zero padding other numeric data ****************/


-- SQL Server 2008 version featuring the LEFT function

-- SQL convert integer to text - convert integer to varchar

USE AdventureWorks2008;

DECLARE @InputNumber int = 522, @OutputLength tinyint = 12

DECLARE @PaddedString char(12)

SET @PaddedString = LEFT( replicate( '0', @OutputLength ),

    @OutputLength - len( @InputNumber ) ) + convert( varchar(12), @InputNumber)

SELECT PaddedNumber=@PaddedString

/* Result


PaddedNumber

000000000522

*/



-- SQL format currency and pad with leading spaces

-- SQL Server lpad to 9 characters

SELECT   TOP (3)  ProductName=Name,

                  Price=   CONVERT(char(9), ListPrice, 1)

FROM Production.Product

WHERE ListPrice > 0.0 ORDER BY Newid()

/*

ProductName                         Price

LL Touring Frame - Blue, 62           333.42

LL Road Seat Assembly                 133.34

Road-250 Red, 58                    2,443.35

*/

------------

-- Padding with zeroes in the middle of string

DECLARE @Number varchar(10)

SET @Number = '99999'

PRINT 'TRK' + REPLICATE('0', 12 - LEN(@Number)) + @Number

SELECT [Zero Padding]='TRK' + REPLICATE('0', 12 - LEN(@Number)) + @Number

-- Result: TRK000000099999


-- Applying the STUFF string function for zero padding

-- SQL convert integer data type to string

DECLARE @SerialNo int, @OutputSize tinyint

SET @OutputSize = 10

SET @SerialNo = 6543

SELECT PaddedSerialNo =  STUFF(replicate('0', @OutputSize),

    @OutputSize - len(@SerialNo)+1, len(@SerialNo), convert(varchar(9),@SerialNo))

-- Result: 0000006543

-- SQL pad integer with 0-s

-- SQL str function - numeric to character conversion

SELECT TOP 5

CAST(replace(str(ProductID,6),' ','0') AS char(6)) AS ProdID

FROM AdventureWorks.Production.Product

ORDER BY Name

/* Results

ProdID

000001

000879

000712

000003

000002

*/


-- SQL pad string with character

-- SQL create function

-- SQL user-defined function

CREATE FUNCTION dbo.fnLeftPadString (

      @Input VARCHAR(255),

      @PadChar CHAR(1),

      @LengthToPad TINYINT

      )

RETURNS VARCHAR(255) AS 

BEGIN

DECLARE @InputLen TINYINT

SET @InputLen = LEN(@Input)

RETURN

   CASE

      WHEN @InputLen < @LengthToPad

      THEN REPLICATE(@PadChar, @LengthToPad - @InputLen) + @Input

      ELSE @Input

   END -- CASE

END -- UDF

GO


-- SQL pad string – left padding - SQL left pad with asterisk

-- SQL check printing - SQL currency formatting

DECLARE @DollarAmount varchar(20)

SET @DollarAmount = '234.40'

SELECT PaddedString='$'+dbo.fnLeftPadString(@DollarAmount, '*', 10)

GO

-- Result: $****234.40


-- SQL currency formatting with asterisk-fill

DECLARE @Amount MONEY

SET @Amount = '3534.40'

SELECT CurrencyFormat = '$' + REPLACE(Convert(char(12),@Amount,1),' ','*')

-- $****3,534.40

SELECT      PaddedProductID =

                  dbo.fnLeftPadString (CONVERT(varchar, ProductID), '0', 6),

            ProductName=Name,

            ListPrice

FROM Production.Product

ORDER BY PaddedProductID

GO


/* Partial results


PaddedProductID         ProductName       ListPrice

000757                  Road-450 Red, 48  1457.99

000758                  Road-450 Red, 52  1457.99

000759                  Road-650 Red, 58  782.99

000760                  Road-650 Red, 60  782.99

000761                  Road-650 Red, 62  782.99

*/

----------

-- Generating tracking numbers

-- SQL pad zeroes

WITH cteSequence(SeqNo)

     AS (SELECT 1

         UNION ALL

         SELECT SeqNo + 1

         FROM   cteSequence

         WHERE  SeqNo < 1000000)

SELECT TOP 100 CAST(('TRK' + REPLICATE('0',

               7 - LEN(CAST(SeqNo AS VARCHAR(6)))) +

               CAST(SeqNo AS VARCHAR(6))) AS VARCHAR(10)) AS TrackingNo

FROM   cteSequence

OPTION (MAXRECURSION 0)

GO

/* Partial results


TrackingNo

TRK0000001

TRK0000002

TRK0000003

TRK0000004

TRK0000005

TRK0000006

TRK0000007

*/

----------

-- SQL server pad

-- SQL str function

-- SQL pad integer

-- SQL left pad

SELECT TOP (4) StaffName=LastName+', '+FirstName,

PaddedEmployeeID = REPLACE(STR(EmployeeID, 6, 0), ' ', '0')

FROM HumanResources.Employee e

INNER JOIN Person.Contact c

      ON e.ContactID = c.ContactID

ORDER BY NEWID()

/* Results


StaffName         PaddedEmployeeID

Dyck, Shelley     000214

Hines, Michael    000039

Ford, Jeffrey     000015

Caron, Rob        000168

*/


-- SQL asterisk padding

-- SQL pad with asterisk

-- SQL right pad

SELECT  TOP ( 2 * 2 )

              AddressID

            , City+REPLICATE('*', 20-len(City)) AS City

            , PostalCode

FROM AdventureWorks.Person.[Address]

WHERE LEN(City) <= 20

ORDER by NEWID()

GO

/*

AddressID   City                          PostalCode

13465       Imperial Beach******    91932

23217       Corvallis***********    97330

18548       Milwaukie***********    97222

24893       Goulburn************    2580

*/

------------

------------

-- SQL left pad any size string Alpha with any length string Beta

------------

-- SQL user-defined function - UDF - scalar-valued string function

-- T-SQL varchar(max)

USE AdventureWorks2008;

GO

CREATE FUNCTION fnMaxPad

               (@SourceString  VARCHAR(MAX),

                @PaddingString VARCHAR(MAX),

                @OutputLength  INT)

RETURNS VARCHAR(MAX)

AS

  BEGIN

    DECLARE  @WorkString VARCHAR(MAX) =

      ISNULL(REPLICATE(@PaddingString,@OutputLength - len(ISNULL(@SourceString,0))),

                            '') + @SourceString

    RETURN RIGHT(@WorkString, @OutputLength)

  END

GO


-- Execute UDF

SELECT TOP ( 5 ) [SQL Padding Demo] =

  dbo.fnMaxPad(CONVERT(VARCHAR,FLOOR(ListPrice)),'_/',21)

FROM     Production.Product

ORDER BY NEWID()

GO

/* Results


SQL Padding Demo

_/_/_/_/_/_/_/2443.00

/_/_/_/_/_/_/_/_/0.00

/_/_/_/_/_/_/_/147.00

/_/_/_/_/_/_/_/_/0.00

_/_/_/_/_/_/_/1003.00

*/

------------

-- SQL left pad unicode string Alpha with any length unicode string Beta

-- MSSQL pad international

-- SQL user-defined function - UDF - scalar-value function

-- T-SQL nvarchar(max)

USE AdventureWorks2008;

GO

CREATE FUNCTION fnMaxPadInternational

               (@SourceString  NVARCHAR(MAX),

                @PaddingString NVARCHAR(MAX),

                @OutputLength  INT)

RETURNS NVARCHAR(MAX)

AS

  BEGIN

    DECLARE  @WorkString NVARCHAR(MAX) =

      ISNULL(REPLICATE(@PaddingString,@OutputLength - len(ISNULL(@SourceString,0))),

                            '') + @SourceString

    

    RETURN RIGHT(@WorkString, @OutputLength)

  END

GO


-- Execute UDF

SELECT TOP ( 5 ) [SQL Padding Demo] =

dbo.fnMaxPadInternational(LEFT(Description,6),'_/',21)

FROM     Production.ProductDescription

ORDER BY NEWID()

GO

/* Results


SQL Padding Demo

/_/_/_/_/_/_/_/ล้อ ที่

/_/_/_/_/_/_/_/Roue d

/_/_/_/_/_/_/_/شوكة ط

/_/_/_/_/_/_/_/Each f

/_/_/_/_/_/_/_/Jeu de

*/

------------
Reference from sqlusa.com

Saturday, December 19, 2009

How to configure SQL Server 2005 to allow remote connections?

To configure SQL Server 2005 to allow remote connections, complete all the following steps.
• Enable remote connections on the instance of SQL Server that you want to connect to from a remote computer.
• Turn on the SQL Server Browser service.
• Configure the firewall to allow network traffic that is related to SQL Server and to the SQL Server Browser service.

Enable remote connections for SQL Server 2005 Express

1. Click Start, point to Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Surface Area Configuration.
2. On the SQL Server 2005 Surface Area Configuration page, click Surface Area Configuration for Services and Connections.
3. On the Surface Area Configuration for Services and Connections page, expand Database Engine, click Remote Connections, click Local and remote connections, click the appropriate protocol to enable for your environment, and then click Apply.
Note Click OK when you receive the following message:
Changes to Connection Settings will not take effect until you restart the Database Engine service.
4. On the Surface Area Configuration for Services and Connections page, expand Database Engine, click Service, click Stop. wait until the MSSQLSERVER service stops, and then click Start to restart the MSSQLSERVER service.

Enable the SQL Server Browser service

1.Click Start, point to Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Surface Area Configuration.
2.On the SQL Server 2005 Surface Area Configuration page, click Surface Area Configuration for Services and Connections.
3.On the Surface Area Configuration for Services and Connections page, click SQL Server Browser, click Automatic for Startup type, and then click Apply.
Note When you click the Automatic option, the SQL Server Browser service starts automatically every time that you start Microsoft Windows.
4.Click Start, and then click OK.

Create exceptions in Windows Firewall

SQL Server 2005 uses an instance ID as part of the path when you install its program files. To create an exception for each instance of SQL Server, you must identify the correct instance ID. To obtain an instance ID, follow these steps:
1. Click Start, point to Programs, point to Microsoft SQL Server 2005, point to Configuration Tools, and then click SQL Server Configuration Manager.
2. In SQL Server Configuration Manager, click the SQL Server Browser service in the right pane, right-click the instance name in the main window, and then click Properties.
3. On the SQL Server Browser Properties page, click the Advanced tab, locate the instance ID in the property list, and then click OK.
To open Windows Firewall, click Start, click Run, type firewall.cpl, and then click OK.
Create an exception for SQL Server 2005 in Windows Firewall
To create an exception for SQL Server 2005 in Windows Firewall, follow these steps:
1. In Windows Firewall, click the Exceptions tab, and then click Add Program.
2. In the Add a Program window, click Browse.
3. Click the C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\sqlservr.exe executable program, click Open, and then click OK.
Note The path may be different depending on where SQL Server 2005 is installed. MSSQL.1 is a placeholder for the instance ID that you obtained in step 3 of the previous procedure.
4. Repeat steps 1 through 3 for each instance of SQL Server 2005 that needs an exception.
Create an exception for the SQL Server Browser service in Windows Firewall
To create an exception for the SQL Server Browser service in Windows Firewall, follow these steps:
1. In Windows Firewall, click the Exceptions tab, and then click Add Program.
2. In the Add a Program window, click Browse.
3. Click the C:\Program Files\Microsoft SQL Server\90\Shared\sqlbrowser.exe executable program, click Open, and then click OK.

---
Hope this helps everyone.

Blog Archive

Ideal SQL Query For Handling Error & Transcation in MS SQL

BEGIN TRY BEGIN TRAN --put queries here COMMIT; END TRY BEGIN CATCH IF @@TRANCOUNT>0 BEGIN SELECT @@ERROR,ERRO...