European Windows 2012 Hosting BLOG

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

SQL Server 2014 Hosting - HostForLIFE.eu :: Error While Saving Table in SQL Server

clock May 31, 2016 20:46 by author Anthony

That happens because sometimes it is necessary to drop and recreate a table in order to change something. This can take a while, since all data must be copied to a temp table and then re-inserted in the new table. Since SQL Server by default doesn't trust you, you need to say "OK, I know what I'm doing, now let me do my work." This problem occurs when the Prevent saving changes that require the table re-creation option is enabled, and you make one or more of the following changes to the table:

Free ASP.NET Hosting - Europe

  • You change the Allow Nulls setting for a column.
  • You reorder columns in the table.
  • You change the column data type.
  • You add a new column.

When you change a table so that you alter the metadata structure of the table, and then you save the table, the table must be re-created based on these changes. This may result in the loss of metadata and in a direct loss of data during the re-creation of the table. If you enable the Prevent saving changes that require the table re-creation option in the Designer section of the SQL Server Management Studio (SSMS) Options window, you receive the error message that is mentioned in the “Symptoms” section.

To change the Prevent saving changes that require the table re-creation option, follow these steps:

  • Open SQL Server Management Studio (SSMS).
  • On the Tools menu, click Options.
  • In the navigation pane of the Options window, click Designers.
  • Select or clear the Prevent saving changes that require the table re-creation check box, and then click OK.

Note If you disable this option, you are not warned when you save the table that the changes that you made have changed the metadata structure of the table. In this case, data loss may occur when you save the table.

Risk of turning off the “Prevent saving changes that require table re-creation” option

Although turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the “Symptoms” section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore, we recommend that you do not work around this problem by turning off the option.

To determine whether the Change Tracking feature is enabled for a table, follow these steps:

  • In SQL Server Management Studio, locate the table in Object Explorer.
  • Right-click the table, and then click Properties.
  • In the Table Properties dialog box, click Change Tracking.

If the value of the Change Tracking item is True, this option is enabled for the table. If the value is False, this option is disabled.

When the Change Tracking feature is enabled, use Transact-SQL statements to change the metadata structure of the table.

Steps to reproduce the problem

  • In SQL Server Management Studio, create a table that contains a primary key in the Table Designer tool.
  • Right-click the database that contains this table, and then click Properties.
  • In the Database Properties dialog box, click Change Tracking.
  • Set the value of the Change Tracking item to True, and then click OK.
  • Right-click the table, and then click Properties.
  • In the Table Properties dialog box, click Change Tracking.
  • Set the value of the Change Tracking item to True, and then click OK.
  • On the Tools menu, click Options.
  • In the Options dialog box, click Designers.
  • Click to select the Prevent saving changes that require table re-creation check box, and then click OK.
  • In the Table Designer tool, change the Allow Nulls setting on an existing column.
  • Try to save the change to the table.

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 :: 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 Hosting - HostForLIFE.eu :: SQL Server Event Alerts

clock May 24, 2016 18:34 by author Anthony

In this article, we will discuss about SQL Server Alert and conditional responses. SQL Server event alerts that respond by notifying operators can lead to too much noise in your email inbox. There is a built-in option to specify a number of minutes to delay between responses. For many, that setting alone is sufficient to keep the spam down to a minimum. But events may still occur during that "delay between responses" window. And SQL Server will fire alerts for them. You may not always want the response suppressed.

Free ASP.NET Hosting - Europe

SQL Server provides another way to more selectively respond to alerts: by executing a SQL Agent job, and using tokens within the job steps. To use tokens, you'll need to enable their use. Open SQL Server Agent Properties, select the Alert System page, and check the "Replace tokens for all job responses to alerts" checkbox as seen here:

Now let's look at a typical alert. The one pictured below raises alerts for errors with a severity level of 20. On the Response page, we see the alert is configured to respond by executing a job. (From this dialog you can choose an existing job, or click to create a new one.) The Notify Operators option is left unchecked.

Within the "DBA-Catch Severity 20 Alert" SQL Agent job, T-SQL job steps that use tokens can be created. Here is an example:

DECLARE @Descr VARCHAR(MAX) = '$(ESCAPE_SQUOTE(A-MSG))';

 

IF @Descr LIKE '%CLIENT: 127.0.0.1%'

BEGIN

    --Do nothing.

    PRINT 'Alert originating from pen test server.'

END

ELSE

BEGIN

    DECLARE @To NVARCHAR(MAX) = [email protected]';

    DECLARE @Subj NVARCHAR(255);

    DECLARE @EmailBody NVARCHAR(MAX);

    DECLARE @Date VARCHAR(MAX) = '$(ESCAPE_SQUOTE(DATE))';

    DECLARE @Time VARCHAR(MAX) = '$(ESCAPE_SQUOTE(TIME))';

 

    SET @Subj = 'SQL Server Alert System: ''20-Fatal Error in Current Process''' +

        'occurred on ' + @@SERVERNAME

    SET @Date = SUBSTRING(@Date, 5, 2) + '/' + RIGHT(@Date, 2) + '/' + LEFT(@Date, 4);

    SET @Time = LEFT(@Time, 2) + ':' + SUBSTRING(@Time, 3, 2) + ':' + RIGHT(@Time, 2);

    SET @EmailBody = 'DATE/TIME: ' + @Date + ' ' + @Time + '

 

DESCRIPTION: ' + @Descr + '

COMMENT: (None)

JOB RUN: (None)'

    EXEC msdb..sp_send_dbmail

        @recipients = @To,

        @subject = @Subj,

        @body = @EmailBody

END


There are three tokens within the T-SQL (highlighted in yellow above): A-MSG, DATE, and TIME. SQL server replaces these three tokens as follows:

 

  • A-MSG: Message text. If the job is run by an alert, the message text value automatically replaces this token in the job step.

 

  • DATE: Current date (in YYYYMMDD format).

 

  • TIME: Current time (in HHMMSS format).

 

Note the conditional logic, checking the error message. If it originates from a server with a particular IP address, no action is taken. Otherwise, an email is sent with the relevant error information. (This is a real-world example involving recurring penetration tests. The pen test server conducted port scans on the SQL host and attempted numerous connections as [sa]. I got an onslaught of unwanted email.)

Tokens are a powerful tool that give you a lot of flexibility. This very simple example just scratches the surface of what is possible. Use your imagination. Get creative. Happy alerting!

 

 



AngularJS Hosting - HostForLIFE.eu :: How to Create Cascading Dropdown in AngularJS?

clock May 17, 2016 20:38 by author Peter

In this post, I will make a Cascading Dropdown in AngularJS. Add 2 Class 1 for Countries and other for state. Write the following code:
public class Country 

    public int CountryId { get; set; } 
    public string CountryName { get; set; } 

public class State 

    public int StateId { get; set; } 
    public string StateName { get; set; } 
    public int CountryId { get; set; } 

Create a ActionResult Name it as Index [Add a View].

Add the script

<script src="~/Scripts/angular.min.js"></script> 

Create a js Name it in my case its CascadingDropdown.

var app = angular.module('myApp', []); 
app.controller('myController', function ($scope, $http) { 
    getcountries(); 
    function getcountries() { 
     
        $http({ 
            method: 'Get', 
            url: '/Home/Countries' 
 
        }).success(function (data, status, header, config) { 
 
            $scope.countries = data; 
        }).error(function (data, status, header, config) { 
            $scope.message = "Error"; 
        }); 
    } 
 
    $scope.GetStates = function ()  
    { 
        var countryIdselected = $scope.countrymodel; 
        if (countryIdselected) { 
            $http({ 
                method: 'Post', 
                url: '/Home/States', 
                data: JSON.stringify({ countryId: countryIdselected }) 
            }).success(function (data, status, header, config) { 
                $scope.states = data; 
            }).error(function (data, status, header, config) { 
                $scope.message = "Error"; 
            }) 
        } 
        else { 
            $scope.states = null; 
        } 
    } 
}); 
 
 
//Calls for Country DropDown 
 public ActionResult Countries() 
        { 
            List<Country> cobj = new List<Country>(); 
            cobj.Add(new Country { CountryId = 1, CountryName = "India" }); 
            cobj.Add(new Country { CountryId = 2, CountryName = "Srilanka" }); 
            cobj.Add(new Country { CountryId = 3, CountryName = "USA" }); 
 
            return Json(cobj, JsonRequestBehavior.AllowGet); 
        } 
 
//Calls for State DropDown with CountryID as Parameter 
 
        public ActionResult States(int countryId) 
        { 
   List<State> sobj = new List<State>(); 
   sobj.Add(new State { StateId = 1, StateName = "Karnataka", CountryId = 1 }); 
   sobj.Add(new State { StateId = 2, StateName = "Kerala", CountryId = 1 }); 
   sobj.Add(new State { StateId = 3, StateName = "TamilNadu", CountryId = 1 }); 
   sobj.Add(new State { StateId = 1, StateName = "Newyork", CountryId = 3 }); 
   sobj.Add(new State { StateId = 1, StateName = "Colombo", CountryId = 2 }); 
 
//Filter based on CountryID 
            var result = sobj.Where(x => x.CountryId == countryId).Select(x => new { x.StateId, x.StateName }); 
 
            return Json(result); 
        } 
 
//IndexView 
//  Add the script file <script src="~/Scripts/CascadingDropdown.js"></script> 
<div ng-app="myApp"> 
       
            <form name="mainForm"  ng-controller="myController"> 
 
                <select ng-model="countrymodel" ng-options=" c.CountryId as c.CountryName for c in countries" ng-change="GetStates()"> 
                    <option value="">-- Select Country --</option> 
                </select> 
                <select ng-model="statemodel" ng-options="s.StateId as s.StateName for s in states "> 
                    <option value="">-- Select State --</option> 
                </select> 
            </form> 
</div>  


I hope it works for you!

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.



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.



SQL 2016 Hosting - HostForLIFE.eu :: How to Use Concat Function in SQL 2016?

clock May 3, 2016 00:52 by author Anthony

In this tutorial, I will explain how to use concat function in SQL 2016. CONCAT function is also known as T-SQL Function which was introduced in SQL Server 2012. This function allows us to concatenate two or more parameters values together and these parameters values should be separated by comma. Before release of Concat function, we used to use the “+” operator to combine or concatenate two or more string values. The most important feature of Concat function is that it also takes care of data type conversion and beautifully handles NULL on its own. In case of Concat function, we don't need to care about the null values in the parameters which are going to be used.

Syntax

CONCAT ( string_value1, string_value2 [, string_valueN ] )

Arguments

string_value: A string value to concatenate to the other values.

Return Types: String, the length and type of which depend on the input.

 

Interesting features

1. CONCAT takes a variable number of string arguments and concatenates them into a single string.

2. It requires at least two input values; otherwise, an error is raised.

3. All arguments are implicitly converted to string types and then concatenated.

4. Best part of this; Null values are implicitly converted to an empty string. If all the arguments are null, an empty string of type varchar(1) is returned.

5. The implicit conversion to strings follows the existing rules for data type conversions. 

6. If none of the input arguments is of a supported large object (LOB) type, then the return type is truncated to 8000 in length, regardless of the return type. This truncation preserves space and supports efficiency in plan generation.

Examples:

Concatenate Space Characters with input variables

 

To understand the features of Concat function, we are showing the examples with Concat function and without the concat functions as given below:

---- Declare local variables

Declare @inpFirstName Varchar(20) ='John'

Declare @inpLastName Varchar(20) ='Carter'

 

---- Concatenating variables without Concat Function

Select @inpFirstName+' '[email protected] as FullName

FullName

John Carter

---- Concatenating variables with Concat Function

Select CONCAT(@inpFirstName,' ',@inpLastName) as FullName

FullName

John Carter

 

In the above example, we are using the two variables to concatenating together. You can see that, we are getting the same outputs. 

 

Concatenate Space Characters with with NULL values

Now, we are going to make some interesting changes in the above example by setting the null value in the second variable as given below:

---- Declare local variables

Declare @inpFirstName Varchar(20) ='John'

---- Set Null Value here

Declare @inpLastName Varchar(20) =NULL

 

---- Concatenating variables without Concat Function

Select @inpFirstName+' '[email protected] as FullName

FullName

NULL

---- Concatenating variables with Concat Function

Select CONCAT(@inpFirstName,' ',@inpLastName) as FullName

FullName

John

You can easily see that full name is showing NULL values in case of without Concat function but by using Concat function, full name is showing because of Null values are implicitly converted to an empty string.

Concatenate number and string together

If you want to concatenate string with numeric value then you should need to convert the numeric value into the string as given below:

---- Declare local variables

Declare @inpFirstName Varchar(20) ='John'

Declare @inpContactNumber BIGINT =1234567890

 

---- Concating variables without Concat Function

Select @inpFirstName+':'+CAST(@inpContactNumber as VarcharasNameWithContact

 

NameWithContact

John :1234567890

---- Concatenating variables with Concat Function

Select CONCAT(@inpFirstName,':',CAST(@inpContactNumber as Varchar))as NameWithContact

 

NameWithContact

John:1234567890

If you want to concatenate two numeric values then there is no need to change their data types because of implicit conversion to strings follows the existing rules for data type conversions.

Conclusion

The CONCAT function appends one string to the end of another string and does not require ISNULL for converting NULL into an empty string. All arguments are implicitly converted to string types and then concatenated.

 

 

 

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 Hosting - HostForLIFE.eu :: Rename SQL Server Database

clock April 28, 2016 21:34 by author Anthony

Database Administrators usually use the sp_renamedb system stored procedure to quickly rename a SQL Server Database. However, the drawback of using sp_renamedb is that it doesn't rename the Logical and Physical names of the underlying database files. It's a best practice to make sure the Logical Name and Physical File Name of the database is also renamed to reflect the actual name of the database to avoid any confusion with backup, restore or detach/attach operations.

Let's first create a new database named CoreDB using the T-SQL below:

USE master
GO
IF EXISTS (SELECT name FROM sys.databases WHERE name = N'CoreDB')
DROP DATABASE CoreDB
GO
USE master
GO
CREATE DATABASE [CoreDB]
ON PRIMARY
(
NAME = N'CoreDB',
FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\CoreDB.mdf' ,
SIZE = 2048KB ,
FILEGROWTH = 1024KB
)
LOG ON
(
NAME = N'CoreDB_log',
FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\CoreDB_log.ldf' ,
SIZE = 1024KB ,
FILEGROWTH = 10%
)
GO

Rename CoreDB Database Using sp_renamedb System Stored Procedure

Now let's rename the CoreDB database to ProductsDB by executing the below T-SQL code.

USE master
GO
ALTER DATABASE CoreDB
SET SINGLE_USER

WITH ROLLBACK IMMEDIATE
GO
EXEC master..sp_renamedb 'CoreDB','ProductsDB'
GO
ALTER DATABASE ProductsDB
SET MULTI_USER
GO

Once the above T-SQL has executed successfully the database name will change however the Logical Name and File Name will not change. You can verify this by executing the T-SQL below:

USE master
GO
/* Identify Database File Names */
SELECT

name AS [Logical Name],
physical_name AS [DB File Path],
type_desc AS [File Type],
state_desc AS [State]
FROM sys.master_files
WHERE database_id = DB_ID(N'ProductsDB')
GO

Your output should look something like this from the above query.

You can see in the above snippet that the Logical Name and File Name in the DB File Path column for ProductsDB are still reflecting the old name of CoreDB. This is not a good practice to follow in a Production Environment. Below you will see the steps which a DBA can follow to rename the database and its respective files.

Steps to Rename a SQL Server Database

DBAs should follow the below steps which will not only rename the database, but at the same time will also rename the Logical Name and File Name of the database.

This first set of commands put the database in single user mode and also modifies the logical names.


/* Set Database as a Single User */
ALTER DATABASE CoreDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE
/* Change Logical File Name */
ALTER DATABASE [CoreDB] MODIFY FILE (NAME=N'CoreDB', NEWNAME=N'ProductsDB')
GO
ALTER DATABASE [CoreDB] MODIFY FILE (NAME=N'CoreDB_log', NEWNAME=N'ProductsDB_log')
GO

This is the output from the above code.


Now we need to detach the database, so we can rename the physical files.  If the database files are open you will not be able to rename the files.

/* Detach Current Database */
USE [master]
GO
EXEC master.dbo.sp_detach_db @dbname = N'CoreDB'
GO

Once the CoreDB database is detached successfully then the next step will be to rename the Physical Files. This can be done either manually or by using the xp_cmdshell system stored procedure. You can enable xp_cmdshell feature using the sp_configure system stored procedure.

USE master
GO
sp_configure 'show advanced options'
GO
/* 0 = Disabled , 1 = Enabled */
sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE WITH OVERRIDE
GO

Once xp_cmdshell is enabled you can use the below script to rename the physical files of the database.

/* Rename Physical Files */
USE [master]
GO
EXEC xp_cmdshell 'RENAME "C:\Program Files\Microsoft SQL ServerMSSQL10.SQL2008\
MSSQL\DATA\CoreDB.mdf", "ProductsDB.mdf"'
GO
EXEC xp_cmdshell 'RENAME "C:\Program Files\Microsoft SQL ServerMSSQL10.SQL2008\
MSSQL\DATA\CoreDB_log.ldf", "ProductsDB_log.ldf"'
GO

Once the above step has successfully executed then the next step will be to attach the database, this can be done by executing the T-SQL below:

/* Attach Renamed ProductsDB Database Online */
USE [master]
GO
CREATE DATABASE ProductsDB ON
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\ProductsDB.mdf' ),
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\DATA\ProductsDB_log.ldf' )
FOR ATTACH
GO

Once the above step has successfully executed then the final step will be to allow multi user access for the user database by executing the below T-SQL:

/* Set Database to Multi User*/
ALTER DATABASE ProductsDB SET MULTI_USER
GO

You can verify the Logical and File Names for the ProductsDB database by executing the T-SQL below:

USE master
GO
/* Identify Database File Names */
SELECT
name AS [Logical Name],
physical_name AS [DB File Path],
type_desc AS [File Type],
state_desc AS [State]
FROM sys.master_files
WHERE database_id = DB_ID(N'ProductsDB')

 

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. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



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.



SQL Server 2012 Hosting - HostForLIFE.eu :: SQL Server 2012 Database Fixing

clock April 26, 2016 00:35 by author Anthony

In this article, we will see about fixed database roles in SQL Server. As the name suggests, fixed database roles cannot be removed or modified and performs specific administrative tasks as it has pre-defined set of permissions. You need to be very careful while assigning these roles and assign these roles only when there is a serious requirements. You can execute the sp_helpdbfixedrole system procedure to get the list of fixed database roles.

EXEC sp_helpdbfixedrole
GO

  • db_owner
  • db_accessadmin
  • db_securityadmin
  • db_ddladmin
  • db_backupoperator
  • db_datareader
  • db_datawriter
  • db_denydatareader
  • db_denydatawriter

You can navigate to Database Roles from Object Explorer –> Expand Databases Node –> Select Database –> Navigate to Security –> Roles –> Database Roles


db_owner

All the members of db_owner fixed database roles can perform all the maintenance activities and setting configurations. This role should not be given to regular users and should be assigned very carefully as it can perform almost all the operations in a database.

db_accessadmin

As the name suggests, all the members of db_accessadmin can handle access related issues. This role controls security, grants access, revokes access for logins to enter database. This role is rarely used as these operations are performed by DBAs as he has relevant fixed server role.

db_securityadmin

Members of db_securityadmin role manages all the permissions and security related activities. As database administrators usually manages security, permissions, role membership etc. so this role is hardly assigned and used. You should not assign this role to regular users.

db_ddladmin

If any member is assigned with db_ddladmin role then he can perform all DDL operations and can execute, create, drop and alter any objects. Normally this role is assigned to developers to perform the related operations in application. This role is usually not assigned to regular users as he can misuse the DDL operations.

db_backupoperator

db_backupoperator role can perform the database backup operations. This role is rarely used as backup activity is a role of database administrator and he has much higher permissions rather than using this specific fixed database role.

db_datareader

If any user is requesting for SELECT permission on database tables then you can tag him with db_datareader fixed database role as this role allows a member to perform SELECT operations on database tables and views and tagged member will not be able to modify any object. This role is mostly assigned to developers and regular users who need table access on production database.

db_datawriter

All the members of db_datawriter fixed database role can perform INSERT, UPDATE, DELETE operations on all tables and views in respective database. This role is basically assigned to developers to perform operations on QA servers. Testing applications sometimes require this role.

db_denydatareader

As the name suggests this role doesn’t allow to read data from tables in a database. So user will not be able to perform SELECT operations on a table or views. I haven’t used this role any time and also never seen members assigned with this role.

db_denydatawriter

This role is basically opposing db_datawriter role which means members with this role will not be able to perform INSERT, UPDATE or DELETE operations on tables and views. Again as a DBA I have not used this role yet and never seen anyone using this role.

 


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. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 



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 2012 Hosting, ASP.NET 4.5 Hosting, ASP.NET MVC 5 Hosting, SQL 2014 Hosting and SQL 2014 Hosting.

Tag cloud

Sign in