European Windows 2012 Hosting BLOG

BLOG about Windows 2012 Hosting and SQL 2012 Hosting - Dedicated to European Windows Hosting Customer

SQL Server 2016 Hosting - HostForLIFE.eu :: How to Use SQL Script to Identify Blocking Chain

clock August 20, 2015 07:16 by author Rebecca

In this article, you will play around with some SQL Script to identify blocking behaviour. The most basic script that I have been using and used by many DBA will include Activity Monitor, sp_who2, sysprocesses etc.

Recently, I saw a script written by one person:

SELECT * FROM sys.dm_os_waiting_tasks
WHERE blocking_session_id IS NOT NULL
GO

This will shows the rows like:

This is so cool because I know who is waiting for whom. In the above image 53 is waiting for 68. While 79 is waiting for 53. This was a cool way to look at things. Sure, you wanted to show the same data in slightly different way using T-SQL. So, I wrote a Blocking Tree TSQL script:

SET NOCOUNT ON
GO
SELECT SPID, BLOCKED, REPLACE (REPLACE (T.TEXT, CHAR(10), ' '), CHAR (13), ' ' ) AS BATCH
INTO #T
FROM sys.sysprocesses R CROSS APPLY sys.dm_exec_sql_text(R.SQL_HANDLE) T
GO
WITH BLOCKERS (SPID, BLOCKED, LEVEL, BATCH)
AS
(
SELECT SPID,
BLOCKED,
CAST (REPLICATE ('0', 4-LEN (CAST (SPID AS VARCHAR))) + CAST (SPID AS VARCHAR) AS VARCHAR (1000)) AS LEVEL,
BATCH FROM #T R
WHERE (BLOCKED = 0 OR BLOCKED = SPID)
AND EXISTS (SELECT * FROM #T R2 WHERE R2.BLOCKED = R.SPID AND R2.BLOCKED <> R2.SPID)
UNION ALL
SELECT R.SPID,
R.BLOCKED,
CAST (BLOCKERS.LEVEL + RIGHT (CAST ((1000 + R.SPID) AS VARCHAR (100)), 4) AS VARCHAR (1000)) AS LEVEL,
R.BATCH FROM #T AS R
INNER JOIN BLOCKERS ON R.BLOCKED = BLOCKERS.SPID WHERE R.BLOCKED > 0 AND R.BLOCKED <> R.SPID
)
SELECT N'    ' + REPLICATE (N'|         ', LEN (LEVEL)/4 - 1) +
CASE WHEN (LEN(LEVEL)/4 - 1) = 0
THEN 'HEAD -  '
ELSE '|------  ' END
+ CAST (SPID AS NVARCHAR (10)) + N' ' + BATCH AS BLOCKING_TREE
FROM BLOCKERS ORDER BY LEVEL ASC
GO
DROP TABLE #T
GO

The output would look like:

That's a simple way to look at the same Blocking data inside SSMS.

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



HostForLIFE.eu Launches Umbraco 7.2.8 Hosting

clock August 19, 2015 06:57 by author Peter

HostForLIFE.eu, a leading web hosting provider, has leveraged its gold partner status with Microsoft to launch its latest Umbraco 7.2.8 Hosting support

HostForLIFE.eu, a leading Windows web hosting provider with innovative technology solutions and a dedicated professional services team, today announced the support for Umbraco 7.2.8 hosting plan due to high demand of Umbraco users in Europe. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam (NL), London (UK), Paris (FR), Frankfurt (DE) and Seattle (US) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. HostForLIFE Umbraco hosting plan starts from just as low as €3.00/month only and this plan has supported ASP.NET 4.5, ASP.NET MVC 5/6 and SQL Server 2012/2014.

Umbraco 7.2.8 is a fully-featured open source content management system with the flexibility to run anything from small campaign or brochure sites right through to complex applications for Fortune 500's and some of the largest media sites in the world. Umbraco was sometimes unable to read the umbraco.config file, making Umbraco think it had no content and showing a blank page instead (issue U4-6802), this is the main issue fixed in this release. This affects people on 7.2.5 and 7.2.6 only. 7.2.8 also fixes a conflict with Courier and some other packages.

Umbraco 7.2.8 Hosting is strongly supported by both an active and welcoming community of users around the world, and backed up by a rock-solid commercial organization providing professional support and tools. Umbraco 7.2.8 can be used in its free, open-source format with the additional option of professional tools and support if required. Not only can you publish great multilingual websites using Umbraco 7.2.8 out of the box, you can also build in your chosen language with our multilingual back office tools.

Further information and the full range of features Umbraco 7.2.8 Hosting can be viewed here: http://hostforlife.eu/European-Umbraco-728-Hosting

About HostForLIFE.eu

HostForLIFE.eu is an European Windows Hosting Provider which focuses on the Windows Platform only. HostForLIFE.eu deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

HostForLIFE.eu is awarded Top No#1 SPOTLIGHT Recommended Hosting Partner by Microsoft (see http://www.asp.net/hosting/hostingprovider/details/953). Their service is ranked the highest top #1 spot in several European countries, such as: Germany, Italy, Netherlands, France, Belgium, United Kingdom, Sweden, Finland, Switzerland and other European countries. Besides this award, they have also won several awards from reputable organizations in the hosting industry and the detail can be found on their official website.



SQL Server 2016 Hosting - HostForLIFE.eu :: How to Find Corrupt Records of The Pages

clock August 10, 2015 06:00 by author Rebecca

SQL Server database files are organized in 8KB (8192 bytes) chunks, called pages. When we create the first row in a table, SQL Server allocates an 8KB page to store that row. Similarly every row in every table ends up being stored in a page.


Say one of the pages in your table is corrupt and while repairing the corrupt pages, you may eventually end up loosing some data. You may want to find out which records are on the page. To do so, use the following undocumented T-SQL %%physloc%% virtual column:

USE AdventureWorks2014
GO
SELECT *, %%physloc%% AS physloc
FROM Person.AddressType
ORDER BY physloc;

As you can see, the last column represents the record location. However the hexadecimal value is not in a human readable format. To read the physical record of each row in a human readable format, use the following query:

SELECT *
FROM Person.AddressType
CROSS APPLY sys.fn_PhysLocCracker(%%physloc%%)


The sys.fun_PhysLocCracker function takes the %%physloc%% and represents a human readable format fileid, pageid i.e. 880 and record number on the page 880.

If you are interested in knowing what’s inside the sys.fn_PhysLocCracker function, use sp_helptext as follows:

EXEC sp_helptext 'sys.fn_PhysLocCracker'
which display the definition of sys.fn_PhysLocCracker
-------------------------------------------------------------------------------
-- Name: sys.fn_PhysLocCracker
--
-- Description:
--    Cracks the output of %%physloc%% virtual column
--
-- Notes:
-------------------------------------------------------------------------------
create function sys.fn_PhysLocCracker (@physical_locator binary (8))
returns @dumploc_table table
(
    [file_id]    int not null,
    [page_id]    int not null,
    [slot_id]    int not null
)
as
begin
    declare @page_id    binary (4)
    declare @file_id    binary (2)
    declare @slot_id    binary (2)
    -- Page ID is the first four bytes, then 2 bytes of page ID, then 2 bytes of slot
    --
    select @page_id = convert (binary (4), reverse (substring (@physical_locator, 1, 4)))
    select @file_id = convert (binary (2), reverse (substring (@physical_locator, 5, 2)))
    select @slot_id = convert (binary (2), reverse (substring (@physical_locator, 7, 2)))
  
    insert into @dumploc_table values (@file_id, @page_id, @slot_id)
    return
end

The undocumented sys.fn_PhysLocCracker works on SQL Server 2008 and above.

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

 



AngularJS Hosting - HostForLIFE.eu :: Learn How to Make a Directive to Allow only Numbers using AngularJs

clock August 5, 2015 08:36 by author Peter

Before reading this text there is only one prerequisite condition; you must know how to create a directive in AngularJs and why we need to create them. First of all you need to add AngularJs and jQuery to your page, similar to here:
<head runat="server"> 
<title></title> 
<script src="angular.min.js"></script> 
<script src="jquery-1.11.1.min.js"></script> 
</head>

You will either download them from my code that is available at the start of this article or you can download from their official websites. Now i'm simply adding a textbox wherever i would like to allow only numbers using an AngularJs directive.
<body> 
<form ng-app="app" id="form1" runat="server"> 
<div>
<h3> Demo to Allow Numbers Only </h3>
<hr /> 
Provide Your Mobile Number: <input type="text" 
name="MobileNumber" 
class="form-control" 
allow-only-numbers /> 
<hr /> 
</div> 
</form> 
</body>

Now it's time for Angular code. Write the following code:
<script> 
var app = angular.module('app', []); 
app.directive('allowOnlyNumbers', function () { 
return { 
restrict: 'A', 
link: function (scope, elm, attrs, ctrl) { 
elm.on('keydown', function (event) { 
if (event.which == 64 || event.which == 16) { 
// to allow numbers 
return false; 
} else if (event.which >= 48 && event.which <= 57) { 
// to allow numbers 
return true; 
} else if (event.which >= 96 && event.which <= 105) { 
// to allow numpad number 
return true; 
} else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) { 
// to allow backspace, enter, escape, arrows 
return true; 
} else { 
event.preventDefault(); 
// to stop others 
return false; 

}); 


}); 
</script>


Here I first created a module named "app". The module creation is a necessary part if you wish to use Angular. This module is added to the HTML page using the ng-app directive. Then I created the directive with the name "allowOnlyNumbers". If you're making any kind of directive using AngularJs then you need to continually check that the name is provided using "-" in your HTML page and these dashes "-" are replaced by capital letters in the Angular code. Since I had applied this directive to the attribute of the textbox I had restricted this directive using "A" for Attribute.

I had applied this directive on the keydown event of the textbox. After those varied conditions are applied to the ASCII values of the keys to permit or to prevent them. In any case our ASCII values aren't allowed. event.preventDefault() will take away that character and can revert to the previous value. But still I had the intense problem of all the characters that were entered by pressing the shift + key weren't removed by this code, therefore I used easy jQuery at the beginning of the code to help prevent this situation.
var $input = $(this); 
var value = $input.val(); 
value = value.replace(/[^0-9]/g, '') 
$input.val(value); 


Then, write the following code:
app.directive('allowOnlyNumbers', function () { 
return { 
restrict: 'A', 
link: function (scope, elm, attrs, ctrl) { 
elm.on('keydown', function (event) { 
var $input = $(this); 
var value = $input.val(); 
value = value.replace(/[^0-9]/g, '') 
$input.val(value); 
if (event.which == 64 || event.which == 16) { 
    // to allow numbers 
    return false; 
} else if (event.which >= 48 && event.which <= 57) { 
    // to allow numbers 
    return true; 
} else if (event.which >= 96 && event.which <= 105) { 
    // to allow numpad number 
    return true; 
} else if ([8, 13, 27, 37, 38, 39, 40].indexOf(event.which) > -1) { 
    // to allow backspace, enter, escape, arrows 
    return true; 
} else { 
    event.preventDefault(); 
    // to stop others 
    //alert("Sorry Only Numbers Allowed"); 
    return false; 

}); 


}); 


Output:
Now our application is made and we will check the output. On running the application an easy textbox are going to be shown wherever only numbers are allowed.

If you press the numbers from anywhere within the key, they will be allowed however all the other characters won't be allowed to exist, although they're special characters.

HostForLIFE.eu AngularJS Hosting

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



HostForLIFE.eu Launches nopCommerce 3.60 Hosting

clock July 14, 2015 10:53 by author Peter

HostForLIFE.eu, a leading web hosting provider, has leveraged its gold partner status with Microsoft to launch its latest NopCommerce 3.60 Hosting support

European Recommended Windows and ASP.NET Spotlight Hosting Partner, HostForLIFE.eu, has announced the availability of new hosting plans that are optimized for the latest update of the NopCommerce 3.60 hosting technology.

HostForLIFE.eu supports NopCommerce 3.60 hosting on their latest Windows Server and this service is available to all their new and existing customers. nopCommerce 3.60 is a fully customizable shopping cart. It's stable and highly usable. nopCommerce is an open source ecommerce solution that is ASP.NET (MVC) based with a MS SQL 2008 (or higher) backend database. Their easy-to-use shopping cart solution is uniquely suited for merchants that have outgrown existing systems, and may be hosted with your current web hosting. It has everything you need to get started in selling physical and digital goods over the internet.

HostForLIFE.eu Launches nopCommerce 3.60 Hosting

nopCommerce 3.60 is a fully customizable shopping cart. nopCommerce 3.60 provides new clean default theme. The theme features a clean, modern look and a great responsive design. The HTML have been refactored, which will make the theme easier to work with and customize , predefined (default) product attribute values. They are helpful for a store owner when creating new products. So when you add the attribute to a product, you don't have to create the same values again , Base price (PAngV) support added. Required for German/Austrian/Swiss users, “Applied to manufacturers” discount type and Security and performance enhancements.

HostForLIFE.eu hosts its servers in top class data centers that is located in Amsterdam, London, Paris, Seattle (US) and Frankfurt (Germany) to guarantee 99.9% network uptime. All data center feature redundancies in network connectivity, power, HVAC, security, and fire suppression. All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee.

All hosting plans from HostForLIFE.eu include 24×7 support and 30 days money back guarantee. The customer can start hosting their NopCommerce 3.60 site on their environment from as just low €3.00/month only. HostForLIFE.eu is a popular online Windows based hosting service provider catering to those people who face such issues. The company has managed to build a strong client base in a very short period of time. It is known for offering ultra-fast, fully-managed and secured services in the competitive market. Their powerful servers are specially optimized and ensure NopCommerce 3.60 performance.

For more information about this new product, please visit http://hostforlife.eu/European-nopCommerce-36-Hosting



SQL Server 2016 Hosting - HostForLIFE.eu :: How to Use THROW to Handle Error in SQL Server

clock June 29, 2015 06:03 by author Rebecca

Today, I'm gonna talk about how to handle error in SQL Server using THROW. In versions prior to SQL Server 2012, you can use @@RAISE_ERROR to generate error messages dynamically or using the sys.messages catalog.

Consider the following example:

SELECT ROUND(800.0, -3)

On executing this statement, you get the following error:

This error is caused by the value does not fit into the decimal data type.

You can use @@RAISERROR to raise a message:

BEGIN TRY
SELECT ROUND(800.0, -3)
END TRY
BEGIN CATCH
DECLARE @ErrorMsg nvarchar(1000), @Severity int
SELECT @ErrorMsg = ERROR_MESSAGE(),
@Severity = ERROR_SEVERITY()
RAISERROR (@ErrorMsg, @Severity, 1)
END CATCH

Note: The old syntax of RAISERROR syntax specifying the error number and message number got deprecated (RAISEERROR 50005 ‘Exception Occurred’). Instead the new syntax RAISEERROR(50005, 10, 1) allowed you to specify the messageid, severity and state). For new applications use THROW.

However in SQL Server 2012 and above, there’s a better way to this without much efforts, using THROW. Consider the following code:

BEGIN TRY
SELECT ROUND(800.0, -3)
END TRY
BEGIN CATCH
THROW
END CATCH

As you can see, with just one word THROW, we were able to handle the error with grace and get a result too.

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server 2016 Hosting - HostForLIFE.eu :: How to Detect a Table Has A Primary Key or Foreign Key

clock June 25, 2015 05:46 by author Rebecca

If you want to know if a table has a primary key or foreign key, you can find out this in many ways. Just follow these steps on this tutorial.

Step 1

First, let us create these a table using code below:

CREATE TABLE product_master
(
prod_id INT PRIMARY KEY,
prod_name VARCHAR(100),
price DECIMAL(12,2)
)
GO
CREATE TABLE product_details
(
prod_id INT,
sales_date DATETIME,
sales_qty INT,
sales_amount DECIMAL(16,2)
)
GO
CREATE TABLE company_master
(
compnay_id INT,
company_name VARCHAR(100),
address VARCHAR(1000)
)
GO

Step 2

Now, let us create foreign key:

ALTER TABLE product_details ADD CONSTRAINT ck_item FOREIGN KEY(prod_id) REFERENCES product_master(prod_id)

Step 3

If you want to check if a table has a primary key, you can use the following methods:

1. Use sp_pkeys system stored procedure

The result will be:

 

 

2. Use Objectproperty function

SELECT
*
FROM
INFORMATION_SCHEMA.TABLES
WHERE
OBJECTPROPERTY(OBJECT_ID(TABLE_NAME),'TABLEHASPRIMARYKEY')=1 AND
TABLE_TYPE='BASE TABLE'
ORDER BY
TABLE_NAME

Step 4

If you want to check if a table has a foreign key, you can use the following method:

SELECT
*
FROM
INFORMATION_SCHEMA.TABLES
WHERE
OBJECTPROPERTY(OBJECT_ID(TABLE_NAME),'TABLEHASFOREIGNKEY')=1 AND
TABLE_TYPE='BASE TABLE'
ORDER BY
TABLE_NAME

And the result is:

Step 5

If you want to check for the tables that do not have primary key or foreign key, you can use the following method:

SELECT
*
FROM
INFORMATION_SCHEMA.TABLES
WHERE
OBJECTPROPERTY(OBJECT_ID(TABLE_NAME),'TABLEHASPRIMARYKEY')=0 AND
OBJECTPROPERTY(OBJECT_ID(TABLE_NAME),'TABLEHASFOREIGNKEY')=0 AND
TABLE_TYPE='BASE TABLE'
ORDER BY
TABLE_NAME

This is the result:

Easy right?

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server 2016 Hosting - HostForLIFE.eu :: How to Automate Restore All Transaction log Backup Files ?

clock June 23, 2015 08:13 by author Peter

On one of my servers we had to recover ten databases using last night's full backup and all subsequent log backups. Therefore within the middle of the night it had been about to be huge challenge to manually choose each log backup file to restore. So wrote this script to create commands to restore log backup files which can be then run in an exceedingly query window. Please follow the steps below to use the script.

1. Set the database name to the variable @dbname
2. Copy all the transaction log backups to a new directory. You'll prefer to begin copying the files. That  were taken a couple of minutes before the full backup was taken. You'll choose to copy the last file you wish to be restored based on the recovery point of your time.
3.  In the following line set the directory where you copied the log backup files to.

insert into #dir
exec xp_cmdshell 'dir "C:\Backup\Adventure*.trn" /b'

4. The below code will set the directory to where the log backup files have been copied.
SET @cmd='use master; RESTORE LOG ['+@dbname+'] FROM  DISK =
    N''C:\Backup\'+@filename+''' WITH  FILE = 1,  NORECOVERY,  NOUNLOAD,  STATS = 10'
select (@cmd)

5. Now, Copy the output which should have the RESTORE commands and run them in a new query window.
6. Run the following command to bring the database out of restoring state.

RESTORE DATABASE dbname WITH RECOVERY


############################################################################
use master
set nocount on
DECLARE @filename varchar(2000), @cmd varchar(8000), @dbname varchar(100)

-----------------------Enter the Database name in the next line
SET @dbname='New'

IF  EXISTS (SELECT name FROM tempdb.sys.tables WHERE name like '#dir%')
begin
   DROP table #dir
end
create table #dir (filename varchar(1000))

-----------------------Enter the path to TRN File in the xp_cmdshell line
insert into #dir
exec xp_cmdshell 'dir "C:\Backup\Adventure*.trn" /b'

delete from #dir where filename is null
DECLARE filecursor CURSOR FOR
select * from #dir order by filename asc

OPEN filecursor
FETCH NEXT FROM filecursor INTO @filename

WHILE @@FETCH_STATUS = 0
BEGIN
 SET @cmd='use master; RESTORE LOG ['+@dbname+'] FROM  DISK = N''C:\Backup\'+@filename+''' WITH  FILE = 1,  NORECOVERY,  NOUNLOAD,  STATS = 10'
 print @cmd
FETCH NEXT FROM filecursor INTO @filename
END
CLOSE filecursor 
DEALLOCATE filecursor
drop table #dir

############################################################################

HostForLIFE.eu SQL Server 2016 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server 2014 Hosting - HostForLIFE.eu :: How to Get CONSTRAINT of Database or Table

clock June 22, 2015 05:51 by author Rebecca

In this post, I am going to explain how you can list all CONSTRAINT of database or table in SQl Server. When you are working on database sometimes you need to check or get the CONSTRAINT on database or table. Using below given query we can get the CONSTRAINT of table or database quickly.

Step 1

Query to list all fields of sys.objects:
SELECT * FROM sys.objects WHERE type_desc LIKE '%CONSTRAINT'
Using above query we get all fields of sys.objects.

Step 2

To get only Constraint name, tabe name and Constraint type I use the refined query mention below:
SELECT OBJECT_NAME(object_id) AS ConstraintName,
SCHEMA_NAME(schema_id) AS SchemaName,
OBJECT_NAME(parent_object_id) AS TableName,
type_desc AS ConstraintType
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT'

Step 3

To get the Constraint detail of a particular table use the below given query:
SELECT OBJECT_NAME(object_id) AS ConstraintName,
SCHEMA_NAME(schema_id) AS SchemaName,
type_desc AS ConstraintType
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT' AND OBJECT_NAME(parent_object_id)='Student_Register'

The last, replace the Student_Register with your database table name.

HostForLIFE.eu SQL Server 2014 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



SQL Server 2016 Hosting - HostForLIFE.eu :: How to Save Picture in SQL Server with ASP.NET ?

clock June 18, 2015 07:18 by author Peter

This article will explains the way to Save pictures In Sqlserver database In Asp.Net using File upload control. I am upload the pictures using FileUpload control and saving or storing them in SQL Server database in ASP.NET with C# and VB.NET.

Database has a table named pictures with 3 columns:
1. ID Numeric Primary key with Identity Increment.
2. ImageName Varchar to store Name of picture.
3. Image column to store image in binary format.

After uploading and saving pictures in database, pics are displayed in GridView. And here is the HTML markup:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtName" runat="server" Width="95px">
</asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Label ID="lblMessage" runat="server">
</asp:Label>
<asp:Button ID="btnUpload" runat="server"
            OnClick="btnUpload_Click" Text="Upload"/>
</div>
</form>

Now, write the following code in Click Event of Upload Button:
protected void btnUpload_Click(object sender, EventArgs e)
{
 string strImageName = txtName.Text.ToString();
 if (FileUpload1.PostedFile != null &&
     FileUpload1.PostedFile.FileName != "")
  {
   byte[] imageSize = new byte
                 [FileUpload1.PostedFile.ContentLength];
  HttpPostedFile uploadedImage = FileUpload1.PostedFile;
  uploadedImage.InputStream.Read
     (imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);

 // Create SQL Connection
  SqlConnection con = new SqlConnection();
  con.ConnectionString = ConfigurationManager.ConnectionStrings
                         ["ConnectionString"].ConnectionString;

 // Create SQL Command

 SqlCommand cmd = new SqlCommand();
 cmd.CommandText = "INSERT INTO Images(ImageName,Image)" +
                   " VALUES (@ImageName,@Image)";
 cmd.CommandType = CommandType.Text;
 cmd.Connection = con;

 SqlParameter ImageName = new SqlParameter
                     ("@ImageName", SqlDbType.VarChar, 50);
 ImageName.Value = strImageName.ToString();
 cmd.Parameters.Add(ImageName);

 SqlParameter UploadedImage = new SqlParameter
               ("@Image", SqlDbType.Image, imageSize.Length);
 UploadedImage.Value = imageSize;
 cmd.Parameters.Add(UploadedImage);
 con.Open();
 int result = cmd.ExecuteNonQuery();
 con.Close();
 if (result > 0)
 lblMessage.Text = "File Uploaded";
 GridView1.DataBind();
 }
}


VB.NET Code

Protected Sub btnUpload_Click
(ByVal sender As Object, ByVal e As EventArgs)

    Dim strImageName As String = txtName.Text.ToString()
    If FileUpload1.PostedFile IsNot Nothing AndAlso
       FileUpload1.PostedFile.FileName <> "" Then

        Dim imageSize As Byte() = New Byte
          (FileUpload1.PostedFile.ContentLength - 1) {}

        Dim uploadedImage__1 As HttpPostedFile =
                                 FileUpload1.PostedFile

        uploadedImage__1.InputStream.Read(imageSize, 0,
              CInt(FileUpload1.PostedFile.ContentLength))
       
        ' Create SQL Connection
        Dim con As New SqlConnection()
        con.ConnectionString =
                 ConfigurationManager.ConnectionStrings
                  ("ConnectionString").ConnectionString
       
        ' Create SQL Command
       
        Dim cmd As New SqlCommand()
        cmd.CommandText = "INSERT INTO Images
           (ImageName,Image) VALUES (@ImageName,@Image)"
        cmd.CommandType = CommandType.Text
        cmd.Connection = con
       
        Dim ImageName As New SqlParameter
                  ("@ImageName", SqlDbType.VarChar, 50)
        ImageName.Value = strImageName.ToString()
        cmd.Parameters.Add(ImageName)
       
        Dim UploadedImage__2 As New SqlParameter
            ("@Image", SqlDbType.Image, imageSize.Length)
        UploadedImage__2.Value = imageSize
        cmd.Parameters.Add(UploadedImage__2)
        con.Open()
        Dim result As Integer = cmd.ExecuteNonQuery()
        con.Close()
        If result > 0 Then
            lblMessage.Text = "File Uploaded"
        End If
        GridView1.DataBind()
    End If
End Sub

HostForLIFE.eu SQL Server 2016 Hosting

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in