Friday 30 March 2012

Top SQL Server Tools SQL safe backup SQL diagnostic manager SQL Sentry Performance Advisor for SQL Server SQL compliance manager Creating LINQ to SQL Object Models using SqlMetal


ProblemIn a previous tip on Querying SQL Server databases using LINQ to SQL, you have seen how we can model our SQL Server databases using LINQ with Visual Studio 2008. I have a database with a lot of tables and stored procedures, so dragging-and-dropping them on the Visual Studio design surface would take some time. Is there a faster way to create LINQ to SQL object models?
SolutionWhile Visual Studio provides a way for developers to be more productive, dealing with a lot of SQL Server database objects with LINQ is totally inefficient. The dragging-and-dropping process to create the object model will take a lot of time, depending on the amount of objects.
As I was going thru the April 2008 edition of the SQL Server Magazine, I've learned about this utility called SqlMetal.SqlMetal.exe is a command-line tool that generates code and mapping for the LINQ to SQL component of the .NET Framework. When I started working with LINQ, I was only using Visual Studio 2008 to generate the object-relational diagram by (you guessed it) dragging-and dropping the database objects on my designer surface. You can find this tool inside the \Program Files\Microsoft SDKs\Windows\v6.0a\bin folder. It generates the necessary data entity andDataContext object for LINQ as either a .vb or .cs source file. You can run this tool by navigating to the folder location using command prompt and execute from there.
A sample code to use SqlMetal.exe is shown below
sqlmetal /server:localhost /database:Northwind /language:cs /code:Northwind.cs
The command above generates a .cs file (used for C# as the default language for the generated code is in VB.NET) from the Northwind database running on my SQL Server 2000 instance that represents the database object model. This can then be imported as code in your Visual Studio project. Just remember the file name and where the file is stored when importing it in your Visual Studio project or you can specify the path where you want to store the files as they are generated by the tool. In this case, it's in the same location as SqlMetal. In case you want both code and the object diagram, simply replace the /code switch with the /dbml switch. The /dbml switch will generate the dbml file which will then generate the corresponding source code when imported in your Visual Studio project. You cannot specify both/dbml and /code switches at the same time.
sqlmetal /server:localhost /database:Northwind /language:cs /dbml:Northwind.dbml
When you open either the dbml file or the code in Visual Studio 2008, you will see things which may seem familiar if you have used the designer to create LINQ objects. The dbml file and the code includes all the database entities and their corresponding attributes - the tables and their fields with constraints and data types - as well as their relationships.
If you need to include stored procedures and functions in your code, you can simply add the /sprocs and /functionsswitches. The available switches for SqlMetal are available on the MSDN website.
LINQ to SQL Server Compact is unsupported?
You probably have heard about SQL Server Compact and how you can use it as an embedded database engine for Windows Desktop and mobile device applications. Unfortunately, Visual Studio does not support the data provider for SQL Server Compact. When you create a SQL Server Compact database in you Visual Studio project and add a LINQ to SQL class that references the database, you will get an error similar to the one below.
While you can't use the designer surface to generate the object model for SQL Server Compact databases, SqlMetal gives you that option. You can generate the dbml file for your SQL Server Compact database for import in you project as described in this MSDN article.
A sample code is shown below
SqlMetal /dbml:northwind.dbml northwind.sdf
Remember to specify the complete path of your SQL Server Compact database file when using SqlMetal as this is not the same when connecting to a full-blown SQL Server instance.

Next Steps
Generating code or dbml file using SqlMetal takes only a few seconds on my local SQL Server instance, as compared to dragging-and-dropping all of the objects on the designer surface in Visual Studio. This is a great time saver especially if you have to deal with a lot of objects in your SQL Server database. What's more, you can use it with a combination of T-SQL scripting with VBScript/PowerShell if you need to generate code for several databases across SQL Server instances.

Reading XML documents using LINQ to XML


ProblemIn a recent tip on Language Integrated Query (LINQ), you have described how it can be used as a query language extension to both VB.NET and C#. As XML has become a popular means to store data for ease of interoperability, how do we use LINQ to query XML data?
SolutionLanguage-Integrated Query for XML (LINQ to XML) allows XML data to be queried by using the standard query operators as well as tree-specific operators that provide XPath-like navigation through descendants, ancestors, and siblings. It simplifies working with XML data without having to resort to using additional language syntax like XPath or XQuery. You can use LINQ to XML to perform LINQ queries over XML that you retrieve from the file system, from a remote web service, or from an in-memory XML content. This tip will only focus on querying XML using LINQ from an XML file - theCustomers.xml file. You can download the XML file so you can follow along with the tip.
Create a simple LINQ project 
We will start by following the steps outlined in the Introduction to LINQ tip. We will name our Visual Studio projectConsoleLINQtoXML and use the C# language. Add the following namespaces with the using directive. TheSystem.Xml.Linq namespace contains the classes for LINQ to XML
//Include the LINQ to XML namespaces 
using System.Xml//namespace to deal with XML documents 
using System.Xml.Linq//namespace to deal with LINQ to XML classes 
Next, we will add the Customers.xml file in our project. You can also opt to store the XML file in a directory in your file system but for simplicity's sake, we'll just include it in our project. Click on the Project menu and select Add Existing Item... from Visual Studio.
Select the Customers.xml file and click Add. The XML file should be added in your project.
Right-click on the Customers.xml file from the Solutions Explorer and select Properties. This should bring up the Properties window..
On the Properties window for the Customers.xml file, click the Copy to Output Directory option and select Copy always from the drop-down list
Now we are ready to write LINQ queries to read our XML file. Let's start writing some code inside the static voidMain(string[] args).
// Create the query 
var custs = from c in XElement.Load("Customers.xml").Elements("Customers"
          select c ;
// Execute the query 
foreach (var customer in custs)
     Console.WriteLine(customer);
}
//Pause the application 
Console.ReadLine();
You will notice that there isn't much difference in the query from the Introduction to LINQ tip except for the fact that it now uses the XElement class which represents an XML element. The Load method of the XElement class simply loads the Customers.xml file into the XElement class. The Elements method returns a filtered collection of the child elements of this element - the Customers element -in the XML document. This just demonstrates how powerful LINQ is as you are using the same language query constructs on collections and now on XML documents. You can even implement sorting, filtering and grouping as you normally would in LINQ. You can insert a where clause in the query above to filter your results.
where c.Element("Country").Value == "Italy"
Your output will look like this when you run your project in Visual Studio. You can press F5 or click on Debug - Start Debugging in Visual Studio
Doing the same thing without LINQ is more complex as you still need to traverse the nodes explicitly to access the elements and their values. You can check out the Microsoft KB article that demonstrates how to do this in C# and compare the differences.
Next Steps
You have seen how easy it is to read XML documents with LINQ. You can use LINQ to read XML documents from the file system, from a remote web service, or from an in-memory XML content. We will look at using LINQ to XML to manipulate XML data in future tips.

Querying SQL Server databases using LINQ to SQL


ProblemIn a recent tip on Language INtegrated Query (LINQ), you have described how it can be used as a query language extension to both VB.NET and C#. How can we use LINQ to SQL in .NET applications to query SQL Server databases?
Solution
LINQ to SQL is a component of .NET Framework version 3.5 that provides a run-time infrastructure for managing relational data as objectsAs most developers are used to the object-oriented paradigm, accessing data from a relational database requires understanding of relational paradigm. LINQ to SQL makes querying a SQL Server database as if it was an object and eliminate the need to write very complex SQL statements whenever necessary. It is also an OR/M (object-relational mapping) implementation that allows you to model a relational database using .NET classes. You can then run queries in the database as well as perform insert, update and delete actions to it.
Model your SQL Server databases using LINQ 
Visual Studio 2008 and the corresponding Express Editions come with a visual designer which makes it easy to model and visualize a database as a LINQ to SQL object model. Let's create a console project by following the steps outlined in theIntroduction to LINQ tip. We will name our Visual Studio project ConsoleLINQ2SQL and use the C# language. Next, let's add a new item in our project. Click on the Project menu and select Add New Item... from Visual Studio.
On the Add New Item window, select LINQ to SQL Classes under the Templates section and name itNorthwind.dbml as we will be using the Northwind database for the sample queries
This will do a couple of things. First, it will add the System.Data.Linq namespace in the project. This assembly contains the framework implementation for LINQ to SQL and makes it easy to refer to SQL Server database objects as how developers do in object-oriented programming. Next, it gives you a object-relational designer where you can drag-and-drop database objects and it will create the corresponding. The designer will open up, displaying two separate panes, after adding the LINQ to SQL class in your project.
To start adding database objects in the designer surface, click on the Server Explorer link. Create a new connection to a SQL Server database by clicking on the Connect to Database icon in the Server Explorer window. The Add Connection window appears which will ask you to specify the SQL Server instance name, database name and your login credentials. I've selected the Northwind database for the samples
Once the database connection has been created, you can start dragging and dropping database objects in the designer surface. Expand the Server Explorer window and select the Instancename.Northwind.dbo data connection. Expand the Tables folder to see all of the tables inside the Northwind database. Start by selecting the CustomersOrder DetailsOrdersProductsShippers and Suppliers tables and dragging them on the designer surface.
The designer will create the corresponding classes necessary to translate your database into objects. Each table dragged into the designer surface will have a corresponding entity class. Each instance of the entity class represents a row within the table. The arrows represent the relationships between the entity classes as defined by the primary key/foreign key constraints in the database. The direction of the arrows indicate whether the associations are one-to-one or one-to-many.
Introducing the DataContext class
The designer will create a corresponding DataContext class together with all of the entity classes that correspond to the tables in the database. This is done immediately after clicking the Save button within the designer surface. TheDataContext class represents the main entry point for the LINQ to SQL framework and is the most important class. I refer to it as a proxy class responsible for representing how the database should look like from an object-oriented perspective. We will be using this proxy class to query entities from the database as well as perform changes. The properties and methods of this proxy class correspond to the tables and stored procedures we have added, respectively. We will look at using stored procedures with LINQ to SQL in a future tip.
Querying tables using LINQ
Let's start writing some code inside the static void Main(string[] args).
//Obtaining the data source 
var dbNorthwind =new NorthwindDataContext() ;
// Create the query 
var query = from c in dbNorthwind.Customers     
                   select
 c;
// Execute the query 
foreach (var c in query)
     Console.WriteLine(c.CompanyName);
}
//Pause the application 
Console.ReadLine()
As you would have figured out, there isn't much difference in the query from the Introduction to LINQ tip except for the part where the output needs to be written to the console window. Since c is an instance of thedbNorthwind.Customers class. Since we are returning an instance of the class, it would make sense to simply display the properties rather than the entire object which, in this case, the CompanyName property of thedbNorthwind.Customers class. As previously mentioned, the properties of the class represent the columns in the associated table. LINQ to SQL also makes sure that the properties are strongly-typed to avoid data type conflicts between the class and the columns in the associated table. You can also apply filtering and sorting in the queries as you would do using T-SQL.
where c.Country == "USA"
orderby c.CompanyName descending
Your output will look like this when you run your project in Visual Studio. You can press F5 or click on Debug - Start Debugging in Visual Studio
We can see what is happening under the covers by logging the activity to the console. Insert the following code after the var dbNorthwind =new NorthwindDataContext(); line and run the application.
//Obtaining the data source 
var dbNorthwind =new NorthwindDataContext() ;
dbNorthwind.Log = Console.Out;
The first few lines of the output display the T-SQL query that LINQ generated and the provider used for the backend SQL Server database. Mine displays SqlProvider( Sql2000) as I am using a SQL Server 2000 instance. You can also useSQL Profiler to capture the generated T-SQL queries. Notice the use of parameters in the query because of the existence of a where clause. LINQ to SQL generates parameterized queries in order to prevent SQL injection attacks thru the application.
Query Across Relationships
Since the O/R model has generated the corresponding relationships for your classes, you can write queries that refer to those relationship properties. Let's say you wanted to retrieve all the OrderIDs and ContactName of all Customersbased in Italy. You can write your query as shown below
//Obtaining the data source 
var dbNorthwind =new NorthwindDataContext() ;
// Create the query 
var query = from O in dbNorthwind.Orders     
                   where 
O.Customer.Country=="Italy"
//Create a new class instance to represent the result 
                   select new
{CustomerName=O.Customer.ContactName,OrderID=O.OrderID};
// Execute the query 
foreach (var c in query)
     Console.WriteLine(c.CustomerName + "," + c.OrderID);
}
//Pause the application 
Console.ReadLine()
You will notice that the IntelliSense feature in Visual Studio will pick up the corresponding relationships between the class instances using the dot (.) notation.
Next StepsYou have seen how you can use LINQ to SQL to query SQL Server databases. LINQ to SQL is only for SQL Server and not for any other relational databases out there so we still need to wait for LINQ to SQL implementations for Oracle or IBM DB2. In future tips, we will look at data manipulation and using stored procedures in LINQ to SQL.
  • Give this example a try and change the query parameters so you can have a feel of how LINQ to SQL works.
  • Learn more about LINQ to SQL

Top SQL Server Tools SQL diagnostic manager SQL Sentry Performance Advisor for SQL Server SQL compliance manager SQL safe backup Introduction to Language Integrated Query (LINQ)


ProblemLanguage-Integrated Query (LINQ) is a groundbreaking innovation in Visual Studio 2008 and the .NET Framework version 3.5 that bridges the gap between the world of objects and the world of data. As LINQ is part of the development enhancements in SQL Server 2008, how can I have an understanding of how it works and how I can use it in other areas of administration, not just SQL Server?
SolutionLet's start off by explaining LINQ.  LINQ is a codename for a project which is a set of extensions to the .NET Framework that encompasses language-integrated query, set and transform operations. It extends C# and VB with native language syntax for queries and provides class libraries to take advantage of these capabilities, available only in .NET Framework 3.5. For developers who write code that regularly access a recordset, this means a lot. The fact that queries are usually expressed in a specialized query language for different data sources makes it difficult for developers to learn a query language for each data source or data format that they must access. This is what LINQ is all about. It simplifies data access by providing a consistent model for working with data across various kinds of sources and formats. In LINQ, data is translated into objects, something that developers are more comfortable with working . Understanding LINQ will give us an idea of its capabilities and its benefits
Create a simple LINQ project
Let's start by creating a simple console project using the C# language in Visual Studio 2008. You can also download the free Visual C# 2008 Express Edition from the MSDN Download Center. Make sure you select .NET Framework 3.5 from the target framework drop-down menu.
This will open up your Program.cs file. Notice that by simply creating a project that targets the .NET Framework 3.5 automatically adds a using directive for the System.Linq namespace as this is already a part of the System.Coreassembly. The System.Linq namespace provides classes and interfaces that support queries that use LINQ. We will start with this to understand the basics of LINQ.
Let's start writing some code inside the static void Main(string[] args):
//Obtaining the data source 
string[] carNames = {"Ferrari""Porsche""Mercedes" , "McLaren""Audi""BMW"};
// Create the query 
// query is an IEnumerable 
var query = from name in carNames
         
where name.Contains("e"    
            select
 name;
// Execute the query 
foreach (string name in query)
     Console.WriteLine(name);
}
//Pause the application 
Console.ReadLine();
We'll examine the basic components of a LINQ query. Any LINQ query consists of three distinct actions.  These are obtaining the data source, creating the query and executing the query. The first thing that we need to do is to have a data source. In this case, it's an array of strings which supports the generic IEnumerable(T) interface. This makes it available for LINQ to query. A queryable type does not require special modification to serve as a LINQ data source as long as it is already loaded in memory.  If not, you would have to load it into memory so LINQ can query the objects. This is applicable to data sources like XML files. Next, is the query. A query specifies information to retrieve from the data source. This is similar to a SQL query which includes syntaxes like SELECT, FROM, WHERE, GROUP BY, etc. Looking at the code above, you'll notice that its not like your typical SQL statement as the FROM clause appeared before the SELECT clause. There are a couple of reasons for this. One, it adheres to the programming concept of declaring the variable before using it. Also, from the point of view of Visual Studio, this makes it easy to provide the IntelliSensefeature using the dot (.) notation as the variable has already been declared and that the framework has already inferred the correct type to the object.  This provides the appropriate properties and methods, making it easy for the developers to write their code.
Let's look at how the code was constructed. The from clause specifies the data source, in this case, the carNamescollection. The where clause applies the filter, in this case, the list of all elements in the collection containing the letter 'e'. The select clause specifies the type of the returned elements. This means that you can create an instance of the elements in your collection. An example could be creating an instance of an object with fewer attributes. The query variable, query, just stores the information required to produce the results when the query is executed, maybe at a later point. Simply defining the query variable does not return any data nor takes any action. The third component of the code above is query execution. As I mentioned, the query variable does not contain any data, but rather simply contains only the query commands. The actual execution of the query is when we iterate over the query variable. There are a couple of ways to do this. One of which is shown above. The use of a foreach statement iterates thru the query variable and execute it as well. This concept is called deferred query execution. This is very much important when dealing with data sources such as highly-transactional database systems as you minimize connecting to the database unless necessary (database connections are additional resources on the database server as well). You can opt to execute the query immediately by using aggregate functions such as CountMaxAverage and First or calling the ToList() or ToArray()methods. Another way is to bind the collection to a data-bound control in either a web or windows form control similar to how you would do it in previous versions of Visual Studio - specifying the DataSource property of the control to be the query variable and calling the DataBind() method.
Another area to highlight in the code is the use of the keyword var, which is a new keyword introduced in C# 3.0. What this does is it looks at the value assigned to the variable, then determines and sets the appropriate one. This concept is called type inference. From the code above, the query variable, query, appears to be an array of string. So the compiler will automatically assume that it is a variable of type IEnumerable. This is helpful if you do not know the variable type during runtime. But this does not mean that any type can be assigned to the variable after the initial assignment - something like a dynamic type - since .NET is a strongly typed language platform. This simply means that an object can take on a different type and the compiler can simply handle that. Assigning a different type to an already existing one violates the concept of polymorphism in object-oriented programming. Let's say you assign the value 12 to the query variable, query. This will throw a type conversion exception as the original type of the variable is a string collection.
Your output will look like this when you run your project in Visual Studio. You can press F5 or click on Debug - Start Debugging in Visual Studio
Next Steps

Using Stored Procedures with LINQ to SQL


ProblemIn a recent tip on Querying SQL Server databases using LINQ to SQL, you have described how it can be used to query SQL Server databases. How do I use LINQ to SQL with stored procedures that retrieve database records?
SolutionWe use stored procedures to encapsulate business logic on the database server side. This gives us the advantage of modularity, performance, and security to name a few. We can use these stored procedures with LINQ to SQL. LINQ to SQL maps these database-defined abstractions to code-generated client objects, so that you can access them in a strongly typed manner from client code. This gives us the advantage of using Visual Studio's IntelliSense feature to expose them as methods together with the strongly-typed parameters which might be needed to call the stored procedures.
We'll start with the example project used in the LINQ to SQL tip to write LINQ query expressions that call stored procedures. Open the Northwind.dbml file by double-clicking it from the Solutions Explorer window.

This will open up the designer surface for you to drag-and-drop the stored procedures from the Server Explorerwindow. I'll use the SalesByCategory stored procedure from the Northwind database to retrieve a list of sales record based on the CategoryName and Year passed as parameters. If the stored procedure generates a list of classes based on what is already on the designer surface, you can drag-and-drop the stored procedure from the Server Explorerwindow to the class that will be generated. Let's say the stored procedure retrieves records from the Products table, you can drop the stored procedure on the Products class in the designer surface. This tells the designer that the resultset of the stored procedure is a list of Products classes. Otherwise, you can just drop it anywhere on the designer surface which will then be added to the DataContext class as a method.
Notice that the data types defined by the parameters accepted by the stored procedure are also strongly-typed. By default, the name of the method will be the same as the name of the stored procedure. If the stored procedure name contain spaces, the designer automatically converts them to the underscore ( _ ) character.
Calling the stored procedure using LINQ
Let's start writing some code inside the static void Main(string[] args).
//Obtaining the data source 
var dbNorthwind =new NorthwindDataContext() ;
// Create the query 
var query = dbNorthwind.SalesByCategory("Beverages","1997");     
                   
 // Execute the query 
foreach (var c in query)
     Console.WriteLine(c.ProductName + "," + c.TotalPurchase);
}
//Pause the application 
Console.ReadLine()
Visual Studio's IntelliSense feature now exposes the DataContext class' new method together with the parameters with their corresponding data types.
Even the results returned by the method are strongly typed
Running the application with logging will look like this when you run your project in Visual Studio. You can press F5 or click on Debug - Start Debugging in Visual Studio.
There is a limitation on calling stored procedures using LINQ to SQL. The designer does not generate code for stored procedures that use dynamic SQL statements to return a result set or those that depend on temporary tables to return a result. This is because LINQ to SQL cannot acquire the metadata for the resultset during design time. But it doesn't mean it is not possible. It just means that you will not be able to use the IntelliSense feature to retrieve the strongly-typed resultsets based on the metadata returned by the stored procedure.
Next Steps
You have seen how LINQ to SQL supports the ability to call SQL Server stored procedures and call them as methods of the DataContext class
  • Start using stored procedures with LINQ to SQL.
  • Learn more about LINQ to SQL

Wednesday 28 March 2012

Chamundi Hills


Chamundeshwari Temple at Chamundi HillsChamundi Hills can be viewed from a distance of about 8 to 10 kms and from all the corners of Mysore City. Chamundeshwari temple is situated on the top of Chamundi hill which is about 3,489 ft. above sea level and located at a distance of 13 kms. from Mysore. The temple is dedicated to Sri Chamundeshwari, the titular deity of the Mysore Royal Family also described as ‘Mahishasura Mardini’for having killed the buffalo headed demon Mahishasura. The temple has a very beautiful idol of the goddess wearing a garland of skulls. Goddess Chamundeshwari, also spelled Chamundeswari is an incarnation of Goddess Durga, Goddess Kali is also referred to as the Goddess Chamundi.

Mysore was ruled by the demon-king Mahishasura, he was a buffalo-headed monster. Hence, came the name of this place - Mahishuru, the city of demon Mahisha. Hearing to the prayers of Gods and Goddess to save them from the monster, Goddess Parvathi, (consort of Lord Siva), took birth as Chamundeshwari and killed the monster. After killing the demon, the Goddess resided atop the Chamundi Hills where she is worshiped with reverence and devotion. The goddess is also known as Mahishasura Mardini meaning She who slew Mahishasura.
Nandi Bull at Chamundi HillsThe Chamundi temple has always been patronised by the rulers of Mysore. In 1659 Dodda Devaraja Wodeyar built 1,000 steps and huge Nandi, Lord Shiva's Bull. This colossal Nandi is one of the largest in India, 16 ft. (4.8 meters) tall at the front and 25 ft. (7.5 meters) in length. The magnificent pendent bells around its neck are exquisite. Nandi and the temple beside it are located at the 700th step of the Chamundi Hill. Krishnaraja Wodeyar III repaired the shrine in 1827 and built the present beautiful forty-meter, seven storied Gopura (tower at the entrance) with gold finials, and set up statues of his and his three queens. In 1827, Krishnaraja Wodeyar III made arrangements for festivals and processions and gifted Simhavahana in 1843.
There are two other temples dedicated to Lakshmi Narayana Swamy and Mahabaleswara. Sri Mahabaleswara temple - dedicated to Lord Shiva in the form of Linga, is the oldest temple on the hill. It was built before the beginning of the Hoysala rule. Epigraphical evidences indicate this area as Mabhala or Mabbala theertha and states that Hoysala King Vishnuvardhana has given donations to this temple in 1128 A.D.

The Mahishasura Statue - built in 1659 by Dodda Devaraja Wodeyar and Rajendra Vilas palace - used to be a popular hotel earlier are few other attractions on the hill.

A panoramic view of the city is seen from the top of the Chamundi hills. Among other landmarks, you can see the race course, the Lalitha Mahal palace, Mysore Palace, Karanji and Kukkarahalli lakes. At dusk, the view of the city is especially beautiful, and on Sunday evenings and during the Mysore dasara festival, the illuminated Mysore Palace glitters like gold !
Chamundeshwari Temple Pooja Timings
07.30 am - 02.00 pm
03.30 pm - 06.00 pm
07.30 pm - 09.00 pm
Chamundi Temple Entry Charges Free
Distance From Mysore
13 kms by road
1000 odd steps from the foot of Chamundi Hills
How to Reach From Mysore
Chamundi temple is well connected by road.
Mysore City Buses ply regularly from Mysore City
Attractions NearbyLalitha Mahal Palace | Karanji Lake Mysore Zoo

Map data ©2012 Google - Terms of Use

Map
Satellite
Hybrid
Terrain