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 :: 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.



AngularJS Hosting - HostForLIFE.eu :: How to Datatable Binding Using AngularJS?

clock March 30, 2016 00:05 by author Peter

Today I want to show you how to Datatable Binding Using AngularJS. Now write the following code:
<html xmlns="http://www.w3.org/1999/xhtml"> 

  <head> 
      <title>Datatable Records Using AngularJS</title> 
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script> 
      <script src="http://ui-grid.info/release/ui-grid-unstable.js"></script> 
      <link rel="stylesheet" href="http://ui-grid.info/release/ui-grid-unstable.css" type="text/css"> 
      <script type="text/javascript"> 
      debugger; 
      var myApp = angular.module('sampleapp', ['ui.grid', 'ui.grid.selection', 'ui.grid.exporter']); 
      myApp.controller("appcontroller", function ($scope, $http) 
      { 
          $scope.gridOptions = { 
              data: 'BindDataTableusingJSON', 
              columnDefs: [ 
              { 
                  field: 'Application_Number' 
              }, 
              { 
                  field: 'Candidate_Name' 
              }, 
              { 
                  field: 'Category' 
              }, 
              { 
                  field: 'Fathers_Name' 
              }, 
              { 
                  field: 'Date' 
              }, 
              { 
                  field: 'Address' 
              }] 
          }; 
          $scope.BindDataTableusingJSON = { 
              "data": [] 
          }; 
          $http.post('try2.aspx/SaveUser', 
              { 
                  data: 
                  {} 
              }) 
              // $http.get('try2.aspx/SaveUser') 
              .success(function (data) 
              { 
                  debugger; 
                  // var data = jQuery.parseJSON(data.d.toString()); 
                  var d = JSON.parse(data.d); 
                  $scope.BindDataTableusingJSON = d; 
              }); 
      }).config(function ($httpProvider) 
      { 
          $httpProvider.defaults.headers.post = {}; 
          $httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8"; 
      }); 
      </script> 
      <style type="text/css"> 
      .grid { 
          width: 800px; 
          height: 400px; 
      } 
       
      .nodatatxt { 
          position: absolute; 
          top: 80px; 
          opacity: 0.25; 
          font-size: 1.5em; 
          width: 100%; 
          text-align: center; 
          z-index: 1000; 
      } 
      </style> 
  </head> 

  <body> 
      <form id="form1" runat="server"> 
          <div ng-app="sampleapp" ng-controller="appcontroller"> 
              <br /> 
              <br /> 
              <div ui-grid="gridOptions" ui-grid-selection ui-grid-exporter class="grid"> 
                  <div class="nodatatxt" ng-if="BindDataTableusingJSON.data.length==0"> No Records Found</div> 
              </div> 
          </div> 
      </form> 
  </body> 

</html> 

Code-behind

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data; 
using System.Web.Script.Serialization; 
using System.Web.Services; 
using System.Web.Script.Services; 
public partial class Services_t_try2: System.Web.UI.Page 

  protected void Page_Load(object sender, EventArgs e) 
  {} 
  [WebMethod] 
  [ScriptMethod] 
  public static string SaveUser() 
  { 
      DataSet ds = YourFunctionWhichReturnsDataset(); 
      DataTable dt = ds.Tables[0]; 
      ds.Tables[0].Columns[4].ColumnName = ds.Tables[0].Columns[4].ColumnName.Replace("Date Of Birth", "Date"); 
      return DataTableToJSONWithJavaScriptSerializer(ds.Tables[0]); 
  } 
  public static string DataTableToJSONWithJavaScriptSerializer(DataTable table) 
  { 
      JavaScriptSerializer jsSerializer = new JavaScriptSerializer(); 
      List < Dictionary < string, object >> parentRow = new List < Dictionary < string, object >> (); 
      Dictionary < string, object > childRow; 
      foreach(DataRow row in table.Rows) 
      { 
          childRow = new Dictionary < string, object > (); 
          foreach(DataColumn col in table.Columns) 
          { 
              childRow.Add(col.ColumnName, row[col]); 
          } 
          parentRow.Add(childRow); 
      } 
      return jsSerializer.Serialize(parentRow); 
  } 

 

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 Remove Duplicate Data From String on SQL Server?

clock March 15, 2016 21:10 by author Peter

In this tutorial, let me show you how to remove data from string in which data are separated by delimiter. An identifier that complies with all the rules for the format of identifiers can be used with or without delimiters. An identifier that does not comply with the rules for the format of regular identifiers must always be delimited.

Delimited identifiers are used in these situations:

  • When reserved words are used for object names or portions of object names.

    It is recommended that reserved keywords not be used as object names. Databases upgraded from earlier versions of Microsoft® SQL Server™ may contain identifiers that include words not reserved in the earlier version, but are reserved words for SQL Server 2000. You can refer to the object using delimited identifiers until the name can be changed.

  • When using characters not listed as qualified identifiers.

    SQL Server allows any character in the current code page to be used in a delimited identifier; however, indiscriminate use of special characters in an object name may make SQL statements and scripts difficult to read and maintain.

You can use the following code:   

CREATE FUNCTION [dbo].[DistinctList] 
    ( 
    @List VARCHAR(MAX), 
    @Delim CHAR 
    ) 
    RETURNS 
    VARCHAR(MAX) 
    AS 
    BEGIN 
    DECLARE @Return_List [varchar](max); 
    DECLARE @Temp_Str [varchar](max); 
    DECLARE @Char_index int; 
    SET @List=@List+@Delim; 
    SET @Return_List=''; 
    SET @Char_index=CHARINDEX(@Delim,@List,1); 
    WHILE @Char_index>0 
    BEGIN 
    SET @Temp_Str=SUBSTRING(@List,1,@Char_index-1); 
    SET @Return_List=@Return_List+@Temp_Str+@Delim; 
    SET @List=REPLACE(@List,@Temp_Str+@Delim,''); 
    SET @Char_index=CHARINDEX(@Delim,@List,1); 
    END 
    Return SUBSTRING(@Return_List,1 ,LEN(@Return_List)-1); 
    END  


In this function first parameter take the string  and second parameter the delimiter ,on the behalf of this delimiter we split the string and remove the duplicate data.
    DECLARE @String [varchar](max); 
    SET @String='10,11,12,10,11'; 
    SELECT dbo.DistinctList(@String,',') AS List; 


And here is the output:
10,11,12

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 :: Make an Index on #temp tables on SQL Server

clock March 8, 2016 21:12 by author Peter

Today let me explain you about how to make an Index on #temp tables. #Temp tables are much like SQL tables that are defined and stored in TempDB. Difference between them and a permanent table is they are not allowed to have foreign keys.


One of the feature of temp table (#temp) is that we can add a clustered or non clustered index. Also, #temp tables allow for the auto-generated columns (fields) to be created. This can help the optimizer when determining the number of records. Below is an example of creating both a clustered and non-clustered index on a temp table.
-- creating temp table - #employees
CREATE TABLE #Employees 

ID INT IDENTITY(1,1), 
EmployeeID INT, 
EmployeeName VARCHAR(50) 


INSERT INTO #Employees 

EmployeeID, 
EmployeeName 

SELECT 
EmployeeID = e.EmployeeID 
,EmployeeName = e.EmployeeName 
FROM dbo.Employees e 
 
-- creating clustered index 
CREATE CLUSTERED INDEX IDX_C_Employees_EmployeeID ON #Employees(EmployeeID)
 
-- creating non-clustured index 
CREATE INDEX IDX_Users_UserName ON #Employees(EmployeeName) 

 

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.



AngularJS Hosting - HostForLIFE.eu :: How to create Strong Password for AngularJS?

clock March 3, 2016 21:33 by author Peter

This code snippet helps us in choosing a strong password for AngularJS UI pages. All of us have seen , for choosing a password we need combination of special characters, Capital letter , small letters, digits etc to make it strong.

Write the following code:

<!DOCTYPE html>  
<html>  
<head>  
<title>Strong Password for Angular UI Pages</title>  

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.8/angular.min.js"></script>    
<script>  
var app = angular.module("myApp", []);  
app.controller("myCtrl", function ($scope) {  

    var strongRegularExp = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");  

    var mediumRegularExp = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})");  

    $scope.checkpwdStrength = {  
        "width": "150px",  
        "height": "25px",  
        "float": "right"  
    };  

    $scope.validationInputPwdText = function (value) {  
        if (strongRegularExp.test(value)) {  
            $scope.checkpwdStrength["background-color"] = "green";  
            $scope.userPasswordstrength = 'You have a Very Strong Password now';  
        } else if (mediumRegularExp.test(value)) {  
            $scope.checkpwdStrength["background-color"] = "orange";  
            $scope.userPasswordstrength = 'Strong password, Please give a very strong password';  
        } else {  
            $scope.checkpwdStrength["background-color"] = "red";  
            $scope.userPasswordstrength = 'Weak Password , Please give a strong password';  
        }  
    };  

});  
</script>  
</head>  
<body ng-app="myApp">  
<div ng-controller="myCtrl" style="border:5px solid gray; width:800px;">  
<div>  
    <h3>Strong Password for Angular UI Pages </h3>  
</div>  
<div style="padding-left:25px;">  
    <div ng-style="checkpwdStrength"></div>  
    <input type="password" ng-model="userPassword" ng-change="validationInputPwdText(userPassword)" class="class1" />  
    <b> {{userPasswordstrength}}</b>  
</div>  
<br />  
<br />  
<br />  
</div>  
</body>  
</html>  

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.



How To Collect Performance Metrics From SQL Server Query Analyzer?

clock March 1, 2016 20:37 by author Peter

In this topic, I will show you how to collect value of performance counters from query analyzer. Microsoft® SQL Server SQL Query Analyzer is a graphical tool that allows you to:

  • Create queries and other SQL scripts and execute them against SQL Server databases. (Query window)
  • Quickly create commonly used database objects from predefined scripts. (Templates)
  • Quickly copy existing database objects. (Object Browser scripting feature)
  • Execute stored procedures without knowing the parameters. (Object Browser procedure execution feature)
  • Debug stored procedures. (T-SQL Debugger)
  • Debug query performance problems. (Show Execution Plan, Show Server Trace, Show Client Statistics, Index Tuning Wizard)
  • Locate objects within databases (object search feature), or view and work with objects. (Object Browser)
  • Quickly insert, update, or delete rows in a table. (Open Table window)
  • Create keyboard shortcuts for frequently used queries. (custom query shortcuts feature)
  • Add frequently used commands to the Tools menu. (customized Tools menu feature)

The following code is demo query to do same. You can create collect any counter vale for instant. Now write the code:

/*************************************************/
USE Master
GO
Create Table Perfmon (Object_name Varchar (200),
Counter_name varchar (300) , Instance_name varchar (100),
cntr_value bigint, cntr_type bigint , date varchar (20))
GO
Insert into Perfmon
SELECT object_name , counter_name , instance_name , cntr_value, cntr_type
, convert (varchar (20),getdate () , 120) as date
FROM sys.dm_os_performance_counters
WHERE OBJECT_NAME in
(
'MSSQL$Servername:Databases' ,
'MSSQL$Servername:General Statistics',
'MSSQL$Servername:Buffer Manager' ,
'MSSQL$Servername:Locks'
)
AND counter_name in
(
'Transactions/sec' ,'User Connections','Page life expectancy',
'Buffer cache hit ratio', 'Buffer cache hit ratio base' ,
'Free pages','Total pages','Target pages','Lock Wait Time (ms)'
)
Select @@servername
GO
Select *, case
when cntr_type  = 65792  Then 'instant_value'
when cntr_type = 272696576 Then 'Incremental'
When cntr_type = 1073939712 Then 'Instant fraction'
When cntr_type = 537003264 Then 'Use this with Base value'
else 'null' end 
from Master.dbo.perfmon
/*************************************************/

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 :: String comparison and Collation in SQL Server

clock February 23, 2016 19:39 by author Peter

You probably already know that string comparison is dependent on the collation. but sometimes this dependency is slightly strange. I have installed an SQL Server with LATIN1_GENERAL_CI_AS as default collation (like is also the default setting during installation). Some weeks ago I came across a specific behavior in combination of this collation and the german language.

German is a stunning language! really. You may know that we have a tendency to Germans have some special vowels (the “Umlaut”: ä, ö, and ü) and also that extra ß which is often (but not always) simply interchangeable with “ss”. look at this query that uses the default collation for comparison:
select case
 when 'ss' collate latin1_general_ci_as
     = 'ß' collate latin1_general_ci_as
      then 'Yes'
 else 'No'
end [ss=ß?]

Considering that LATIN1_GENERAL_CI_AS is the default collation, the query above is identical to the following query:
select case
 when 'ss' = 'ß' then 'Yes'
 else 'No'
end [ss=ß?]

In both cases the result is Yes, so “ß” is considered as to be identical to “ss” when using the LATIN1_GENERAL_CI_AS collation. Now it's time to look at this query:

select case
 when 'ä' = 'ae' then 'Yes'
 else 'No'
end [ä=ae?]

This time the answer is no which is somewhat surprising, since one could consider the overall behavior inconsistent. In German, “ä” and “ae” (and also “ö” and “oe” in addition as “ü” and “ue”) are just as interchangeable as “ß” and “ss”. When this happened to me, I started browsing books online. There’s a hint, where you're advised setting the default collation to LATIN1_GENERAL_BIN for new installations. I didn’t know this so far, but ok: let’s retry our experiment:

select case
 when 'ss' collate latin1_general_bin
     = 'ß' collate latin1_general_bin
      then 'Yes'
 else 'No'
end [ss=ß?]

Now the answer is no. but considering the fact that most newer installations use LATIN1_GENERAL_CI_AS, simply because that’s the default during installation, I can’t just change the collation to LATIN1_GENERAL_BIN, since this will certainly produce other problems with queries spanning multiple databases with totally different collations. Not taking into account that changing the collation for an existing server and all of its databases/columns is a cumbersome and also very risky task on its own.

 

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.



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