I was working on getting a report in Sql Server and it was actually simple report of a list email addresses and some and other data. Apparently, while sorting the report by email address, I realised that I need to sort by the domain name of the email address to get a better understanding. So, how can you sort the result by domain name of the email address. Here is how.
February 27, 2014
To continue on from the previous post, in this post I will show how to create a relationship between two entities in the model. In the last post, I had an Employee entity created. In this one, I will create a new entity Department, update the Employee entity to have an association with Department.
Here is how the model looks like currently.
Now, the Department entity is added in the same way Employee was added previously. The model looks like below now.
Now, to add the association, right click on Employee entity and choose Add New > Association.
An Add Association prompt like below will appear with most of the options correctly set.
Notice that Multiplicity has been incorrectly set in this scenario. I will invert the relationships so 1 department can have multiple employees. So , this will look like below.
Notice that there is an option to “Add Foreign key to the Employee Entity”. I have selected it clicked OK. The model is now updated but the foreign key is named as “DepartmentDepartmentId” like below. This happened as I renamed the original primary key from “Id” to “DepartmentId”.
I have renamed it to DepartmentId by clicking on it and editing it through the properties. My model is now ready and I clicked Validate like but it failed with the messages below.
This is because the new table does not exist yet. So, I will right click and choose generate database from model which will correct this issue as shown in the previous post.
That’s it, the association is now created and the model is good to go.
I usually create a Sql Server database using Sql Server Management Studio and use asp.net or mvc application to create a database connected application. Using Entity Framework’s model first approach, I can also visually create the model and then create a database using it. in this post, I will show how to create a data model using entity framework and then create a database using it.
I will use an empty asp.net application and add an entity data model to it. To do so, add a new file and choose Data > ADO.NET Entity Data Model .
I have renamed the model to "EmployeeModel and clicked OK. In the next screen, I chose Empty Model and clicked Finish.
Clicking Finish creates the EmployeeModel.edmx and EmployeeModel.Context.tt files in the solution explorer.
The designer should be opened by default and I will write click and Add a New Entity.
In the next prompt, fill in the Entity name, and choose a unique id property which I have set as EmployeeId.
Clicking OK will generate the entity as below.
Next, I will add a few properties to this entity like FirstName, LastName, EmailAddress, DateJoined, IsActive and Salary.
To add the properties, right click on the Entity and choose Add New > Scalar Property
After adding the properties, set the properties of individual fields. Like FirstName, LastName, EmailAddress will be string, isActive will be Boolean, DateJoined will be DateTime and Salary will be double. Other properties like Nullable and default value can also be set. I have set 0 for the default value for Salary. Notice that the string fields have additional properties like Fixed Length and Max Length. I have set 50 to be the Max Length for all string properties.
For now, let’s assume that the model is ready. In future posts, (I will add more to it.). Right click on the designer and click on Validate.
Notice that Validation will fail with one warning – Entity type ‘Employee’ is not mapped.
This is because the model is not mapped to any database. To create the database, right click on the model and choose “Generate database from model”. A prompt will open to choose a connection or to create a new one. In this situation, I have created a new connection to an Employee database previously created using Sql Server Management Studio. The script is generated and when I click on Finish, the database will be generated.
The generated sql file is also saved in the project. This will create the store schema definition language (SSDL) and the mapping specification language (MSL) that is based on the model. Note that the database tables are not really added. The generated script will need to be run from with Sql Server Management Studio to create the tables to the database.
February 25, 2014
I am trying to create a new database and ended up receiving an error like “Directory lookup for the file … failed with the operating system error 2”. The following screen shot tells the full story.
With this kind of error, it normally happens when a path is specified on where the database will be created and in my situation I have specified the path but have not created the appropriate folders. Sql Server Management Studio does not automatically create the folders where the database will be created and this needs to be created manually by the administrator.
In the previous post, I showed how to create a new Sql Server database from backup, however, at times the following error might occur -
System.Data.SqlClient.SqlError: The backup set holds a backup of a database other than the existing 'NewDB' database. (Microsoft.SqlServer.SmoExtended)
The above error really states that the new database is not the same the database in the backup. To avoid this error, I will, set couple more options in the Restore database dialog.
Click on Options on the left and select “Overwrite the existing database (WITH REPLACE)”.
And, in the Files option, I will set the data file folder and log file folder to the folder location that I used to create the database. By default, it will have the paths specified for the original backed up database.
Click on OK and continue to create the database as specified in the previous post on how to create a database from backup.
Usually, we take a backup of a database at regular time intervals and to be on the safe side that if something goes wrong, we have a point in time to go back to. However, we can also create a new database from the backup and this might be useful for debugging purposes. In this post, I will show how to create a new database from a backup of different database.
To create a database from a backup follow the following steps.
Create a new database with the new name.
Click OK and this will create the database. Once created, right click on Databases and choose Restore Database. In the Source section, select Device, click on the … icon
Click on Add and select the location and select the backup file.
Click OK twice and then select the destination. Select the NewDB that was created earlier.
Click on OK and the new database should be setup correctly.
So, I have got an asp.net application and I can see the file structure of the application using Visual Studio or by navigating to the folder and viewing the directories but how can I view it on the server's end. This is not particularly useful and I don't recommend having this on the server but it might be useful for debugging specially when you don't have full control on deployment.
Since, I am getting the file structure of an asp.net application, I will use a web control for displaying the file structure. Because of the type of data I am expecting to get, a TreeView control is the perfect control to bind this data to. The TreeView control is instantiated like below.
Now, I will need to get the list of all directories and files and bind to this TreeView. To start with, I will need to get the root application folder as discussed in my previous post – how to get root application path.
Next, I have written a method that will recursively go through all the directories and add the file names and directory names with the TreeView. And finally, from Page_Load event, I have added the nodes to the TreeView. Here is the code for how it works.
Once the page is run, the following screen shot is displayed for my application.
So, I have got a Windows Server setup in Windows Azure and I want to create more of these with the same settings. For example, in the initial Windows Server, I already have configured IIS and Sql Server and firewall and now I want create more servers with the same configuration. To achieve this in Windows Azure, I will need to basically create an image of the existing server and then use that image to create more servers. So, what is an image – an image is a template of the server that is currently running and is a virtual hard disk that can be later used to create more windows servers.
To create an image of the server, I will log on to the server and then run sysprep command with administrative privilege within command prompt. To run sysprep, change current folder to %windir%\system32\sysprep and run sysprep.exe .
The System Preparation Tool options will appear. Choose “Entire System Out of Box Experience” in “System Cleanup Action” and select “Generalize”. In the “Shutdown Options” select “Shutdown”. The screen shot for this is below.
Click OK. Sysprep shuts down the virtual machine. At this stage, I cannot connect to the virtual machine using remote desktop which is the right behavior. However, the machine appears to be running from the Windows Azure portal. This is a bug in Windows Azure portal and at this stage I cannot capture the image of the virtual machine.
So, I chose the shut down option for the virtual machine and then clicked on the Capture button in the portal.
While clicking Capture a popup will appear suggesting that the currently running virtual machine will be deleted and I need to accept that before continuing. This, to me, is a poor experience as I don’t necessarily want to kill the virtual machine and this works better in AWS. In next step, I got a prompt to name the image name to continue. This will create the image for the current virtual machine.
Cool, if you have any better ways of doing it, please comment on this post.
February 23, 2014
The Sql Server has been setup and from the Services panel and Sql Server Configuration panel, I can see that it’s up and running but I cannot connect to it from asp.net solution. At this stage, I would verify if Sql Server is indeed running by logging into the server using Sql Server Management Studio from within the server. In this situation, it will connect from within the server but not when connected from outside – that is, from other servers.
The above issue can happen remote connections are not allowed in the Sql Server. To enable remote connections, open Sql Server Management Studio and connect to the Sql Server. Right click on the server name and click on “Properties”. This will open a up dialog like this.
Click on Connections from the left hand panel which will open a dialog like this.
Select the “Allow remote connections to the server” option and and click OK.
February 22, 2014
Has this ever happened to you that you have setup Sql Server (any version) and it seems to be up and running but I cannot access it from Sql Server Management Studio. To start with, how do you know it's up an running - I usually check if the Sql Server related services are up and running from Administrative Tools > Services section.
Once confirmed I connect from SSMS in the same server to the Sql Server but it does not work. At this stage, we need to check if firewall settings allow SSMS to access the sql server. Open firewall settings from Administrative Tools > Windows Firewall and Advanced Security and a new inbound rule to allow the SSMS program to access the sql server like below.
In the programs section, browse to the location where SSMS is installed. This setting will allow SSMS to access Sql Server.
February 21, 2014
A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server) (Microsoft SQL Server, Error: 2)
which I have received almost every time. As this does take up a lot of time to figure out the issue, this is how I have gone about it.
February 20, 2014
Few days back I was working with our IT team to do an audit on the Sql Servers and to get a list of how many is installed. Later, I realised that I can also do so using SQLCMD command with in the command prompt. Here is how you do it.
Open Command Prompt and type in SQLCMD -L. This will list the servers.
Alternatively and even better we can output the list to a text file by using the following command.
SQLCMD -L > c:\testdata\sqlserver.txt
This will save the text file – sqlserver.txt in C:\testdata
How often do we work with csv files? I am sure even with databases, xml and web services, csv files are still used in a great number of applications. In this post, I will show how we can bind a csv to a web control like ListView and GridView.
The main challenge to bind data from csv is to get the data in a reasonable format like a DataTable. To do so, we can use OleDB to connect and query the csv and populate a DataTable and then bind the GridView and the ListView to the data table.
February 15, 2014
How many of the web developers have heard this before that the site runs fine in localhost and development environment but is slow in production? I am sure many of us have had this issue in the past and have worked it out after few trials and errors. The following are the few components to consider to solve the issue.
Scenario 1: Many users have issues with many pages
This is a big problem as it means the site is not usable. I would start by looking into the server usage - CPU and memory. If the site is receiving lots of requests then this could cause the CPU and memory usage it spike up. Check for the server specs - how much CPU and memory it has. One the web servers I worked for had 2 GB ram when my laptop had 4 GB. The server definitely needs to be upgraded with better specs.
This would ease the problem but may not solve the issue totally. If you are receiving way more requests than the server can handle, you need to think about multiple server load balancing. Windows Azure can help you do that - http://www.windowsazure.com/en-us/documentation/articles/load-balance-virtual-machines/ .
Also, if the site is database driven, check if that is causing the issue. There might be lots of database calls in individual pages or maybe the master page has few database calls which is slowing the site down. You might be logging each of the requests, etc to the database which is calling the database too many times. Monitor your database activity when a page is requested and compare.
Another way to check if database is slowing down the site is to create html pages with same content and to note the loading time differences between the 2 page.
If you conclude that it is a database related issue, consider caching your content where possible and only grab the data that is needed instead of a random set of data. For example,
In case, it is a database related issue but the application is not really doing any strange queries, it could be the database server that is overloaded. In many cases, the same database server is used to host multiple database instances and chances are another database instance is taking all the resources in the server. In this situation, you need to figure out our hosting situation.
To improve bandwidth issue, you can cache content on the client as necessary. For example, the scripts, css and images can be cached in the client browser but there is no benefit to first time users. We can cache content by using the cache control for static content in IIS7 or the system.webServer property in web.config file.
If the HTML file served to the client is large, then HTML minification is another component look into. You should also reduce the spaces and new lines when possible from the controls. For example, if you have the following snippets in a ListView,
it will generate 3 new lines for every record returned. So, in case you generated 100 records - this will result in 300 extra lines of html. Instead of above, use,
Also, put the css files at the top within the head section and scripts at the bottom of the page before the body end tag. Putting css at top allows the page to render progressively and putting scripts to the bottom avoid blocking other content downloads.
Static sub-domain for static resources:
Few years back, while working on a site, it was recommended to have all urls in lowercase and submitting from one domain for SEO reasons. In my situation, the site was configured to serve from both example.com and www.example.com and the same link was created in many different way like example.com/abc , example.com/Abc , www.example.com/abc . Even though these are referring to the same page, it's a bad practice to have multiple urls to the same page. The site was also hosted in IIS 6 and to overcome this I used isapi rewrite tool to redirect pages to one url format. Though it solved the url formatting issue, the extra redirects slowed down the pages.
Scenario 2: One user having issues with speed of the site
If you have more than one user, you can be more or less certain that the issue is at the client end. To start with, check where the user is located. For example, you might be hosting the site in US whereas the user is visiting it from Australia. The site will certainly be slower due to network latency. You can use the site - http://www.webpagetest.org/ - to get some idea on how the site performs in various geographical locations.
February 7, 2014
There are few ways we can get the size of a Sql Server database. There are built in stored procedures and we can also write our own and even use the sql server management studio to get the size. In this scenario, I am using the AdventureWorks database.
The stored procedure "sp_spaceused" returns the database size, index size, data size and unused space of the database. We can use it in the following way.
The stored procedure "sp_helpdb" returns the size of the database, name, dbid, filename, data size, log size and few other metadata. It can be used like below.
We can write a custom script to query from sysfiles to get the size of the database. The script and the result it produces is below.
Lastly, and most easily, we can get the size from the properties of the database. Right click on the database name in object explorer, click on properties and then choose Files from "Select a page".