European Windows 2012 Hosting BLOG

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

European Windows 2012 Hosting - Amsterdam :: Windows Server 2012 Hyper-V Replica

clock July 29, 2013 07:30 by author Scott

For small businesses, there’s often no easy answer when it comes to disaster recovery. With many storage and DR options out of reach, finding an affordable way to protect data can be challenging. But in Hyper-V Replica, Microsoft offers a new path to DR for many SMBs.

Usage Scenarios

Hyper-V Replica, one of many operational and performance improvements to Hyper-V in Windows Server 2012, allows users to replicate virtual machines over slow, unreliable network links. Replica is purely a DR solution and doesn’t replace clustering, but it can be used to replicate clusters of Hyper-V servers.

With Replica, SMBs can set up a DR site at a branch office (or at a remote site hosted by a service provider) and use Hyper-V to replicate the contents of selected VMs at 5-minute intervals.

Unlike most enterprise-grade replication technologies, Hyper-V Replica does not require a reliable, high-bandwidth network link between primary and DR sites. It’s designed to work with links that don’t run over dedicated lines, such as broadband or asymmetric digital subscriber line (ADSL) technologies, which may be subject to short outages.

The Replication Process

To begin, Hyper-V Replica creates an initial copy of the primary server. That file is then copied over, either manually or over the network, to the Replica server at the recovery site. Replica then writes to a log file (Hyper-V Replica Log, or HRL) on the primary server every time there’s a write operation. This HRL file is replicated on the Replica server and is replayed every 5 minutes, in reverse, replicating only changes made since the last replay.

Due to the 5-minute replication frequency, if the primary server goes offline, up to 10 minutes of data might be lost. If Hyper-V can’t replicate at the 5-minute interval, an alert is written to the event log. If replication fails for more than 30 minutes, the Replica server is put into a failed state and replication must be manually restarted — so it’s possible that an hour of data could be lost at the DR site.

The replication schedule is designed to keep the state of the operating system consistent after a failover to the Replica server. If it’s critical that applications remain consistent, Hyper-V Replica can be set to create additional Volume Shadow Copy Service (VSS) recovery points for this purpose.

Ensuring Security with Hyper-V Replica

Before implementing Hyper-V Replica, Windows Firewall must be configured to allow the necessary replication traffic to pass through. This applies as well to any other firewalls that separate the corporate intranet from the DR site. Replica comes with default Windows Firewall rules, but they must be enabled manually in the Windows Firewall with Advanced Security management console. There are two inbound rules:

  1. Hyper-V Replica HTTP Listener (TCP-In)
  2. Hyper-V Replica HTTPS Listener (TCP-In)


The HTTPS rule is needed only if certificate-based authentication is used. Hyper-V in Windows Server 2012 also includes a new simple authorization model in which a Hyper-V Administrators group is created on each server that hosts the Hyper-V role. Hyper-V Administrators can configure Replica servers to accept incoming connections from specific Hyper-V servers.

There are two different types of authentication that Hyper-V Replica uses. Kerberos, a network authentication protocol, is the default option, but certificate-based authentication allows replication between primary and Replica servers to be encrypted.

Integrated authentication uses the Kerberos protocol and can be established between trusted Active Directory domains. In the absence of Active Directory, X.509v3 certificates can be used instead of Kerberos. Replication Authorization Tags protect Replica VMs residing on a single server in a data center, which is useful for hosting service providers that need to stop clients from gaining access to Replica VMs other than their own.

Installing Hyper-V Replica

Replica works in both workgroup and domain scenarios, and Replica servers don’t need to be in the same AD domain as primary servers. The first step is to configure a Replica server in a branch office by adding the Hyper-V role. This is done either with Server Manager or by using PowerShell. Once the role is installed, the server must be restarted. The following PowerShell command will install the Hyper-V role and management tools:

Install-WindowsFeature -Name Hyper-V –IncludeManagementTools

Now open Hyper-V Settings in the Actions pane of Hyper-V Manager, click on Replication Configuration and select Enable this computer as a replica server in the Details pane. Choose an authentication method, and don’t forget to enable the default Windows firewall rules. In the Authorization and storage section, the system can be set to allow replication from any authenticated server or from a specific list of servers.

VMs in the primary site can be enabled for replication with a simple wizard. In Hyper-V Manager, select a VM in the Details pane, right-click the VM and choose Enable Replication. The wizard allows a choice in how to perform the initial replication, which by default happens over the network. That may not be feasible or desirable over a slow network, so there’s also the option to perform the first replication using external media and then import the data at the Replica site.

Failover

Hyper-V has a new section in the configuration option for each VM called Failover TCP/IP, where both alternative IPv4 and IPv6 addresses can be provided should the DR site have a completely different IP addressing scheme than the primary site. These addresses are used when a failover action is performed.

There are three kinds of failover:

  • Test Failover
  • Planned Failover
  • Unplanned Failover

A Test Failover allows Hyper-V administrators to perform a failover without disrupting the primary server.

A Planned Failover should involve no data loss; the primary server will temporarily become the Replica server for the VM that has failed over. The VM on the primary server needs to be shut down beforehand, and the primary server must be configured as a Replica server.

An Unplanned Failover is not expected and is initiated from the Replica server at the DR site. A VM on the Replica server will be started from a Replica recovery point. This could result in some data loss.



European SQL 2012 Hosting - Amsterdam :: SQL 2012 Always On Hosting on Cloud

clock July 17, 2013 10:45 by author Scott

It has traditionally been almost impossible to architect infrastructure-class, highly available (HA) SQL Server solutions using shared storage in the public cloud. Recently Microsoft announced support for some System Center 2012 SP1 applications to work with SQL AlwaysOn, a new way to achieve HA SQL. AlwaysOn uses an availability group concept, much like Exchange 2010 database availability groups (DAGs) to achieve clustered HA services without shared storage.

This is good news for architects looking to move management workloads into the public cloud when appropriate. In theory, a pair of powerful VMs in Azure running SQL 2012 AlwaysOn can approach and exceed the HA SLAs expected of many mission critical applications. Figure 1 shows the new dashboard view of AlwaysOn HA availability groups with some System Center 2012 SP1 databases made highly available.

Figure 1

HA SQL is Important. What is the Reason?

Highly available (HA) SQL Server services are the cornerstone of many enterprise database applications. Few enterprise solutions today are deployed on non-HA SQL. Without an HA mechanism for database services, enterprise applications and e-commerce websites cannot offer maximum available uptime. Even perfectly managed servers require periodic restarts for updates and maintenance; and you always need to be prepared for equipment failure such as extended outages of particular servers or disk drives.

The traditional way to offer HA SQL is by creating a SQL Server failover cluster based on shared storage. That is, a storage area network (SAN) presents shelves of disk drives to two or more servers at the same time ("shared storage"). The SAN and shared storage is often the most expensive component in the datacenter. Public cloud solutions abstract you from the storage, and usually don't offer the kind of infrastructure you would need to run a conventional HA SQL failover cluster with shared storage in the cloud.

SQL Server 2012 AlwaysOn, no need for SAN

With SQL Server 2012 AlwaysOn, two or more complete copies of each HA database can exist, synchronized by AlwaysOn technology. The independent database copies are presumed to exist locally in direct attached storage (DAS) on each SQL node, or over on the network using economical Windows Server 2012 SMB 3.0 file shares on dedicated Windows Server 2012 file servers.

- You can use Windows Server 2012 Standard for the SQL server nodes-unlike in previous Windows releases, you can enable the failover cluster feature in the Standard edition of Windows Server 2012 as well as Windows Server 2012 Datacenter.

- SQL Server 2012 does require the Enterprise edition of SQL Server 2012 to use the AlwaysOn feature.

Steps to deploy a SQL Server 2012 AlwaysOn Availability Group

Here are the high-level steps to follow to deploy SQL 2012 AlwaysOn in a SQL 2012 failover cluster (without shared storage).

1. Install Windows Server 2012 in two computers or virtual machines (VMs), each with a single network interface card (NIC).

2. Create a two-node failover cluster without shared storage. You will need a cluster name and an IP address for the cluster network name.

3. Install SQL Server 2012 Enterprise on both computers as if they were going to be stand-alone SQL servers.

  • When you install, use a domain account for the SQL server services.
  • Open the Windows Firewall on ports TCP 1433 and TCP 5022.

4. Create a temporary "seed" database on the first SQL server using SQL Server 2012 Management Studio. This database will be used to establish the AlwaysOn cluster, and then can be deleted after the first production database is deployed.

5. Make sure the database is of the "Full" type model, and perform a SQL Backup job.

6. In the Management Studio, create an AlwaysOn Availability Group and an Availability Group Listener. (The Availability Group Listener is essentially the virtual (or clustered) SQL Server instance. There is a one-to-one relationship between availability groups and listeners.)

  • Assign a DNS name and TCP IP address for the AlwaysOn Availability Group and an Availability Group Listener.
  • Assign a shared network folder that is accessible to all SQL servers that will have AlwaysOn database replicas.

7. At the AlwaysOn High Availability node, right-click and select Add A Database To An Availability Group. If your database is of the Full type and has been backed up, the status will be "Meets Requirements". Click Next.

8. Select that you will perform a full synchronization, using the shared network folder you specified in step 6(b). Click Next.

9. Enter security information to access the primary database replica. Click Next, observe the validation and click Next, and then Finish.

10. Observe after a moment that new database replica on the secondary node in the SQL AlwaysOn availability group has been created, as seen in Figure 2.

Figure 2



European SQL 2008 R2 Hosting - Amsterdam :: Generated LINQ to SQL, SQL Server Profiler, and Provide Final T-SQL Generated

clock July 5, 2013 07:42 by author Scott

If you’re interested in taking a look at the final T-SQL generated by your LINQ to SQL queries then you have a few options available:

  1. Utilise LINQPad which converts your C# LINQ database queries into T-SQL
  2. Execute an SQL Server Profiler trace against the database your application is querying while its running
  3. Understand how ADO.NET translates the LINQ to SQL expression tree into T-SQL so you know what it’s going to output

So first off I’ll provide a brief overview of SQL Server Profiler and what a “trace” is. Then I’ll show you how to configure and run a trace. Finally I’ll throw a few LINQ to SQL examples at a local SQL database and provide the final T-SQL generated.

SQL Server Profiler & Traces

SQL Server Profiler comes packaged with SQL Server so if you’re running SQL Server Management Studio chances are you’ll find a shortcut to this particular tool in amongst the SQL shortcuts, or via the Tools menu option in SQL Server Management Studio. Its primary aim is to analyse, and even replay SQL trace results, for the purpose of troubleshooting, diagnosis, benchmarking, monitoring, etc. As a developer you can imagine how helpful this can be when you want to identify bottlenecks, optimise your system during the testing and performing tuning phase, generate performance reports, etc.

Once you delve into examining SQL events you’ll start to notice that SQL generates a LOT of unique events (well over a hundred) and in order to help isolate the ones you’re looking for you have to create what’s called a trace. The trace defines which SQL events to capture as well as providing very handy filtering and output options.

The trace results are also returned in a tabular fashion which you can browse through within the tool or export for use elsewhere.

Creating a Trace

Start up SQL Server Profiler. The first screen you’ll see will hopefully look like this:

Click on “File” in the menu and select “New Trace…” then select the appropriate connection settings.

You’ll then be presented with a fresh “Trace Properties” window from where you’ll be able to configure your trace.

Leave everything as is on the “General” tab with the exception of the “Use the template:” option which you want to change to “Blank”. This essentially clears the events the trace is going to capture so that we can start from scratch and only add those we want. There are a lot of preconfigured templates but we want to avoid those for now.

Now click on the “Events Selection” tab and you’ll see an array of events all grouped accordingly. We want a specific event called “RPC:Completed” which is under the “Stored Procedures” category.

Select the checkbox to the left of “RPC:Completed”. This tells our trace that we want to capture all events that are fired when a remote procedure call completes it’s execution.

One small but useful tip is to organise how the data will be returned so click on the “Organize Columns…” button and reorder the columns so the “StartTime”, “Duration” and “TextData” are at the top. This means we’ll have our trace results returned in chronological order and each will tell us how long they took to execute in milliseconds and what T-SQL was executed in the first few columns. See below:

Click “OK” to save the column order then click “Run” to proceed.

Congratulations you just created a trace!

Reviewing the Trace for LINQ to SQL queries

Now that the trace is up and running we’ll start to see all stored procedure calls that are completed against any database associated with the connection you chose earlier.

If you fire up a Windows C# application that makes LINQ to SQL calls you’ll start to see them appearing in the trace output. What’s important to clarify at this point is that even if your LINQ to SQL queries aren’t calling a stored procedure the system stored procedure sp_executesql will be executing the queries, and that’s what the trace will be capturing.

See below for an example:

What I’ve selected is a simple LINQ to SQL insert into a table called “ExceptionLog”, and here’s the C# code that generated this call:

var exceptionLog = new ExceptionLog
{
    ExceptionType = exceptionType,
    Message = message,
    AddedDateTime = DateTime.UtcNow
}; 

using (var dataContext = GetDataContext())
{
    dataContext.ExceptionLogs.InsertOnSubmit(exceptionLog);
    dataContext.SubmitChanges();
}

You can use the Pause/Start buttons to halt the trace if need be so you don’t find SQL Server Profiler auto-scrolling to the bottom of the list every time a new procedure is completed.

Here’s another example of a simple LINQ to SQL select:

var query =
    (
        from el in dataContext.ExceptionLogs
        where el.AddedDateTime.Year == 2012
        orderby el.AddedDateTime ascending
        select new ExceptionLog
        {
            ExceptionLogId = el.ExceptionLogId,
            ExceptionType = el.ExceptionType,
            AddedDateTime = el.AddedDateTime
        }
    ).ToList();

And in the trace window we’ll see:

exec sp_executesql N'SELECT [t0].[ExceptionLogId], [t0].[ExceptionType], [t0].[AddedDateTime]
FROM [dbo].[ExceptionLog] AS [t0]
WHERE DATEPART(Year, [t0].[AddedDateTime]) = @p0
ORDER BY [t0].[AddedDateTime]',N'@p0 int',@p0=2012

You can see the exact SQL output. More information is displayed above as well so you can get an idea for what other data is associated with the trace; duration in milliseconds, DatabaseName, RowCounts etc. All very useful.

Here’s another example where I’ve employed the SQL IN operator to retrieve a collection of authorised users. The LINQ to SQL:

var authorisedUserRoleIds = new List
{
    1, // 1 = System Administrator
    2, // 2 = Regional Manager
    3 // 3 = County Manager
}; 

var query =
    (
        from u in dataContext.Users
        join ur in dataContext.UserRoles on u.UserId equals ur.UserId
        where authorisedUserRoleIds.Contains(ur.RoleId)
        orderby u.Surname ascending
        orderby u.FirstName ascending
        select new User
        {
            UserId = u.UserId,
            FirstName = u.FirstName,
            Surname = u.Surname,
            EmailAddress = u.EmailAddress
        }
    ).ToList();

And the resulting SQL:

exec sp_executesql N'SELECT [t0].[UserId], [t0].[FirstName], [t0].[Surname], [t0].[EmailAddress]
FROM [dbo].[User] AS [t0]
INNER JOIN [dbo].[UserRole] AS [t1] ON [t0].[UserId] = [t1].[UserId]
WHERE [t1].[RoleId] IN (@p0, @p1, @p2)
ORDER BY [t0].[FirstName], [t0].[Surname]',N'@p0 int,@p1 int,@p2 int',@p0=1,@p1=2,@p2=3

If you look closely you can see the JOIN, WHERE  clause and ORDER BY  just as you’d expect.

What Next?

This is really a starting point and there is a lot more that can be achieved with SQL Server Profiler further. Some examples being:

If you want to edit your running trace you’ll have to pause it, select the properties option to edit it then get it running again – “File > Properties”.

Another useful event under the SQL group is SP:StmtCompleted. SP:StmtCompleted returns every single statement completed whereas RPC:Completed only returns the last remote procedure executed. So if you called a stored procedure which contained five individual queries from your LINQ to SQL you’d see five SP:StmtCompleted events and one RPC:Completed.

Save the trace you’ve created as a template so that you can reuse it again – “File > Save as Template“. You can even save it into the list of templates that appears in “New Trace” window for easier access or share it amongst your development team.

Apply filters to the trace in the “Events Selection” tab. See the “Column Filters…” button. Useful if you want to identify queries taking longer than 10 milliseconds or just target a given database.

Look into the Database Engine Tuning Advisor tool and how it can analyse trace outputs to help create indexes to boost performance.



MySQL Tutorial :: Backup Data Using mysqldump Utility in MySQL

clock June 25, 2013 07:38 by author Scott

The mysqldump client is a backup program o It can be used to dump a database or a collection of databases for backup or transfer to another SQL server (not necessarily a MySQL server). The dump typically contains SQL statements to create the table, populate it, or both. However, mysqldump can also be used to generate files in CSV, other delimited text, or XML format.

To take dump of a mysql table use below command
-------------------------------------------------------
~/mysql/bin/mysqldump -u root  database_name ORDERS > orders.txt

1.  command to dumb  only tables definitions , not the data “ use –d command”  if path is not set then you need to run that command from mysql/bin directory

./mysqldump -d -u root database_name  ORDERS , CLIENTS , COMPANY  > ~/tmp/test.database.sql

2. Command to recreate table from that file

mysql -u root database_name < ~/tmp/test.database.sql

Easy, right?

 



European SQL Hosting - Amsterdam :: SQL Injection? How to Prevent It?

clock June 19, 2013 08:10 by author Scott

This article talk about what SQL injection is, how can that effect the security of our websites and what steps should be taken to create an ASP.NET application SQL injection proof. SQL injection is the attack in which the user of the website will input some SQL code as input which would result in creating a SQL statement that developers didn't intend to write. These SQL statements could result in unauthorized access, revealing secret user information and sometimes it could even wipe out the entire data lying on the server.

 

Getting to know SQL Injection

Let us take this discussion a little further by looking into the bad coding practices that will make the application prone to the SQL injection attacks. Let us create a simple table that contains username and password of the user for authentication.

Now I will create a small page that lets the user to enter his login credentials and get them validated against the Users table.

Note: Password should never be stored in plain text. This table contains password in plain text just for the sake of simplicity of this article.

The actual code that I will use to authenticate the user contains dynamic SQL that is being created by concatenating strings. This code will return true if the userid and password are found in the database otherwise false.  

public bool IsUserAuthenticated_Bad(string username, string password)
{
    DataTable result = null;
    try
    {
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleDbConnectionString1"].ConnectionString))
        {
            using (SqlCommand cmd = con.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select userID from Users where userID = '" + username + "' and password = '" + password + "'";               

                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    result = new DataTable();
                    da.Fill(result);


                    //check if any match is found
                    if (result.Rows.Count == 1)
                    {
                        // return true to indicate that userID and password are matched.
                        return true;
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        //Pokemon exception handling
    }

    //user id not found, lets treat him as a guest       
    return false;
}

For all the normal users this code will work fine. I can even test it using userid as sampleuser and password as samplepwd and this will work fine. For any other data except this it should say that authentication failed(since this is the only record in the table). The query that will get generated to test this input will be:

select userID from Users where userID = 'sampleuser' and password = 'samplepwd'

Now let us try to inject some SQL into this page. Let me give hacker' or 1=1-- as username and anything in the password(even leave it empty). Now the resultant SQL for this will become:

select userID from Users where userID = 'hacker' or 1=1--' and password = ''

Now when we execute this query the 1=1 clause will always return true(and the password check is commented out. Now irrespective of whatever data user has entered this will SQL return a row making this function return true and in turn authenticating the user. So What I have done now is that I gained access to the website even when I didn't knew the valid user credentials.

How can I curb this problem is something we will look into details in some time. But before that let us also look at one more example of SQL injection just to get little more understanding.

In this second example we will assume that the malicious user somehow got hold of the database schema and then he is trying to manipulate the application to find some confidential information. Lets say we have a page that is supposed to show all the products that are assigned to a user in the organization.

Let us start by looking at the Product table.

Let us now look at the code that is retrieving this data:

public DataTable GetProductsAssigner_Bad(string userID)
{
    DataTable result = null;
    try
    {
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleDbConnectionString1"].ConnectionString))
        {
            using (SqlCommand cmd = con.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select * from Products where AssignedTo = '" + userID + "'";

                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    result = new DataTable();
                    da.Fill(result);
                }
            }
        }
    }
    catch (Exception ex)
    {
        //Pokemon exception handling
    }

    //user id not found, lets treat him as a guest       
    return result;
}

Now if I call this function with the proper data(as normal users would do) then this will show me the results. i.e. If I call this page for sampleuser the resulting query would be:

select * from Products where AssignedTo = 'sampleuser'

Now let me use this query string with this page: userID=' UNION SELECT 0 AS Expr1, password, userID FROM Users -- . Once this data is used with the current code this will show me all the username and passwords from the database. The reason will be quiet clear once we look into the resulting query of this input.

select * from Products where AssignedTo = '' UNION SELECT 0 AS Expr1, password, userID FROM Users --

Now we saw that how string concatenated dynamic SQL is prone to SQL injection. There are many other problems that could be created by injecting SQL. Imagine a scenario where the injected SQL is dropping tables or truncating all the tables. The problem in such cases would be catastrophic.

How to Prevent SQL Injection

ASP.NET provides us beautiful mechanism for prevention against the SQL injection. There are some thumb rules that should be followed in order to prevent injection attacks on our websites.

  • User input should never be trusted. It should always be validated
  • Dynamic SQL should never be created using string concatenations.
  • Always prefer using Stored Procedures. 
  • If dynamic SQL is needed it should be used with parametrized commands.
  • All sensitive and confidential information should be stored in encrypted.
  • The application should never use/access the DB with Administrator privileges. 

User input should never be trusted. It should always be validated

The basic thumb rule here is that the user input should never be trusted. First of all we should apply filters on all the input fields. If any field is supposed to take numbers then we should never accept alphabets in that. Secondly, All the inputs should be validated against a regular expression so that no SQL characters and SQL command keywords are passed to the database.

Both this filtration and validation should be done at client side using JavaScript. It would suffice for the normal user. Malicious users cans till bypass the client side validations. So to curb that all the validations should be done at server side too.

Dynamic SQL should never be created using string concatenations.

If we have dynamic SQL being created using string concatenations then we are always at the risk of getting some SQL that we are not supposed to use with the application. It is advisable to avoid the string concatenations altogether.

Always prefer using Stored Procedures.

Stored procedures are the best way of performing the DB operations. We can always be sure of that no bad SQL is being generated if we are using stored procedures. Let us create a Stored procedure for the database access required for our login page and see what is the right way of doing the database operation using stored procedure.

CREATE PROCEDURE dbo.CheckUser     
      (
      @userID varchar(20),
      @password varchar(16)
      )
AS
      select userID from Users where userID = @userID and password = @password
      RETURN

And now lets have a good version in our code using this stored procedure.

public bool IsUserAuthenticated_Good(string username, string password)
{
    DataTable result = null;
    try
    {
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleDbConnectionString1"].ConnectionString))
        {
            using (SqlCommand cmd = con.CreateCommand())
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = "CheckUser";
                cmd.Parameters.Add(new SqlParameter("@userID", username));
                cmd.Parameters.Add(new SqlParameter("@password", password));

                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    result = new DataTable();
                    da.Fill(result);

                    //check if any match is found
                    if (result.Rows.Count == 1)
                    {
                        // return true to indicate that userID and password are matched.
                        return true;
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        //Pokemon exception handling
    }

    //user id not found, lets treat him as a guest       
    return false;
}

If dynamic SQL is needed it should be used with parametrized commands.

If we still find our self needing the dynamic SQL in code then parametrized commands are the best way of performing such dynamic SQL business. This way we can always be sure of that no bad SQL is being generated. Let us create a parametrized command for the database access required for our Product page and see what is the right way of doing the database operation.

public DataTable GetProductsAssigner_Good(string userID)
{
    DataTable result = null;
    try
    {
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["SampleDbConnectionString1"].ConnectionString))
        {
            using (SqlCommand cmd = con.CreateCommand())
            {
                cmd.CommandType = CommandType.Text;
                cmd.CommandText = "select * from Products where AssignedTo = @userID";
                cmd.Parameters.Add(new SqlParameter("@userID", userID));

                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    result = new DataTable();
                    da.Fill(result);
                }
            }
        }
    }
    catch (Exception ex)
    {
        //Pokemon exception handling
    }

    //user id not found, lets treat him as a guest       
    return result;
}

All sensitive and confidential information should be stored in encrypted.

All the sensitive information should be stored encrypted in the database. The benefit of having this is that even if somehow the user get hold of the data he will only be able to see the encrypted values which are not easy to use for someone who doesn't know the encryption technique used by the application.

The application should never use/access the DB with Administrator privileges.

This will make sure that even if the bad SQL is being passed to the Database by some injections, the database will not allow any catastrophic actions like dropping table.

Note: Refer the sample application attached to see the working examples SQL injection and how to curb them using parametrized commands and stored procedures.



European SQL Hosting - Amsterdam :: Combine Multiple Columns And Records In MS SQL Server

clock May 20, 2013 11:55 by author Scott

In this example i am going to describe how to combine multiple columns and records in one column in MS SQL.

Here is the scenario

I have a table having Employees names and their respective Department names,
now i want to show Employees names separated by comma into one column and respective Department name in another column.

My table schema is shown in the image below

And this is Data into table

I want output in following format

                                  Department                               FirstName
                                   IT                                             amiT,Emp1,Emp5
                                  Admin                                       Shobhit, Emp3,Emp7

and so on

To get this desired result we need to write below mentioned query

1SELECT DISTINCT
2Department,
3EmpNames = substring( ( SELECT ', ' + FirstName
4FROM Employees e2
5WHERE e2.Department = e1.Department FOR XML path(''), elements
6),2,500)
7FROM Employees e1

And the output of this SQL Query would be



European SQL 2012 Hosting - Amsterdam :: Database Backup With Compression in SQL Server 2012

clock May 17, 2013 08:20 by author Scott

In this article, we will see how to do Database Backup Compression in SQL Server 2012. To do that you can use SQL Server Management Studio and also you can use a Transact-SQL statement. So let's have a look at a practical example of how to do database backup with compression. The example is developed in SQL Server 2012 using the SQL Server Management Studio.

To visually create a Database Backup

Now Press F8 to open the Object Browser in SQL Server Management Studio and expend it.

Select database then right-click on the selected database then click on "Task" then click on "Back Up".

This will open the following window:

To specify the destination of the database, select the destination then click on the Add Button. We then see a new dialog box, click on the browse button to choose the location

Now next click on "Options" and the following screen appears:

Now select Compress Backup.

The above image contains three options to select:

  1. The first option, "Use the default server settings" tells the backup to use the server's default backup compression setting. By default, it is set to have backup compression off.
  2. The Second option "Compress Backup" turns backup compression on.
  3. The "Do not compress backup" option turns it off.

Now click again on the "General" option.

Now you will see that the database backup has completed successfully.

 



European Cloud Hosting - Amsterdam :: The Benefits of Using Cloud Hosting

clock May 13, 2013 12:17 by author Scott

There are a number of benefits to cloud hosting, some of which might not directly apply to your business model. The following five benefits of application hosting are those that can certainly apply to every company and the way that they conduct business in the increasingly competitive world that we all live in.

1. Lowered Hardware and Software Investment Costs
Cloud hosting effectively removes the need that your business might otherwise have for large servers. Servers and the maintenance of your servers can be incredibly expensive. Another consideration in terms of cost reductions is that cloud hosting reduces your need to purchase potentially costly software upgrades. Your managed hosting company will shoulder all of the costs to ensure that your dedicated servers are up-to-date and that the version of the application you are using is the most recent.

2. Increased Speed
Because the servers that your applications are hosted on are dedicated to your business needs, you'll notice that the amount of time needed to bring up your application on your laptop or desktop computer is decreased dramatically. Even hosting locally can result in a lot of time spent waiting for the application to load, which then can result in a loss of productivity for your staff.

3. Growth, As Needed
As your need for storage grows, you'll be able to add on extra processing power, extra RAM, and other needed resources as you need them. This means that when you are looking into the costs of managed hosting, you can invest in packages that offer you just enough for now, and then add resources later on as you need them. This type of flexibility can also offer you the potential for significant savings.

4. Lowered Maintenance Costs
Remote application hosting will mean that your business doesn't have the need to have as much hardware onsite. This can result in a decrease in the need to maintain hardware, which can also result in not needing to hired dedicate IT staff. Because cloud hosting uses fewer physical resources at your place of business, you will have less in the way of hardware to maintain, and you will also see a decrease in your over operational costs.

5. Backups - Data Security
One of the key benefits of cloud hosting is that they have exceptional disaster recovery services in place. This means that if one data center experiences an outage, your application and data will be accessible from a separate data center. On the user end you may experience nothing more than a brief delay logging into your application, as the disaster recovery services kick in to ensure that your backed up data is readily available to you when you need it.

There are some definite benefits to cloud hosting, for companies of all sizes. It is worth taking the time to consider just how cloud hosting can make a positive difference in your company's ability to be efficient in all areas of professional excellence. You'll see an increase in productivity, a decrease in IT expenses, and an increase in operational flexibility.



European Visual Studio LightSwitch Hosting - Amsterdam :: How to Deploy LightSwitch in Visual Studio 2012

clock May 3, 2013 07:37 by author Scott

In this article I describe the LightSwitch development environment in Visual Studio 2012. We can easily create a LightSwitch application using Visual Studio LightSwitch 2012.

LightSwitch Development in Visual Studio 2012

Visual Studio LightSwitch automatically creates the User Interface for a DataSource without manually writing any code.

In order to begin our work with LightSwitch 2012 we will perform the following steps:

Step 1

1. Open the Visual Studio 2012.
2. Go to "File" => "New" => "Project..."
3. In "New Project" => "Installed" => "Template"
4. In "Template" => "LightSwitch"
5. Select "LightSwitch Application (Visual C#)".
6. Enter the Name and choose the location.
7. Click "OK".

Step 2

After creating the project a LightSwitch Designer will appear on the screen.

LightSwitch Designer consists of the following two options:

- we can create a new table for our application.
- we can also attach an external database. 

Step 3

Now we will see that Solution Explorer consists of a list of the following items along with two folders:

- Data Sources
- Screens

Here the "Data Sources" folder is used to store user data i.e. "Database Tables" and the "Screens" folder is used where we can create the user interface for our application.

Step 4

When we click on "Create new table" we will get the following image:

Each table consists of an "Id" that is automatically assigned and is also a "Primary Key" of the table.

Step 5

First we will rename the title of the table from "Table" to "ContactTable". Now we will add four additional columns called "Name", "Email", "Age" and "Address" to our table.

Step 6

In order to insert the record we need to create a User Interface screen. When we right-click on the "Screens" Folder we will click on "Add New." It will open the "Add New Screen" dialog window. As the window opens we will select "New Data Screen" from the Screen Template, we will also provide a Screen Name to our screen and choose the database table.

In order to continue we will Click on the "Ok" button. This will create a new UI screen for inserting a new data record by a user.

"Properties" are those where you set properties for various items.

Step 7

When we run the UI screen we get the following.

Step 8

Now we are able to insert a new record without writing any code. We don't need to create anything since Visual Studio LightSwitch automatically creates the screen for us with "Save" and "Refresh" buttons.

Step 9

In the following step we insert a record of another user; for that we create a new contact table.

Step 10

In Light Switch validations are automatically applied to the table. We do not need to apply any kind of validation on their own.

Deploy your LightSwitch application with only 3.00 EUR/month with HostForLIFE.eu



European SQL Hosting - Amsterdam :: Things to Consider While Restore Your Database

clock May 2, 2013 10:21 by author Scott

Here are some important points to consider while restoring a database backup. Let us first create a sample database named test using the following code.

A new database named test will be created in your server and data and log files are created in the d: drive.

Let us assume that you regularly take backup of this database using the below code:

backup database test to disk='d:\test.bak'

Now if you want to create another database or restore this test database to a new database named testing, you can use the following code

restore database testing from disk='d:\test.bak'

However executing the code above will give you the following error

Msg 1834, Level 16, State 1, Line 2
The file 'h:\test_dat.mdf' cannot be overwritten.  It is being used by database 'test'.
Msg 3156, Level 16, State 4, Line 2
File 'test_dat' cannot be restored to 'h:\test_dat.mdf'. Use WITH MOVE to identify a valid location for the file.
Msg 1834, Level 16, State 1, Line 2
The file 'h:\test_log.ldf' cannot be overwritten.  It is being used by database 'test'.
Msg 3156, Level 16, State 4, Line 2
File 'test_log' cannot be restored to 'h:\test_log.ldf'. Use WITH MOVE to identify a valid location for the file.
Msg 3119, Level 16, State 1, Line 2
Problems were identified while planning for the RESTORE statement. Previous messages provide details.
Msg 3013, Level 16, State 1, Line 2
RESTORE DATABASE is terminating abnormally.

This error occurs because the data and log files are currently being used by the database test. So you need to give different names for those files while restoring, as shown below

restore database testing from disk='d:\test.bak'
with
move 'test_dat' to 'd:\testing.mdf',
move 'test_log' to 'd:\testing.ldf'


The above code will work fine and new database will be created with the name testing.

Just be aware of this point while restoring a backup of existing database!

 



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