European Windows 2019 Hosting BLOG

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

SQL Server 2016 Hosting - HostForLIFE.eu :: How to Remove DataBase In Sql Server Without Using Wizard?

clock June 21, 2016 22:08 by author Peter

Today, I will explain you about how to Remove DataBase In Sql Server Without Using Wizard. This system stored procedure will helps you.
exec sp_dbremove 'dataBaseName'


The following is the entire script of the stored procedure:
USE [TMS] 
GO 
/****** Object:  StoredProcedure [sys].[sp_dbremove]    Script Date: 08-12-2014 22:09:09 ******/ 
SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 
ALTER procedure [sys].[sp_dbremove] --- 1996/04/08 00:00 
    @dbname sysname = null, 
    @dropdev varchar(10) = null 
as 
    declare @dbid int 
    declare @devname sysname 
    declare @physname varchar(255) 
 
    if @dbname is null 
    begin 
        raiserror(15131,-1,-1) 
        return(1) 
    end 
 
    if lower(@dropdev) <> 'dropdev' and @dropdev is not null 
    begin 
        raiserror(15131,-1,-1) 
        return(1) 
    end 
 
    -- You must be SA to execute this sproc. 
    if (not (is_srvrolemember('sysadmin') = 1)) 
    begin 
        raiserror(15247,-1,-1) 
        return(1) 
    end 
 
    -- Make sure not trying to remove within a transaction. 
    set implicit_transactions off 
    if @@trancount > 0 
    begin 
        raiserror(15002,-1,-1,'sys.sp_dbremove') 
        return(1) 
    end 
 
    -- Check to see if database exists. 
    select @dbid = dbid from master.dbo.sysdatabases where name=@dbname 
    if @dbid is null 
    begin 
        raiserror(15010,-1,-1,@dbname) 
        return(1) 
    end 
 
    -- Make sure no one is in the db. 
    if (select count(*) from master.dbo.sysprocesses where dbid = @dbid) > 0 
    begin 
        raiserror(15069,-1,-1) 
        return (1) 
    end 
 
    -- Note: database @dbname may not exist anymore 
    -- If invoke gets error, exception will abort this proc. 
    EXEC %%DatabaseRef(Name = @dbname).SetSuspect(Value = 1) 
 
    declare @dropCmd nvarchar(max) 
 
    select @dropCmd = 'drop database ' + quotename(@dbname) 
    exec (@dropCmd) 
    raiserror(15458,-1,-1) 
 
    return(0)   -- sp_dbremove 

HostForLIFE.eu SQL 2016 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



SQL Server 2016 Hosting - HostForLIFE.eu :: How to Calculate or Find median in SQL Server?

clock June 16, 2016 21:20 by author Peter

Today, with this post we explain that how to calculate median in SQL Server or function to find median in SQL Server. Before we calculate/find median in sql server first we understand the what is the median and formula to calculate the median in sql server.

Median means denoting or relating to a value or quality lying at the midpoint of a frequency distribution of observed values or quantities, such that there is an equal probability or falling or below it. To calculate or Find median grou by in SQL Server click here Calculate median group by in SQL Server. For ex: supposed to find the median of bellows values like:
{1,2,3,4,5} then the median is equal 3
{1,2,5,10} then the median is equal 3.5
{1,5,8,7} then median is equal 6

So how to calculate median in SQL Server query, below is the query to find the median

Query:
SELECT CONVERT(FLOAT,
(
(SELECT MAX(Score) FROM
(SELECT TOP 50 PERCENT Score FROM Demo ORDER BY Score ASC) AS BottomHalf))
+ CONVERT(FLOAT,
(SELECT MIN(Score) FROM
(SELECT TOP 50 PERCENT Score FROM Demo ORDER BY Score DESC) AS TopHalf)
) / 2) AS Median

HostForLIFE.eu SQL 2016 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



SQL Server 2016 Hosting - HostForLIFE.eu :: How to Calculate or Find median in SQL Server?

clock June 16, 2016 21:20 by author Peter

Today, with this post we explain that how to calculate median in SQL Server or function to find median in SQL Server. Before we calculate/find median in sql server first we understand the what is the median and formula to calculate the median in sql server.

Median means denoting or relating to a value or quality lying at the midpoint of a frequency distribution of observed values or quantities, such that there is an equal probability or falling or below it. To calculate or Find median grou by in SQL Server click here Calculate median group by in SQL Server. For ex: supposed to find the median of bellows values like:
{1,2,3,4,5} then the median is equal 3
{1,2,5,10} then the median is equal 3.5
{1,5,8,7} then median is equal 6

So how to calculate median in SQL Server query, below is the query to find the median

Query:
SELECT CONVERT(FLOAT,
(
(SELECT MAX(Score) FROM
(SELECT TOP 50 PERCENT Score FROM Demo ORDER BY Score ASC) AS BottomHalf))
+ CONVERT(FLOAT,
(SELECT MIN(Score) FROM
(SELECT TOP 50 PERCENT Score FROM Demo ORDER BY Score DESC) AS TopHalf)
) / 2) AS Median

HostForLIFE.eu SQL 2016 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



HostForLIFE.eu Proudly Launches ASP.NET Core 1.0 RC2 Hosting

clock June 4, 2016 00:47 by author Peter

HostForLIFE.eu was established to cater to an underserved market in the hosting industry; web hosting for customers who want excellent service. HostForLIFE.eu - a cheap, constant uptime, excellent customer service, quality, and also reliable hosting provider in advanced Windows and ASP.NET technology. HostForLIFE.eu proudly announces the availability of the ASP.NET Core 1.0 RC2 hosting in their entire servers environment.

ASP.NET is Microsoft's dynamic website technology, enabling developers to create data-driven websites using the .NET platform and the latest version is 5 with lots of awesome features. ASP.NET Core 1.0 RC2 is a lean .NET stack for building modern web apps. Microsoft built it from the ground up to provide an optimized development framework for apps that are either deployed to the cloud or run on-premises. It consists of modular components with minimal overhead.

A key change that occurred between RC1 and RC2 is the introduction of the .NET command-line interface.  This tool replaces the dnvm, dnx, and dnu utilities with a single tool that handles the responsibilities of these tools. In RC1 an ASP.NET application was a class library that contained a Startup.cs class. When the DNX toolchain run your application ASP.NET hosting libraries would find and execute the Startup.cs, booting your web application. Whilst the spirit of this way of running an ASP.NET Core application still exists in RC2, it is somewhat different. As of RC2 an ASP.NET Core application is a .NET Core Console application that calls into ASP.NET specific libraries. What this means for ASP.NET Core apps is that the code that used to live in the ASP.NET Hosting libraries and automatically run your startup.cs now lives inside a Program.cs.

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. The customers can start hosting their ASP.NET Core 1.0 RC2 site on their environment from as just low €3.00/month only.

HostForLIFE.eu is a popular online ASP.NET 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.

HostForLIFE.eu offers the latest European ASP.NET Core 1.0 RC2 hosting installation to all their new and existing customers. The customers can simply deploy their ASP.NET Core 1.0 RC2 website via their world-class Control Panel or conventional FTP tool. HostForLIFE.eu is happy to be offering the most up to date Microsoft services and always had a great appreciation for the products that Microsoft offers.

Further information and the full range of features ASP.NET Core 1.0 RC2 Hosting can be viewed here http://hostforlife.eu



SQL Server 2012 Hosting - HostForLIFE.eu :: Auto Identity Column Value Jump Error in SQL Server 2012

clock June 1, 2016 18:50 by author Peter

From SQL Server 2012 version, when SQL Server instance is restarted, then table's Identity value is jumped and the actual jumped value depends on identity column data type. If it's integer (int) data type, then jump value is a thousand and if huge integer (bigint), then jump value is ten thousand. From our application point of view, this increment isn't acceptable for all the business cases especially once the value shows to the client. this is the special case/issue ships with only SQL Server 2012 and older versions don't have any such issue.

A few days ago, our QA Engineer claims that one of our table's identity column jumped ten thousand. Which means the last identity value of that table was 2200 now it's 12001. In our business logic is like that the value shows to the client and it will not be accepted by the client. So we must solve the issue.
Using the Code

The first time, we all are surprised and confused on how it's possible? we usually don't insert any value in identity column (insert value to identity column is possible). The identity value is maintained by SQL Server itself. one of our core team members started investigation the issue and found out the solution. Now, i want to elaborate the issue and solution that was found out by my colleague.

Now, you need to setup SQL Server 2012 and create a test database. Then create a table with auto identity column with the following code:
create table MyTestTable(Id int Identity(1,1), Name varchar(255));

Now insert 2 rows there:
insert into MyTestTable(Name) values ('Mr.Tom');
insert into MyTestTable(Name) values ('Mr.Jackson');

You see the result:
SELECT Id, Name FROM MyTestTable;

The result is as expected. Now just restart your SQL Server service. There are various ways in which you can do it. We did it from SQL Server management studio.

Now, insert another 2 rows to the same table again:
insert into MyTestTable(Name) values ('Mr.Tom2');
insert into MyTestTable(Name) values ('Mr.Jackson2');

Now, you can see the result:
SELECT Id, Name FROM MyTestTable;


Now you see that after restarting the SQL Server 2012 instance, then identity value starts with 1002. It means it jumped 1000. Previously, I said that we also see if the data type of that identity column is bigint, then it will jump 10000.


Microsoft declares it is a feature rather than a bug and in many scenarios it would be helpful. But in our case, it would not be acceptable because that number is shown to the client and the client will be surprised to see that new number after jump and the new number depends on how many times SQL Server is restarted. If it is not visible to the client, then it might be acceptable so that the number is used internally.
Solutions

If we are not interested in this so called feature, then we can do two things to stop that jump.
    Using Sequence
  Register -t272 to SQL Server Startup Parameter

Using Sequence
First, we need to remove Identity column from tables. Then create a sequence without cache feature and insert number from that sequence. The following is the code sample:
CREATE SEQUENCE Id_Sequence
    AS INT
    START WITH 1
    INCREMENT BY 1
    MINVALUE 0
    NO MAXVALUE
   NO CACHE

   insert into MyTestTable values(NEXT VALUE FOR Id_Sequence, 'Mr.Tom');

   insert into MyTestTable values(NEXT VALUE FOR Id_Sequence, 'Mr.Jackson');


How to Register -t272 to SQL Server Startup Parameter?
First, open the SQLServer configuration manager from your server. Select SQL Server 2012 instance there right client and select Properties menu. You will find a tabbed dialog window. You select start up parameters tab from there and register -t272. Then restart SQL Server 2012 instance again and see the difference as you can see on the following picture:

If too many tables contain identity column to your database and all contain existing values, then it is better to go for solution 2. Because it is a very simple solution and its scope is server wise. This means if you add SQL Server 2012 parameter -t272 there, then it will affect all your databases there. If you want to create a new database and you need auto generated number field, then you can use solution 1, that means use sequence value to a column instead of auto Identity value. There are so many articles you can find online about when you will use auto identity column when using sequence and advantages/disadvantages of each other. I hope you will read all those and take the appropriate decision.

HostForLIFE.eu SQL Server 2012 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 :: Avoid Multiple Database Request to Improve Performance

clock May 26, 2016 23:35 by author Peter

It is not smart to execute multiple db request for loading single page.  Review your database code to see if you have got request paths that go to the database quite once. each of these round-trips decreases the number of requests per second your application will serve. By returning multiple resultsets in a single database request, you can cut the total time spent communicating with the database.

In order to enhance performance you should execute single keep proc and bring multiple resultset in to single dB request. In this article i will explain you how to avoid multiple database request and how to bring multiple resultset into single dB request. Consider a scenario of loading a Product Page, which displays:
Product information
Product Review information.

In order to bring two information request in single dB request, your sql server keep proc ought to be declared as below.

SQL Server Stored Proc


CREATE PROCEDURE GetProductDetails
 @ProductId bigint,
AS
SET NOCOUNT ON

--Product Information
Select ProductId,
 ProductName,
 ProductImage,
 Description,
 Price
From Product
Where ProductId = @ProductId


--Product Review Information
Select  ReviewerName,
 ReviewDesc,
 ReviewDate
From ProductReview
Where ProductId = @ProductId


Asp.net, C# Code to bring multiple db request into single db request
Code Inside Data Access Class Library (DAL)
public DataSet GetProductDetails()
{
SqlCommand cmdToExecute = new SqlCommand();
cmdToExecute.CommandText = "GetProductDetails";
cmdToExecute.CommandType = CommandType.StoredProcedure;
DataSet dsResultSet = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(cmdToExecute);

try
{
    var conString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"];
    string strConnString = conString.ConnectionString;
    SqlConnection conn = new SqlConnection(strConnString);

    cmdToExecute.Connection = conn;

    cmdToExecute.Parameters.Add(new SqlParameter("@ ProductId", SqlDbType.BigInt, 8, ParameterDirection.Input, false, 19, 0, "", DataRowVersion.Proposed, _productId));

    //Open Connection
    conn.Open();

    // Assign proper name to multiple table
    adapter.TableMappings.Add("Table", "ProductInfo");
    adapter.TableMappings.Add("Table1", "ProductReviewInfo");
    adapter.Fill(dsResultSet);

    return dsResultSet;             
}
catch (Exception ex)
{
    // some error occured.
    throw new Exception("DB Request error.", ex);
}
finally
{
    conn.Close();
    cmdToExecute.Dispose();
    adapter.Dispose();
}
}

Code Inside Asp.net .aspx.cs page
protected void Page_Load(object sender, EventArgs e)
{
   if (Request.QueryString[ProductId] != null)
   {
      long ProductId = Convert.ToInt64(Request.QueryString[ProductId].ToString()); 
  
      DataSet dsData = new DataSet();

      //Assuming you have Product class in DAL
      ProductInfo objProduct = new ProductInfo();
      objProduct.ProductId = ProductId;
      dsData = objProduct.GetProductDetails();

      DataTable dtProductInfo = dsData.Tables["ProductInfo"];
      DataTable dtProductReviews = dsData.Tables["ProductReviewInfo"];

      //Now you have data table containing information
      //Make necessary assignment to controls
      .....
      .....
      .....
      .....
      ..... 

    }
}

 

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 2014 Hosting - HostForLIFE.eu :: How to Save Youtube video into database and display using Linq?

clock May 12, 2016 00:08 by author Peter

In this article I am going to explain how to save the youtube into database and display it in Gridview using Linq. I have got a requirement to save the youtube video URL into database and display them where user can play the videos. I have created a table Tb_videos which store the information video tile, description and URL as you can see on the following :

HTML Markup:
<table>  
<tr>
<td>Title :</td>
 <td>
     <asp:TextBox ID="txttitle" runat="server" Width="450px"></asp:TextBox></td>
</tr>
<tr>
<td></td>
 <td></td>
</tr>
   <tr>
<td>Description :</td>
 <td><asp:TextBox ID="txtdescription" runat="server" TextMode="MultiLine" Width="450px"></asp:TextBox></td>
</tr>
<tr>
<td></td>
 <td></td>
</tr>
   <tr>
<td>Video URL :</td>
 <td><asp:TextBox ID="txturl" runat="server" Width="450px"></asp:TextBox></td>
</tr>
<tr>
<td></td>
 <td></td>
</tr>
   <tr>
<td></td>
 <td>
     <asp:Button ID="btnsubmit" runat="server" Text="Submit" /></td>
 </tr>
</table>
<br />
    <asp:GridView ID="grdvideo" runat="server" AutoGenerateColumns="False"
        BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"
        CellPadding="4" ForeColor="Black" GridLines="Vertical">
        <AlternatingRowStyle BackColor="White" />
    <Columns>
    <asp:BoundField DataField="Title" HeaderText="Title" />
    <asp:BoundField DataField="Description" HeaderText="Description"/>
   <asp:TemplateField HeaderText="Videos">
   <ItemTemplate>
   <object  width="480" height="385">
<embed src='<%#Eval("url") %>' type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385">
</embed>
</object> 
   </ItemTemplate>
   </asp:TemplateField>
    </Columns>
        <FooterStyle BackColor="#CCCC99" />
        <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
        <RowStyle BackColor="#F7F7DE" />
        <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
        <SortedAscendingCellStyle BackColor="#FBFBF2" />
        <SortedAscendingHeaderStyle BackColor="#848384" />
        <SortedDescendingCellStyle BackColor="#EAEAD3" />
        <SortedDescendingHeaderStyle BackColor="#575357" />
    </asp:GridView>


Import the namespace
C#:
using System.Text.RegularExpressions;

VB:
Imports System.Text.RegularExpressions

Create the object of DBML:
C#:
BlogDataContext db = new BlogDataContext();

VB:
Private db As New BlogDataContext()

Get the Youtube video id
Write a function to get the youtube video id from youtube video URL .

C# Code:
private string GetYouTubeVideoID(string youTubeVideoUrl)
{
    var regexMatch = Regex.Match(youTubeVideoUrl, "^[^v]+v=(.{11}).*",
                       RegexOptions.IgnoreCase);
    if (regexMatch.Success)
    {
        return "http://www.youtube.com/v/" + regexMatch.Groups[1].Value +"&hl=en&fs=1";
    }
    return youTubeVideoUrl;
}


VB Code:
Private Function GetYouTubeVideoID(ByVal youTubeVideoUrl As String) As String
    Dim regexMatch = Regex.Match(youTubeVideoUrl, "^[^v]+v=(.{11}).*", RegexOptions.IgnoreCase)
    If regexMatch.Success Then
        Return "http://www.youtube.com/v/" + regexMatch.Groups(1).Value + "&hl=en&fs=1"
    End If
    Return youTubeVideoUrl
End Function


Save the record to database
On button click write the below given code to insert the record into database table.

C# Code:
protected void btnsubmit_Click(object sender, EventArgs e)
{
    try
    {
        string ytFormattedVideoUrl = GetYouTubeVideoID(txturl.Text);
        Tb_Video tb = new Tb_Video();
        tb.Title = txttitle.Text;
        tb.Description = txtdescription.Text;
        tb.URL = ytFormattedVideoUrl;
        db.Tb_Videos.InsertOnSubmit(tb);
        db.SubmitChanges();
        Response.Write("<script>alert('Record Inserted Successfully');</script>");
        BindGrid();
        Clear();
    }
    catch (Exception ex)
    { }
}
public void Clear()
{
    txturl.Text = string.Empty;
    txtdescription.Text = string.Empty;
    txttitle.Text = string.Empty;
}


VB Code:
Protected Sub btnsubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnsubmit.Click
    Try
        Dim ytFormattedVideoUrl As String = GetYouTubeVideoID(txturl.Text)
        Dim tb As New Tb_Video()
        tb.Title = txttitle.Text
        tb.Description = txtdescription.Text
        tb.URL = ytFormattedVideoUrl
        db.Tb_Videos.InsertOnSubmit(tb)
        db.SubmitChanges()
        Response.Write("<script>alert('Record Inserted Successfully');</script>")
        BindGrid()
        Clear()
    Catch ex As Exception
    End Try
End Sub
Public Sub Clear()
    txturl.Text = String.Empty
    txtdescription.Text = String.Empty
    txttitle.Text = String.Empty
End Sub


Fetch the record from database and display
Create a method to get the record from database table and display in Gridview data control.

C# Code:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGrid();
    }
}

public void BindGrid()
{
    try
    {
        var bind = from v in db.Tb_Videos
                   select v;
        grdvideo.DataSource = bind;
        grdvideo.DataBind();
    }
    catch (Exception ex)
    {
    }
}


VB Code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        BindGrid()
    End If
End Sub

Public Sub BindGrid()
    Try
        Dim bind = From v In db.Tb_Videos
        grdvideo.DataSource = bind
        grdvideo.DataBind()
    Catch ex As Exception
    End Try
End Sub


Build the project and run. To test the application inserts a record into database.

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 2014 Hosting - HostForLIFE.eu :: How to Save Youtube video into database and display using Linq?

clock May 12, 2016 00:08 by author Peter

In this article I am going to explain how to save the youtube into database and display it in Gridview using Linq. I have got a requirement to save the youtube video URL into database and display them where user can play the videos. I have created a table Tb_videos which store the information video tile, description and URL as you can see on the following :

HTML Markup:
<table>  
<tr>
<td>Title :</td>
 <td>
     <asp:TextBox ID="txttitle" runat="server" Width="450px"></asp:TextBox></td>
</tr>
<tr>
<td></td>
 <td></td>
</tr>
   <tr>
<td>Description :</td>
 <td><asp:TextBox ID="txtdescription" runat="server" TextMode="MultiLine" Width="450px"></asp:TextBox></td>
</tr>
<tr>
<td></td>
 <td></td>
</tr>
   <tr>
<td>Video URL :</td>
 <td><asp:TextBox ID="txturl" runat="server" Width="450px"></asp:TextBox></td>
</tr>
<tr>
<td></td>
 <td></td>
</tr>
   <tr>
<td></td>
 <td>
     <asp:Button ID="btnsubmit" runat="server" Text="Submit" /></td>
 </tr>
</table>
<br />
    <asp:GridView ID="grdvideo" runat="server" AutoGenerateColumns="False"
        BackColor="White" BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px"
        CellPadding="4" ForeColor="Black" GridLines="Vertical">
        <AlternatingRowStyle BackColor="White" />
    <Columns>
    <asp:BoundField DataField="Title" HeaderText="Title" />
    <asp:BoundField DataField="Description" HeaderText="Description"/>
   <asp:TemplateField HeaderText="Videos">
   <ItemTemplate>
   <object  width="480" height="385">
<embed src='<%#Eval("url") %>' type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385">
</embed>
</object> 
   </ItemTemplate>
   </asp:TemplateField>
    </Columns>
        <FooterStyle BackColor="#CCCC99" />
        <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
        <RowStyle BackColor="#F7F7DE" />
        <SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
        <SortedAscendingCellStyle BackColor="#FBFBF2" />
        <SortedAscendingHeaderStyle BackColor="#848384" />
        <SortedDescendingCellStyle BackColor="#EAEAD3" />
        <SortedDescendingHeaderStyle BackColor="#575357" />
    </asp:GridView>


Import the namespace
C#:
using System.Text.RegularExpressions;

VB:
Imports System.Text.RegularExpressions

Create the object of DBML:
C#:
BlogDataContext db = new BlogDataContext();

VB:
Private db As New BlogDataContext()

Get the Youtube video id
Write a function to get the youtube video id from youtube video URL .

C# Code:
private string GetYouTubeVideoID(string youTubeVideoUrl)
{
    var regexMatch = Regex.Match(youTubeVideoUrl, "^[^v]+v=(.{11}).*",
                       RegexOptions.IgnoreCase);
    if (regexMatch.Success)
    {
        return "http://www.youtube.com/v/" + regexMatch.Groups[1].Value +"&hl=en&fs=1";
    }
    return youTubeVideoUrl;
}


VB Code:
Private Function GetYouTubeVideoID(ByVal youTubeVideoUrl As String) As String
    Dim regexMatch = Regex.Match(youTubeVideoUrl, "^[^v]+v=(.{11}).*", RegexOptions.IgnoreCase)
    If regexMatch.Success Then
        Return "http://www.youtube.com/v/" + regexMatch.Groups(1).Value + "&hl=en&fs=1"
    End If
    Return youTubeVideoUrl
End Function


Save the record to database
On button click write the below given code to insert the record into database table.

C# Code:
protected void btnsubmit_Click(object sender, EventArgs e)
{
    try
    {
        string ytFormattedVideoUrl = GetYouTubeVideoID(txturl.Text);
        Tb_Video tb = new Tb_Video();
        tb.Title = txttitle.Text;
        tb.Description = txtdescription.Text;
        tb.URL = ytFormattedVideoUrl;
        db.Tb_Videos.InsertOnSubmit(tb);
        db.SubmitChanges();
        Response.Write("<script>alert('Record Inserted Successfully');</script>");
        BindGrid();
        Clear();
    }
    catch (Exception ex)
    { }
}
public void Clear()
{
    txturl.Text = string.Empty;
    txtdescription.Text = string.Empty;
    txttitle.Text = string.Empty;
}


VB Code:
Protected Sub btnsubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnsubmit.Click
    Try
        Dim ytFormattedVideoUrl As String = GetYouTubeVideoID(txturl.Text)
        Dim tb As New Tb_Video()
        tb.Title = txttitle.Text
        tb.Description = txtdescription.Text
        tb.URL = ytFormattedVideoUrl
        db.Tb_Videos.InsertOnSubmit(tb)
        db.SubmitChanges()
        Response.Write("<script>alert('Record Inserted Successfully');</script>")
        BindGrid()
        Clear()
    Catch ex As Exception
    End Try
End Sub
Public Sub Clear()
    txturl.Text = String.Empty
    txtdescription.Text = String.Empty
    txttitle.Text = String.Empty
End Sub


Fetch the record from database and display
Create a method to get the record from database table and display in Gridview data control.

C# Code:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        BindGrid();
    }
}

public void BindGrid()
{
    try
    {
        var bind = from v in db.Tb_Videos
                   select v;
        grdvideo.DataSource = bind;
        grdvideo.DataBind();
    }
    catch (Exception ex)
    {
    }
}


VB Code:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        BindGrid()
    End If
End Sub

Public Sub BindGrid()
    Try
        Dim bind = From v In db.Tb_Videos
        grdvideo.DataSource = bind
        grdvideo.DataBind()
    Catch ex As Exception
    End Try
End Sub


Build the project and run. To test the application inserts a record into database.

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.



European ReportViewer Hosting - HostForLIFE.eu :: How to Export Reports to Word, PDF and Excel Programmatically

clock April 27, 2016 21:38 by author Peter

When reporting Services reports are shown with ASP.NET Report Viewer control, one of the common requirements for exporting facility is, limiting it to few output formats. By default Export drop-down contains 7 output formats. If we need to limit for 1-2 output formats, one way is, hide the ExportControl and implement it with our own code. Here is the way of implementing it;

Here could be a sample screen for a ASP.NET page with reporting Services report. Note that ExportControl is hidden in the toolbar and drop-down is added to show output formats for exporting.

Write the code below for Page_Load.

protected void Page_Load(object sender, EventArgs e)
{
    ReportViewer1.ShowExportControls = false;
    ReportViewer1.ProcessingMode = ProcessingMode.Remote;
    // this can be set with control itself.
    //ReportViewer1.ServerReport.ReportServerUrl = new Uri(@"http://localhost/reportserver");
    //ReportViewer1.ServerReport.ReportPath = @"/Report Project1/Report2";
    if (!IsPostBack)
    {
        DropDownList1.Items.Add(new ListItem("Word", "Word"));
        DropDownList1.Items.Add(new ListItem("Excel", "Excel"));
        DropDownList1.Items.Add(new ListItem("Acrobat (PDF) file", "PDF"));
    }

}


Now, write the following code for Button-Click.
protected void Button1_Click(object sender, EventArgs e)
{
    string mimeType;
    string encoding;
    string fileNameExtension;
    string[] streams;
    Warning[] warnings;
    byte[] bytes = ReportViewer1.ServerReport.Render(DropDownList1.SelectedValue, null, out mimeType, out encoding, out fileNameExtension, out streams, out warnings);
    HttpContext.Current.Response.Buffer = true;
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ContentType = mimeType;
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=SalesReport." + fileNameExtension);
    HttpContext.Current.Response.BinaryWrite(bytes);
    HttpContext.Current.Response.Flush();
    HttpContext.Current.Response.End();
}

HostForLIFE.eu ReportViewer 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.



WCF Hosting - HostForLIFE.eu :: How to Create Web Services Using C#?

clock April 14, 2016 20:59 by author Peter

In this tutorial, I will show you how to create Web Services Using C#. This service will help you to communicate with the server.Windows Communication Foundation (WCF) is a framework for building service-oriented applications.

Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data.

Now, write the following code:
    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.Services; 
    using EntityLayer; 
    using BusinessLayer; 
    namespace WebApplication1  
    { 
        /// <summary> 
        /// Summary description for WebService1 
        /// </summary> 
        [WebService(Namespace = "http://hostforlife.eu")] 
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 
        [System.ComponentModel.ToolboxItem(false)] 
        // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
        // [System.Web.Script.Services.ScriptService] 
        public class WebService1: System.Web.Services.WebService  
        { 
            [WebMethod] 
            public PurchaseEntity item(PurchaseEntity Vp)  
            { 
                PurchaseBusiness ObjectPurchaseOrder = new PurchaseBusiness(); 
                return ObjectPurchaseOrder.item(Vp); 
            } 
            [WebMethod] 
            public PurchaseEntity Insert(PurchaseEntity obj1)  
            { 
                PurchaseBusiness ObjectPurchaseOrder = new PurchaseBusiness(); 
                return ObjectPurchaseOrder.Insert(obj1); 
            } 
            [WebMethod] 
            public PurchaseEntity Delete(PurchaseEntity obj2)  
            { 
                PurchaseBusiness ObjectPurchaseOrder = new PurchaseBusiness(); 
                return ObjectPurchaseOrder.Delete(obj2); 
            } 
            [WebMethod] 
            public PurchaseEntity Update(PurchaseEntity pe)  
            { 
                PurchaseBusiness ObjectPurchaseOrder = new PurchaseBusiness(); 
                return ObjectPurchaseOrder.Update(pe); 
            } 
        } 
    } 

HostForLIFE.eu WCF 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

HostForLIFE 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 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in