Windows 2012 Hosting - MVC 6 and SQL 2014 BLOG

Tutorial and Articles about Windows Hosting, SQL Hosting, MVC Hosting, and Silverlight Hosting

ASP.NET Hosting - ASPHostPortal.com :: How to Prevent ASP.NET Website From Multiple Database Request

clock October 26, 2015 20:44 by author Dan

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

In order to improve performance you should execute single stored 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 and
  • Product Review Information

In order to bring 2 database request in single db request, your sql server stored proc should 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
      .....
      .....
      .....
      .....
      ..... 

    }
}


Finish, Happy coding.

Best Windows Shared Hosting Recommendation

ASPHostPortal.com provides our customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Our Shared Hosting. We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable Windows Shared Hosting, we should be your best choice.



SQL Server 2014 Hosting - ASPHostPortal :: How to Solve SQL Cannot Generate SSPI Context

clock May 21, 2015 06:24 by author Dan

Everyone knows that it is good practice to use a domain or service account to run the SQL service. I’m sure you do too! However, once you do the right thing and change the SQL Service account, you may start getting the following error message when attempting to connect to the sql server:

“The target principal name is incorrect.  Cannot generate SSPI context.”

The explanation, as given by Microsoft in this KB article

    If you run the SQL Server service under the LocalSystem account, the SPN is automatically registered and Kerberos authentication interacts successfully with the computer that is running SQL Server. However, if you run the SQL Server service under a domain account or under a local account, the attempt to create the SPN will fail in most cases because the domain account and the local account do not have the right to set their own SPNs. When the SPN creation is not successful, this means that no SPN is set up for the computer that is running SQL Server. If you test by using a domain administrator account as the SQL Server service account, the SPN is successfully created because the domain administrator-level credentials that you must have to create an SPN are present.

There are 3 ways to fix the problem:

    - Revert to using the Network Service or Local System account (NOT RECOMMENDED)
    - Assign the domain account to the Domain Admins group (NOT IDEAL – due to the elevated permissions)
    - Fix the problem by giving the domain account just the appropriate permissions in Active Directory. Permissions required are
        >> ServicePrincipalName: Read
        >> ServicePrincipalName: Write

We will use the 3rd option to fix the error. First, it is good practice to verify that the problem is actually due to permission issues. Log in to the server where you SQL Instance is running. Go to the error logs and look for the last time that the SQL service was restarted. You should find an error message similar to this:

Date                   10/17/2013 9:29:50 AM
Log                    SQL Server (Archive #1 - 10/17/2013 10:53:00 AM)
Source                Server
Message
The SQL Server Network Interface library could not register the Service Principal Name (SPN) [ MSSQLSvc/servername.domainname.net:1433 ] for the SQL Server service. Windows return code: 0x2098, state: 15. Failure to register a SPN might cause integrated authentication to use NTLM instead of Kerberos. This is an informational message. Further action is only required if Kerberos authentication is required by authentication policies and if the SPN has not been manually registered.

This is great. At least now we have verified that the problem is related to the SPN and we are ready to apply the fix.

Log in to the server running your Active Directory service and execute the following steps:

    - Run Adsiedit.msc
   
- In the ADSI Edit snap-in, expand Domain [YourDomainName], expand DC= RootDomainName, expand CN=Users, right-click CN= [YourAccountName, and then click Properties.
   
- In the CN= AccountName Properties dialog box, click the Security tab.
   
- On the Security tab, click Advanced.
   
- In the Advanced Security Settings dialog box, select one (any) of "SELF"'s row
   
- Click Edit, Open Permission Entry dialog box.
   
- Make sure Pricipal is "SELF", Type is "Allow" and "Applied to" is "This Object Only", in Properties section, select the properties below:
        >> Read servicePrincipalName
        >> Write servicePrincipalName

Click OK to apply all changes and exit the ADSI Edit snap-in

Finally, you need to restart the SQL Service(s) that use the account in question.

You can verify that the SPN has been registered successfully upon the restart by going to the SQL Server logs. You should now see an entry similar to this:

Date                   10/17/2013 10:53:58 AM
Log                    SQL Server (Current - 10/17/2013 10:54:00 AM)
Source                Server
Message
The SQL Server Network Interface library successfully registered the Service Principal Name (SPN) [ MSSQLSvc/servername.domainname.net:1433 ] for the SQL Server service.

Connections to SQL Server should now succeed.

Best SQL Server 2014 Hosting Recommendation

ASPHostPortal.com provides our customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in SQL Server 2014 . We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable SQL SERVER 2014 Hosting, we should be your best choice.



SQL Server 2014 Hosting - ASPHostPortal :: Identify ErrorLog with xp_ReadErrorLog

clock May 7, 2015 07:14 by author Dan

To read error logs in SQL Server using T-SQL you can use extended stored procedure xp_ReadErrorLog to read SQL Server and SQL Server Agent error logs. xp_ReadErrorLog has seven parameters that can be used to filter error logs.

Syntax for xp_ReadErrorLog:

EXEC xp_ReadErrorLog   <LogNumber>, <LogType>,

<SearchTerm1>, <SearchTerm2>,

<StartDate>, <EndDate>, <SortOrder>

The parameter values can be as follows:

You can use the stored procedure as:

EXEC xp_ReadErrorLog

– Reads current SQL Server error log

Below are some more examples of xp_ReadErrorLog:

EXEC xp_ReadErrorLog 1
– Reads SQL Server error log from ERRORLOG.1 file

EXEC xp_ReadErrorLog 0, 1
– Reads current SQL Server error log

EXEC xp_ReadErrorLog 0, 2
– Reads current SQL Server Agent error log

EXEC xp_ReadErrorLog 0, 1, 'Failed'
– Reads current SQL Server error log with text 'Failed'

EXEC xp_ReadErrorLog 0, 1, 'Failed', 'Login'
– Reads current SQL Server error log with text ‘Failed’ AND 'Login'

EXEC xp_ReadErrorLog 0, 1, 'Failed', 'Login', '20121101', NULL
– Reads current SQL Server error log with text ‘Failed’ AND ‘Login’ from 01-Nov-2012

EXEC xp_ReadErrorLog 0, 1, 'Failed', 'Login', '20121101', '20121130'
– Reads current SQL Server error log with text ‘Failed’ AND ‘Login’ between 01-Nov-2012 and 30-Nov-2012

EXEC xp_ReadErrorLog 0, 1, NULL, NULL, '20121101', '20121130'
– Reads current SQL Server error between 01-Nov-2012 and 30-Nov-2012

EXEC xp_ReadErrorLog 0, 1, NULL, NULL, '20121101', '20121130', 'DESC'
– Reads current SQL Server error log between 01-Nov-2012 and 30-Nov-2012 and sorts in descending order

Hope This Helps!

Best SQL Server 2014 Hosting Recommendation

ASPHostPortal.com provides our customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in SQL Server 2014 . We offers Windows hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable SQL SERVER 2014 Hosting, we should be your best choice.



SQL SERVER 2014 Hosting - ASPHostPortal :: Automatic SQL Server Backup Utility using Sqlserver Agent

clock March 23, 2015 08:22 by author Mark

Automatic SQL Server Backup Utility using Sqlserver Agent

It is a sample C# (Visual Studio) application for Automatic Sql server Backup Utility using sqlserveragent. I have used SQL-DMO dll. This article will show you how to create a automatic backup in Sql server.
This code should work on any PC use VB.NET and installed SQL Server(any edition or Client Components for SQL Server.
SQLDMO (Which installed always bt MS SQL Serveror MS SQL Server Client Tools
To do:

  • First enter your SQL Server username and password on corresponding Text Box.
  • Set backup Start date & Backup Time
  • After Finishing this then please check manually it will working or not
  • Manual working procedure:
    • Run Sql sever enterprise Manager
    • Select management Option
    • Open Sql server agent
    • Open Jobs window
    • Check whether job item exist or not
    • Right click on newly created job item then, we will get one
    • Popup menu, then select start job
    • After finish the job then check folder "D:\backup" bkp file created or not

Add reference to SQL-DMO dll

You can do this by right clicking the project in Solution Explorer, then selecting 'Add Reference', COM components and the latest version of "Microsoft SQLDMO Object Library".

Available Server

public void dIsplayServerList(ComboBox cboListName)
{
    try
    {
        SQLDMO.Application oSQLServerDMOApp = new SQLDMO.Application();
        Info.informationLayer info = new Info.informationLayer();           
        SQLDMO.NameList oNameList;
        oNameList = oSQLServerDMOApp.ListAvailableSQLServers();
        for (int intIndex = 0; intIndex <= oNameList.Count - 1; intIndex++)
        {
            if (oNameList.Item(intIndex as object) != null)
            {
                cboListName.Items.Add(oNameList.Item(intIndex).ToString());
            }
        }
        if (cboListName.Items.Count > 0) cboListName.SelectedIndex = 0;
        else cboListName.Text = "(Local)";
        }
    catch
    {
}
}

Available databases

public void dIsplayDatabases(ComboBox cboDatabase,Info.informationLayer info)
{
    try
    {
        SQLDMO._SQLServer SQLServer = new SQLDMO.SQLServerClass();
        cboDatabase.Items.Clear();
        SQLServer.Connect(info.strServerName,info.strLoginName,info.strPwd);
        foreach (SQLDMO.Database db in SQLServer.Databases)
        {
            if (db.Name != null)
                cboDatabase.Items.Add(db.Name);
        }
        cboDatabase.Sorted = true;
        if (cboDatabase.Items.Count == 0)cboDatabase.Text = "<No databases found>";
    }
    catch (Exception err)
    {
       info.ErrorMessageDataLayer = err.Message;
    }
}
Create Job on Server Agent:
public void CreateJob_Sql(Info.informationLayer info)
{
    try
    {
        SQLDMO._SQLServer SQLServer = new SQLDMO.SQLServerClass();
        SQLDMO.Job SQLJob = new SQLDMO.Job();
        SQLDMO.JobSchedule SQLSchedule = new SQLDMO.JobSchedule();
        SQLServer.Connect(info.strServerName, info.strLoginName, info.strPwd);
        switch (SQLServer.JobServer.Status)
        {
            case SQLDMO_SVCSTATUS_TYPE.SQLDMOSvc_Stopped:
            SQLServer.JobServer.Start();
            SQLServer.JobServer.AutoStart = true;
            break;
        }
        SQLJob.Name = info.strDatabaseName;
        SQLJob.Description = "Check and Backup" + info.strDatabaseName;
        SQLServer.JobServer.Jobs.Add(SQLJob);
        SQLJob.Category = "Database Maintenance";
        SQLDMO.JobStep aJobStep = new SQLDMO.JobStep();
        aJobStep.Name = "Step 2: Backup the Database";
        aJobStep.StepID = 1;
        aJobStep.DatabaseName = info.strDatabaseName;
        aJobStep.SubSystem = "TSQL";
        //------>>> If BackUp Folder is Not Found then create BackUp Folder                
        string   DirectoryName = "D:\\BackUp";
        if (Directory.Exists(DirectoryName)==false)
        {
            System.IO.Directory.CreateDirectory(DirectoryName);
        }
        //------>>>
        string sExt;
        sExt="EXEC master.dbo.xp_sqlmaint '-S " + info.strServerName + " -U " + info.strLoginName + " -P " + info.strPwd + "  -D " + info.strDatabaseName + " -CkDB -CkAl -CkCat -BkUpMedia DISK -BkUpDB D:\\Backup  -BkExt BAK -DelBkUps 2weeks -BkUpOnlyIfClean -Rpt D:\\Backup\\BackDB_Checks.txt'";
        aJobStep.Command = sExt;
        aJobStep.OnSuccessAction = SQLDMO_JOBSTEPACTION_TYPE.SQLDMOJobStepAction_QuitWithSuccess;
        aJobStep.OnFailAction = SQLDMO_JOBSTEPACTION_TYPE.SQLDMOJobStepAction_QuitWithFailure;
        SQLJob.JobSteps.Add(aJobStep);
        SQLJob.ApplyToTargetServer(info.strServerName);
        aJobStep.DoAlter();
        SQLJob.Refresh();
        aJobStep.Refresh();
    }
    catch (Exception Err)
    {
        info.ErrorMessageDataLayer = Err.Message;
    }
}

Create Job shedule on  server Agent:

public void CreateShedule_Sql(Info.informationLayer info)
{
    try
    {
        //it will take bkp every week 2 day
        SQLDMO.Job SQLJob = new SQLDMO.Job();
        SQLDMO._SQLServer SQLServer = new SQLDMO.SQLServerClass();
        SQLDMO.JobSchedule SQLSchedule = new SQLDMO.JobSchedule();
        SQLServer.Connect(info.strServerName, info.strLoginName, info.strPwd);
        SQLJob = SQLServer.JobServer.Jobs.Item(info.strDatabaseName);
        // create a new JobSchedule object
        SQLSchedule.Name = "Weekly Backup";
        SQLSchedule.Schedule.FrequencyType = SQLDMO.SQLDMO_FREQUENCY_TYPE.SQLDMOFreq_Weekly;
        SQLSchedule.Schedule.FrequencyInterval = 2;
        SQLSchedule.Schedule.FrequencyRecurrenceFactor = 2;
        // // start on Mar22, 2015 - at 12.55
        SQLSchedule.Schedule.ActiveStartDate = info.intStartDate;
        SQLSchedule.Schedule.ActiveStartTimeOfDay = info.intStartTime;
        ////  this schedule has no end time or end date
        SQLSchedule.Schedule.ActiveEndDate = 99991231;
        SQLSchedule.Schedule.ActiveEndTimeOfDay = 235959;
        ////  add the schedule to the Job
        SQLJob.BeginAlter();
        SQLJob.JobSchedules.Add(SQLSchedule);
        SQLJob.DoAlter();
        //SQLJob.JobSchedules.Refresh();
        info.ErrorMessageDataLayer = "New Sql Job [Databasename= " + info.strDatabaseName + " ]Sucessfully Created.  ";
    }
    catch (Exception err)
    {
        info.ErrorMessageDataLayer = err.Message;
    }
}

Syntax (SQL Server)

xp_sqlmaint 'switch_string'
[
    [-S server_name[\instance_name]]
    [-U login_ID [-P password]]
    {
        [ -D database_name | -PlanName name | -PlanID guid ]
        [-Rpt text_file]
        [-To operator_name]
        [-HtmlRpt html_file [-DelHtmlRpt <time_period>] ]
        [-RmUnusedSpace threshold_percent free_percent]
        [-CkDB | -CkDBNoIdx]
        [-CkAl | -CkAlNoIdx]
        [-CkCat]
        [-UpdOptiStats sample_percent]
        [-RebldIdx free_space]
        [-WriteHistory]
        [
            {-BkUpDB [backup_path] | -BkUpLog [backup_path] }
            {-BkUpMedia
                {DISK [    [-DelBkUps <time_period>]
                            [-CrBkSubDir ] [ -UseDefDir ]
                         ]
                | TAPE
                }
            }
            [-BkUpOnlyIfClean]
            [-VrfyBackup]
        ]
    }
]
time_period
number[minutes | hours | days | weeks | months]

Syntax (SQL Server)

sqlmaint
[-?] |
[
    [-S server]
    [-U login_ID [-P password]]
    {
        [ -D database_name | -PlanName name | -PlanID guid ]
        [-Rpt text_file [-DelTxtRpt <time_period>] ]
        [-To operator_name]
        [-HtmlRpt html_file [-DelHtmlRpt <time_period>] ]
        [-RmUnusedSpace threshold_percent free_percent]
        [-CkDB | -CkDBNoIdx]
        [-CkAl | -CkAlNoIdx]
        [-CkTxtAl]
        [-CkCat]
        [-UpdSts]
        [-UpdOptiStats sample_percent]
        [-RebldIdx free_space]
        [-WriteHistory]
        [
            {-BkUpDB [backup_path] | -BkUpLog [backup_path] }
            {-BkUpMedia
                {DISK [    [-DelBkUps <time_period>]
                            [-CrBkSubDir ] [ -UseDefDir ]
                         ]
                | TAPE
                }
            }
            [-BkUpOnlyIfClean]
            [-VrfyBackup]
        ]
    }
]

Best SQL 2014 Hosting Recommendation

ASPHostPortal.com

ASPHostPortal.com provides our customers with Plesk Panel, one of the most popular and stable control panels for Windows hosting, as free. You could also see the latest .NET framework, a crazy amount of functionality as well as Large disk space, bandwidth, MSSQL databases and more. All those give people the convenience to build up a powerful site in Windows server. We offers SQL 2014 hosting starts from $5/month only. We also guarantees 30 days money back and guarantee 99.9% uptime. If you need a reliable affordable SQL 2014 Hosting, we should be your best choice.



SQL 2014 Hosting Tutorial - ASPHostPortal.com :: SQL Server 2014 Analysis, Migrate, and Report Tool

clock November 10, 2014 11:28 by author Mark

Determine which tables and stored procedures would benefit from In-Memory OLTP

With SQL Server 2014 new In-Memory OLTP engine, you can load tables and stored procedures in memory, which provides very fast response times. The goal isn't to load all the database tables and stored procedures in memory, but rather just those tables that are crucial to performance and those stored procedures that have complex logical calculations.

To help you identify which tables and stored procedures will give you the best performance gain after being migrated to In-Memory OLTP, SQL Server 2014 provides the new Analysis, Migrate, and Report (AMR) tool. Built into SQL Server Management Studio (SSMS), the AMR tool consists of the:

  • Transaction performance collector (which collects data about existing tables and stored procedures in order to analyze workloads) and transaction performance analysis reports (which gives recommendations about the tables and stored procedures to migrate to In-Memory OLTP based on the collected data)
  • Memory Optimization Advisor (which guides you through the process of migrating a table to a memory-optimized table)
  • Native Compilation Advisor (which helps you identify T-SQL elements that need to be changed before migrating a stored procedure to a natively compiled stored procedure)

The AMR tool leverages the new Transaction Performance Collection Sets for gathering information about workloads and the Management Data Warehouse (a relational database) to store the collected data. The Transaction Performance Collection Sets includes the:

  • Stored Procedure Usage Analysis collection set (which captures information about stored procedures for a future migration to natively compiled stored procedures)
  • Table Usage Analysis collection set (which captures information about disk-based tables for a future migration to memory optimized tables)

Before you can use the AMR tool, you need to configure the Management Data Warehouse and the data collection process. After showing you how to do so, I'll demonstrate how to run the transaction performance analysis reports and how to use the two advisors.

Configuring the Management Data Warehouse

To configure the Management Data Warehouse, go to Object Explorer in SSMS. Expand the Management folder, right-click Data Collection, select Tasks, and click Configure Management Data Warehouse. This will launch the Configure Management Data Warehouse Wizard.

After the Welcome page, you'll find yourself on the Select Configuration Task page. On this page, select the option to configure a Management Data Warehouse.

  • On the Configure Management Data Warehouse Storage page, you need to specify the name of database that will host the Management Data Warehouse and the name of the server on which that database resides. If you need to create the database, click the New button to create one.
  • On the Map Logins and Users page, you'll find the existing logins allowed for the server that will host the Management Data Warehouse. If needed, you can edit the logins or map users to the administrator, reader, and writer roles for the Management Data Warehouse.
  • On the Complete the Wizard page, you need to verify the Management Data Warehouse configuration. If it's OK, click Finish. When the configuration of the Management Data Warehouse has successfully completed, you should see a page like that in Figure 1.

Figure 1: Verifying Configuration of the Management Data Warehouse

The Management Data Warehouse setup is now finished.

Configuring the Data Collection Process

To configure the data collection process, go to Object Explorer in SSMS. Expand the Management folder, right-click Data Collection, select Tasks, and click Configure Data Collection. This will launch the Configure Data Collection Wizard.

After the Welcome page, you'll find the Setup Data Collection Sets page shown in Figure 2. Besides needing to specify the server and database that will host the Management Data Warehouse, you need to specify the data collector sets. In the list of collection sets, select the Transaction Performance Collection Sets check box so that the data collector will collect statistics for transaction performance issues.

Figure 2: Specifying the Data Collector Sets

If the Management Data Warehouse is located on a different SQL Server instance from the data collector and if SQL Server Agent isn't running under a domain account that has dc_admin permissions on the remote instance, you have to use a SQL Server Agent proxy. If that's the case, be sure to select the Use a SQL Server Agent proxy for remote uploads check box.

Once you're done configuring the Setup Data Collection Sets page, click Finish. When the wizard completes the configuration, you'll have an enabled data collection process that will collect information about all user databases. Note that SQL Server Agent must be started on the instance that will collect the data.

In the SQL Server Agent's Jobs folder, you'll see the jobs used to collect data from your workloads and the jobs used to upload the collected data into the Management Data Warehouse. The data collection jobs use the naming convention collection_set_N_collection, where N is a number. The upload jobs use the naming convention collection_set_N_upload, where N is a number.

By default, the AMR tool collects data from three dynamic management views every 15 minutes for both the Stored Procedure Usage Analysis and Table Usage Analysis collection sets. The upload job runs every 30 minutes for the Stored Procedure Usage Analysis collection set and every 15 minutes for the Table Usage Analysis collection set. If you want to speed your upload, you can execute these jobs manually. Uploading the data has a minimal impact on performance.

Running the Transaction Performance Analysis Reports

To access the recommendations based on the information collected about all your user databases on the workload server, you need to run the transaction performance analysis reports. To access them, right-click your Management Data Warehouse database, select Reports, choose Management Data Warehouse, and click Transaction Performance Analysis. From the Transaction Performance Analysis Overview page, you can choose to run three reports, depending on what type of information you need:

  • Recommended Tables Based on Usage
  • Recommended Tables Based on Contention
  • Recommended Stored Procedures Based on Usage

Recommended Tables Based on Usage. This report tells you which tables are the best candidates for migration to In-Memory OLTP based on their usage. Figure 3 shows a sample report. On the left side, you can select the database and how many tables you'd like to see from that database. The chart will then show the selected tables. The horizontal axis represents the amount of work needed to migrate a table to In-Memory OLTP. The vertical axis represents the gains you'll achieve after migrating the table. The best candidates for In-Memory OLTP are located in the top right corner. As you can see, they can be easily migrated and will give you the best performance gain.

Figure 3: Determining Which Tables Are the Best Candidates for Migration Based on Usage

You can access a detailed report for a table by clicking its name in the chart. As Figure 4 shows, this report provides the table's access statistics (e.g., lookups, range scan) and contention statistics (e.g., latches, locks), as well as when this information was captured.

Figure 4: Reviewing the Detailed Performance Statistics for a Table

Recommended Tables Based on Contention. This report tells you which tables are the best candidates for migration to In-Memory OLTP based on their contention. If you compare the contention analysis report in Figure 5 with the usage analysis report in Figure 3, you'll see that they're very similar.

Figure 5: Determining Which Tables Are the Best Candidates for Migration Based on Contention

You can select the database and how many tables you'd like to see from that database. The resulting chart shows the amount of work needed to migrate the tables (horizontal axis) and the gains you'll achieve after migrating them (vertical axis). In the top right corner, you'll find the best candidates for migration based on contention. You can click a table name in the chart to access a detailed report showing the table's statistics. This report provides the table's access and contention statistics.

Recommended Stored Procedures Based on Usage. This report shows you which stored procedures are the top candidates for an In-Memory OLTP migration based on their usage (i.e., total CPU time). After selecting the database and how many stored procedures you'd like to see from that database, the resulting chart shows the top candidates for migration, as Figure 6 shows.

Figure 6: Seeing Which Stored Procedures Are the Top Candidates for Migration Based on Usage

If you want to see the detailed usage statistics for a specific stored procedure, you can click its blue bar. Figure 7 shows an example of the report you'll receive.

Figure 7: Reviewing the Detailed Usage Statistics for a Stored Procedure

Using the Memory Optimization Advisor

  • After you know which tables you want to migrate to In-Memory OLTP, you can use the AMR tool's Memory Optimization Advisor to help you with the migration process. To access this advisor, open Object Explorer in SSMS and navigate to the table you want to migrate. Right-click the table and choose Memory Optimization Advisor.
  • The advisor will launch with the Introduction page, which you can read or skip. Clicking Next brings you to the Migration Optimization Checklist page, where the advisor will check to see if your table can be migrated. If one or more validation items fail, the migration process will stop. If needed, you can generate a report for this analysis. If all you see are green checkmarks, your table doesn't have any features that could prevent the migration process, in which case you can proceed to the next page.
  • On the Migration Optimization Warnings page, you'll find important information about what isn't supported in memory-optimized tables and other types of issues. The issues listed won't prevent the table from being migrated, but they might cause other objects to fail or behave in an unexpected manner.

If a warning applies to the table you selected for migration, an exclamation point in a yellow triangle will appear next to the warning, as shown in Figure 8.

Figure 8: Reviewing the Migration Optimization Warnings

In this case, the selected table has an unsupported French_CI_AS collation on the indexed column named Person_OnDisk_Name. (Only BIN2 collations are supported for indexes in memory-optimized tables.) Thus, the index collation will need to be changed later in the migration process.

Figure 9: Reviewing the Optimization Options

On the Review Optimization Options page, which Figure 9 shows, you have the option to change the defaults listed for the:

  • Name of memory-optimized file group (only one memory-optimized file group is allowed per instance)
  • Logical filename
  • Path where the logical file will be saved
  • New name given to the original table (the original table is renamed to prevent naming conflicts)

You can also choose to copy data from the original table to the new memory-optimized table during the migration process, and you can change the durability of the memory-optimized table. By default, its DURABILITY option will be set to schema_and_data, but you can change it to schema_only by selecting the Check this box to migrate this table to a memory-optimized table with no data durability option. If you do so, the data will be lost after the SQL Server service is restarted. In other words, just the table's schema is persistent. Finally, the Review Optimization Options page shows the estimated current memory cost for the memory-optimized table. If there isn't sufficient memory, the migration process might fail.

Once you're done with the Review Optimization Options page, you can click Next to go to the Review Primary Key Conversion page. When the migration process begins, it will start by converting the primary key. You can convert it to:

  • A nonclustered hash index, which gives the best performance for point lookups. If you select this option, you also need to specify the bucket count, which should be twice the expected number of rows.
  • A nonclustered index, which gives the best performance for range predicates.

For each index you have in the table being migrated, you'll be presented with a Review Index Conversion page that has been populated with the columns and data types for that index. The options you can configure in the Review Index Conversion page are similar to those in the Review Primary Key Conversion page. In this case, for the indexed column Person_OnDisk_Name with the unsupported French_CI_AS collation, you'd have to select BIN2 collation as the Char data type.

On the Verify Migration Actions page, you'll see all operations that will be performed to migrate your table to In-Memory OLTP. You have the option to script those operations by clicking the Script button. After verifying all the options, you can click the Migrate button to start the migration process.

Figure 10 shows how the new memory-optimized table appears in SSMS. If you view its properties, you'll see that the Memory optimized property is set to True and that the schema and data are durable for this table.

Figure 10: New Memory-Optimized Table in SSMS

In Figure 10, you can also see how the original table has been renamed.

Using the Native Compilation Advisor

After you know which stored procedures you want to migrate to In-Memory OLTP, you can use the AMR tool's Native Compilation Advisor to help you with their migration. To access this advisor, open Object Explorer in SSMS and navigate to the stored procedure you want to migrate. Right-click the stored procedure and choose Native Compilation Advisor.

After clicking through the Welcome page, you'll be presented with the Stored Procedure Validation page, which will give you warnings if your stored procedure contains some T-SQL elements that aren't supported by native compilation. If the stored procedure is valid, it can become a natively compiled stored procedure without modification. However, the Native Compilation Advisor doesn't migrate stored procedures like the Memory Optimization Advisor migrates tables. You have to do the migration on your own.

If the stored procedure has unsupported T-SQL elements, the validation will fail. To see the details about the unsupported elements, you need to click Next to go to the Stored Procedure Validation Result page, which Figure 11 shows.

Figure 11: Reviewing the Unsupported T-SQL Elements

You have to modify the unsupported elements before you can migrate your stored procedure to a natively compiled stored procedure.

Eliminate the Guesswork

The AMR tool is useful because it eliminates the guesswork in determining which tables and stored procedures would benefit from In-Memory OLTP. After identifying which tables to migrate, you can use the Memory Optimization Advisor to quickly migrate them. Although the Native Compilation Advisor can help you identify the T-SQL elements you need to change before migrating your stored procedure to a natively compiled one, it unfortunately doesn't guide you through the migration process.

 



SQL 2014 Hosting Tutorial - ASPHostPortal.com :: The Best Way to Create a Table in SQL Server 2014

clock October 24, 2014 07:04 by author Ben

Seeing as our database is actually a task-tracker database, let us get in touch with our initial table "Tasks". This desk will hold all duties - regardless of their status (eg. done, to do, in progress, and so on). Then we are able to develop yet another table known as "Status". Then when our tables contain information, we'll be capable of operate queries towards these tables to discover what jobs have to be carried out and which of them are in a offered position, and so on.

But let's not get forward of ourselves. Let's develop our first table.

They are the measures to make a table in a SQL Server 2014 databases using SQL Server Administration Studio (SSMS).

  1. Ensuring you have the correct database expanded (in our case, the TaskTracker database), right click on the Tables icon and select Table... from the contextual menu:

  2. A new table will open in Design view. While you have this screen open, do the following:
    • Utilizing the values in the screenshot, full the details inside the Column Name column, data Type column, and allow Nulls column.
    • Make the TaskId column a Primary Key discipline by right-clicking the button close to TaskId (i.e. exactly the same area exactly where the true secret seems in the subsequent screenshot) and picking Set Primary Key.
    • Make the TaskId column an identity column by placing Is identity to yes (you can discover this feature underneath the Id Specification area in the bottom pane). Be aware that to set values in the base pane, you should pick the column name within the leading pane initial. We are environment this column to be an auto-number column - it's going to immediately produce a brand new amount for every document that is created.
    • Set the Default Price from the DateCreated column to (getdate()). (This will automatically insert the present date into that field for each new file).



    What we are carrying out is creating the column names, specifying the sort of data that may be entered into them, and setting default values. Restricting the data sort for each column is extremely crucial and aids maintain data integrity. For example, it may stop us from accidentally entering a task title right into a field for storing the existing day. SQL Server will avoid information from getting into tables in which the data does not adhere towards the rules that we have established for each column.

  3. Save the table by selecting File > Save Table_1 or by right-clicking on the Table's tab and selecting Save Table_1 from the contextual menu:

  4. When prompted, name your table (we'll call it Tasks):


Your New Table

Now that you've created a new table, it will appear under your database in the Tables section. If you don't see it immediately, try refreshing the Object Explorer. You can do this by right-clicking on Tables and clicking Refresh from the contextual menu:

Here's a screenshot of the table with the Columns folder expanded:




SQL 2014 Hosting Tutorial :: How to Create Histogram Chart in SQL

clock September 15, 2014 08:42 by author Ben

SQL Server 2014 will be an amazing release regarding all the various performance enhancements that are part of this new release. And know I wanna tell you about how to create Histogram Chart in SQL.

In this tips we will create a histogram chart in SQL 2014 to show how to aggregate data will very little effort.

Step 1
Let's create a sample table called Employee that has columns EmpID and EmpAge with the data as shown in the below screenshot.

Step 2
Create a new SSRS report and configure it to use the data from the table we just created. Add a bar chart to the report and configure it as shown in the below screenshot.

Step 3
Execute/Preview this report and your report should look like the below screenshot and you will see data listed for all fifteen employees.

In reality, an employee table can contain records for hundreds to thousands of employees and therefore if the requirement is to analyze age distribution this type of report won't serve the purpose. A typical approach to solve this issue would be to retrieve the count of employees falling into a few predefined age categories and show it in a distribution chart like a pie-chart. In the next few steps we will see how a histogram chart can be a much simpler approach.

Step 4
Select the EmpAge chart series and open the properties window. In the CustomAttribute category, select "ShowColumnAs" property and set the value as "Histogram" as shown in the below screenshot.

Step 5
Execute the report and you should find results similar to the below screenshot. This is a histogram chart, but the problem with this chart is that by default the chart has selected all fifteen distributions, so you get one employee for each age category which is not very helpful.

Step 6
Let's say we want to see the data in three age groups 20 - 25, 25 - 30 and 30 - 35 and the number of employees in each age group. In the CustomAttribute category, you will find a property "HistogramSegmentIntervalWidth" and the default value is zero. Change this value to "5", so that the age group we have is divided into 3 categories as desired. Execute the report and the report should look like the below screenshot. This chart shows 4 employees in the 20 - 25 group, 5 employees in the 25 - 30 group and 6 employees in the 30 - 35 group.

Also note that the "Percentage of Total" axis is generated and calculated automatically without any programming efforts and this axis is very useful in statistical analysis. This type of axis is not possible out-of-box in charts like pie-charts and hence charts such as histogram charts are preferred.



Reason Why you Must Choose ASPHostPortal.com
ASPHostPortal.com offers the newest Microsoft SQL 2014 database with all our hosting plans. We are your dependable SQL web hosting provider who will fulfill your needs!


Full Remote Access
We allow you full remote connectivity to your SQL Server 2014 Hosting database and do not restrict access in any way.

Easily transfer your existing SQL Server database
With our SQL Server hosting package, there's no need to rebuild your database from scratch should you wish to transfer an existing SQL Server database to us. If you already have a database hosted elsewhere, you can easily transfer the contents of your database using SQL Server Management Studio which is fully supported by our packages. SSMS provides you with an Import/Export wizard which you can use to upload your data and stored procedures with a couple of clicks.



SQL Server 2014 Hosting with ASPHostPortal.com :: How to Restart an Interrupted SQL Server Database Restore

clock August 23, 2014 09:53 by author Kenny

SQL Server is Microsoft's relational database management system (RDBMS). It is a full-featured databse primarily designed to compete against competitors Oracle Database (DB) and MySQL.

Like all major RBDMS, SQL Server supports ANSI SQL, the standard SQL language. However, SQL Server also contains T-SQL, its own SQL implemention. SQL Server Management Studio (SSMS) (previously known as Enterprise Manager) is SQL Server’s main interface tool, and it supports 32-bit and 64-bit environments.

In this article, we will tell you about how to restart an interrupted SQL Server Database Restore.
Have you ever restored a large database on a Failover Cluster Production Server and while the restore was in progress, due to network failure, the restore failed? Once the SQL Server came up on the other node all the databases came up, except for the database which you were restoring prior to the failover. In this tip we will take a look at the command RESTORE DATABASE...WITH RESTART to see how this command can be helpful during such scenarios.

Here is the solution

The RESTORE DATABASE...WITH RESTART command is a very useful command which is available in SQL Server 2005 and higher versions. A Database Administrator can use this command to finish restoring an interrupted database restore operation.

In the below snippet you can see that ProductDB is in a (Restoring...) state once the SQL Server came online after the unexpected failure.

During such scenarios one can execute the RESTORE DATABASE...WITH RESTART command to successfully complete the database restore operation.

Below are two commands.  The first gets a list of the backups on the file and the second does the actual restore with the restart option.

-- get backup information from backup file
RESTORE FILELISTONLY
FROM DISK ='C:\DBBackups\ProductDB.bak'
GO

-- restore the database
RESTORE DATABASE ProductDB
FROM DISK ='C:\DBBackups\ProductDB.bak'
WITH RESTART
GO

Below you can see that after running the RESTORE DATABASE...WITH RESTART command the database was successfully restored allowing user connectivity.



Cheap SQL SSRS 2014 Hosting :: How to Configure Available Memory for SQL Server Reporting Services 2014

clock July 18, 2014 07:35 by author Ben

Reporting Services is a server-based reporting platform that provides comprehensive reporting functionality for a variety of data sources. Reporting Services includes a complete set of tools for you to create, manage, and deliver reports, and APIs that enables developers to integrate or extend data and report processing in custom applications. Reporting Services tools work within the Microsoft Visual Studio environment and are fully integrated with SQL Server tools and components.

Today we're going to cover how to configure available memory for SQL Server Reporting Services 2014. If you need to configure the amount of memory available to an instance of SSRS 2014 you have to get your hands dirty and edit the RsReportServer.config file. The RsReportServer.config file stores settings that are used by Report Manager, the Report Server Web service, and background processing.

The location of the rsconfile file is generally:

\Program Files\Microsoft SQL Server\MSRS1111.MSSQLSERVER\Reporting Services\ReportServer

Within the RsReportServer.config file, configuration settings that control memory allocation for the report server include WorkingSetMaximum, WorkingSetMinimum, MemorySafetyMargin, and MemoryThreshold. If you were to open the file you will see that the WorkingSetMinimum and WorkingSetMaximum are not present by default.

<Service>
 <IsSchedulingService>True</IsSchedulingService>
   <IsNotificationService>True</IsNotificationService>
     <IsEventService>True</IsEventService>
       <PollingInterval>10</PollingInterval>
         <WindowsServiceUseFileShareStorage>False</WindowsServiceUseFileShareStorage>
           <MemorySafetyMargin>80</MemorySafetyMargin>
         <MemoryThreshold>90</MemoryThreshold>
       <RecycleTime>720</RecycleTime>
    <MaxAppDomainUnloadTime>30</MaxAppDomainUnloadTime>
 <MaxQueueThreads>0</MaxQueueThreads>


This is because you have to enter them yourself, as if you are hosting multiple applications on the same computer and you determine that the report server is using a disproportionate amount of system resources relative to other applications on the same computer.

<Service>
  <IsSchedulingService>True</IsSchedulingService>
    <IsNotificationService>True</IsNotificationService>
      <IsEventService>True</IsEventService>
        <PollingInterval>10</PollingInterval>
          <WindowsServiceUseFileShareStorage>False</WindowsServiceUseFileShareStorage>
        <MemorySafetyMargin>80</MemorySafetyMargin>
      <MemoryThreshold>90</MemoryThreshold>
    <RecycleTime>720</RecycleTime>
 <WorkingSetMaximum>786432</WorkingSetMaximum>
<WorkingSetMinimum>524288</WorkingSetMinimum>
 <MaxAppDomainUnloadTime>30</MaxAppDomainUnloadTime>
   <MaxQueueThreads>0</MaxQueueThreads>


The Reasons To Use SQL Reporting Service (SSRS) 2014 Hosting with ASPHostPortal.com

  • Fully Integrated with SharePoint
  • The report development environment is a Standard Microsoft Platform - SSRS Reports are developed in BIDS (Business Intelligence Development Studio).
  • Customizable Report Rendering - SSRS provides a .NET Web Service programmatically accessible to extend the delivery of reports beyond the browser. The SSRS reports can be rendered to HTML. PDF(Portable Document Format), Microsoft Excel, XML, MHTML (MIME HTML), TIFF (Tagged Image File Format). Microsoft Word, and ATOM. The SSRS .NET Web Service allows embedding reports in custom applications where the look and feel of the report viewer can be easily controlled and customized.
  • Mobile Support - Starting SQL Server 2012 Service Pack 1 (SP1), SSRS supports viewing and basic interactivity with reports on Microsoft Surface devices and devices with Apple iOS6 and Apple Safari Browser such as iPAD. SSRS reports can also be view on Windows 8 devices.


SQL Server Hosting with ASPHostPortal.com :: How to Backup and Restore Your Database with PowerShell Commands

clock July 10, 2014 09:20 by author Ben

PowerShell is Microsoft’s new command-line shell and scripting language that promises to simplify automation and integration across different Microsoft applications and components. Database professionals can leverage PowerShell by utilizing its numerous built-in cmdlets, or using any of the readily available .NET classes, to automate database tasks, simplify integration, or just discover new ways to accomplish the job at hand.

Windows PowerShell commands can be a valuable addition to your SQL Server management tools. PowerShell is going to replace SQL Server Management Studio (SSMS) anytime soon, it can be used for a wide range of scripted management tasks. PowerShell can run T-SQL commands and also work with objects outside of the SQL Server database. You can use the SQL Server PowerShell Provider to navigate and manage SQL Server database objects, and PowerShell scripts can be run by SQL Agent.

Here is a working Windows PowerShell script to perform a FULL database backup against the Northwind database, storing the backup file in your file system.

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$s = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "LOCALHOST\SQL2005_1"

#Create a Backup object instance with the Microsoft.SqlServer.Management.Smo.Backup namespace
$dbBackup = new-object ("Microsoft.SqlServer.Management.Smo.Backup")

#Set the Database property to Northwind
$dbBackup.Database = "Northwind"

#Add the backup file to the Devices collection and specify File as the backup type
$dbBackup.Devices.AddDevice("D:\PSScripts\backups\NWind_FULL.bak", "File")

#Specify the Action property to generate a FULL backup
$dbBackup.Action="Database"

#Call the SqlBackup method to generate the backup
$dbBackup.SqlBackup($s)


Since you won't be performing backups of just a single database, it would be better if we loop the entire script in a For-Each cmdlet iterating thru the Databases collection of the Server object.

[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
$s = new-object ("Microsoft.SqlServer.Management.Smo.Server") $instance

$bkdir = "D:\PSScripts\backups" #We define the folder path as a variable
$dbs = $s.Databases
foreach ($db in $dbs)
{
     if($db.Name -ne "tempdb") #We don't want to backup the tempdb database
     {
     $dbname = $db.Name
     $dt = get-date -format yyyyMMddHHmm #We use this to create a file name based on the timestamp
     $dbBackup = new-object ("Microsoft.SqlServer.Management.Smo.Backup")
     $dbBackup.Action = "Database"
     $dbBackup.Database = $dbname
     $dbBackup.Devices.AddDevice($bkdir + "\" + $dbname + "_db_" + $dt + ".bak", "File")
     $dbBackup.SqlBackup($s)
     }
}


There are a lot of different reasons why we need to restore databases, so there are a lot more options with restores than there are with backups. The easiest way to demonstrate a restore is to simply restore a database from a full backup, setting the option to overwrite the existing database.

Restore-SqlDatabase -ServerInstance TESTSQL -Database Northwind`
-BackupFile "E:\Backup\Northwind_db_20130420153024.bak" -ReplaceDatabase


Cheap SQL Hosting with ASPHostPortal.com
Providing the best security, compliance, performance, and managed service separates ASPHostPortal.com from other hosting companies. MS SQL server supports our commitment to providing service options the businesses that choose ASPHostPortal.com demand. Use the Promo Code "DBSQL" (without quotes) and receive double SQL Server Space!



About ASPHostPortal.com

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Sign in