Jack @ ASP.NET

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries Tagged ‘SQL’

Call SQL Server Management Objects (SMO) in C#

Overview of SMO

SQL Server Management Objects (SMO) are objects designed for programmatic management of Microsoft SQL Server. You can use SMO to build customized SQL Server management applications. Although SQL Server Management Studio is a powerful and extensive application for managing SQL Server, there might be times when you would be better served by an SMO application.

SMO in SQL Server 2008 is compatible with SQL Server 2000, SQL Server 2005, SQL Server 2008 and SQL Server 2008 R2. SMO in SQL Server 2005 is compatible with SQL Server 2000, SQL Server 2005. So, you can easily manage a multi-version environment with a higher version of SMO.

Install SMO

Microsoft SQL Server 2008 Management Objects Collection (a component of Feature Pack for Microsoft SQL Server 2005/2008)

The Management Objects Collection package includes several key elements of the SQL Server 2008 management API, including Analysis Management Objects (AMO), Replication Management Objects (RMO), and SQL Server Management Objects (SMO). Developers and DBAs can use these components to programmatically manage SQL Server 2008.

By default, the SMO assemblies are installed in the C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies, you can track this folder to see whether SMO installed successfully.

 

Call SMO in C#

These are the minimum files that are required to build an SMO application, and they are under the C:\Program Files\Microsoft SQL Server\100\SDK\Assemblies\ folder

Microsoft.SqlServer.ConnectionInfo.dll

Microsoft.SqlServer.Smo.dll

Microsoft.SqlServer.Management.Sdk.Sfc.dll

Microsoft.SqlServer.SqlEnum.dll

Here is a demo of script all jobs in sql server

   1:  Server server = new Server(ServerName);
   2:  JobServer server2 = server.JobServer;
   3:  foreach (Job job in server2.Jobs)
   4:  {
   5:      WriteToFile(job, PathToWriteScripts);
   6:  }

Call SQLCMD and get the exit code(return code/%ErrorLevel%)

In my last post Call SQLCMD to run SQL script via C#, we know how to call SQLCMD via C#. But in most scenarios, we also need the exit code(%ErrorLevel%) or the sub SQLCMD thread. It is simple, use ‘-b’ in sqlcmd can do this!

-b on error batch abort

Specifies that sqlcmd exits and returns a DOS ERRORLEVEL value when an error occurs. The value that is returned to the DOS ERRORLEVEL variable is 1 when the SQL Server error message has a severity level greater than 10; otherwise, the value returned is 0. If the -V option has been set in addition to -b, sqlcmd will not report an error if the severity level is lower than the values set using -V. Command prompt batch files can test the value of ERRORLEVEL and handle the error appropriately. sqlcmd does not report errors for severity level 10 (informational messages).

If the sqlcmd script contains an incorrect comment, syntax error, or is missing a scripting variable, ERRORLEVEL returned is 1.

So, just add a –b parameter when call the SQLCMD!

Here are more parameters in error reporting,

-V severitylevel

Controls the severity level that is used to set the ERRORLEVEL variable. Error messages that have severity levels less than or equal to this value set ERRORLEVEL. Values that are less than 0 are reported as 0. Batch and CMD files can be used to test the value of the ERRORLEVEL variable.

-m error_level

Controls which error messages are sent to stdout. Messages that have a severity level less than or equal to this level are sent. When this value is set to -1, all messages including informational messages, are sent. Spaces are not allowed between the -m and -1. For example, -m-1 is valid, and -m -1 is not.

This option also sets the sqlcmd scripting variable SQLCMDERRORLEVEL. This variable has a default of 0.

Call SQLCMD to run SQL script via C#

Usually, we need to call some sql script to update our database in our application(C#), and it is a good way to call SQLCMD to execute the sql scripts. One important reason is that our scripts always contains the GO statement which is is not a Transact-SQL statement; it is a command recognized by the sqlcmd and osql utilities and SQL Server Management Studio Code editor. Since the SQLCMD and SQL Server Management Studio will do the same thing, the scripts edited by SQL Server Management Studio will be 100% supported by SQLCMD.

Here is a block of code to call SQLCMD:

 

string tmpFile = Path.GetTempFileName();

string argument = string.Format(@" -S {0} -d {1} -i ""{2}"" -o ""{3}""",
    ServerName, DatabaseName, fileName, tmpFile);

// append user/password if not use integrated security
if (!connection.IsIntegratedSecurity)
    argument += string.Format(" -U {0} -P {1}", User, Password);

var process = Process.Start("sqlcmd.exe", argument);
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();
while (true)
{
    // wait for the process exits. The WaitForExit() method doesn't work
    if (process.HasExited)
        break;
    Thread.Sleep(500);
}

Incorrect Syntax near ‘GO’ while using SqlCommand.ExecuteNonQuery()

GO is not a Transact-SQL statement; it is often used in T-SQL code. Go causes all statements from the beginning of the script or the last GO statement (whichever is closer) to be compiled into one execution plan and sent to the server independent of any other batches. SQL Server utilities interpret GO as a signal that they should send the current batch of Transact-SQL statements to an instance of SQL Server. The current batch of statements is composed of all statements entered since the last GO, or since the start of the ad hoc session or script if this is the first GO.

GO Statement must be written in new line as it is not T-SQL command. T-SQL statement can not occupy the same line as GO. GO statement can contain comments.

select * from tableA
go
insert into tablea(MyValue) values(‘aaa’)
go
select * from tableA
go

The above sql script for example, will give you a ‘Incorrect Syntax near GO’ exception. the solution to this is remove the ‘GO’ statement.

Entity Framework 4

Some of the big improvements in EF4 include:

  • POCO Support: You can now define entities without requiring base classes or data persistence attributes.
  • Lazy Loading Support: You can now load sub-objects of a model on demand instead of loading them up front.
  • N-Tier Support and Self-Tracking Entities: Handle scenarios where entities flow across tiers or stateless web calls.
  • Better SQL Generation and SPROC support: EF4 executes better SQL, and includes better integration with SPROCs
  • Automatic Pluralization Support: EF4 includes automatic pluralization support of tables (e.g. Categories->Category).
  • Improved Testability: EF4’s object context can now be more easily faked using interfaces.
  • Improved LINQ Operator Support: EF4 now offers full support for LINQ operators.

EF4 enables you to:

  • Develop without ever having to open a designer or define an XML mapping file
  • Define your model objects by simply writing “plain old classes” with no base classes required
  • Use a “convention over configuration” approach that enables database persistence without explicitly configuring anything
  • Optionally override the convention-based persistence and use a fluent code API to fully customize the persistence mapping

WebMatrix – Microsoft’s new web tool

What Is It?

WebMatrix is everything you need to build Web sites using Windows. It includes IIS Developer Express (a development Web server), ASP.NET (a Web framework), and SQL Server Compact (an embedded database). It streamlines Web site development and makes it easy to start Web sites from popular open-source apps. The skills and code you develop with WebMatrix transition seamlessly to Visual Studio and SQL Server.

Why Use It?

You will use the same powerful Web server, database engine and web framework that will run your Web site on the Internet, which makes the transition from development to product seamless. Beyond ensuring everything just works, WebMatrix includes new features that make Web development easier.

Who’s it for?

WebMatrix is for developers, students, or just about anyone who just wants a small and simple way to build Web sites. Start coding, testing, and deploying your own Web sites without having to worry about configuring your own Web server, managing databases, or learning a lot of concepts. WebMatrix makes Web site development easy.

Code Without Boundaries

WebMatrix provides an easy way to get started with Web development. With an integrated code editor and a database editor, Web site and server management, search optimization, FTP publishing, and more, WebMatrix provides a fresh, new Web site development experience that seamlessly bridges all the key components you need in order to create, run, and deploy a Web site.

Top Features:

Small, but complete package

WebMatrix is a free Web development tool that installs in minutes and elegantly brings together a Web server, a database, and programming frameworks into a single, integrated experience. WebMatrix lets you code, test, and deploy both ASP.NET and PHP applications side by side.

Grows with you

With WebMatrix on your desktop, you’re using the same powerful Web server, database engine, and frameworks that your Web site on the internet uses. This ensures that your transition from development to production is smooth and seamless.

When you’re ready, WebMatrix integrates Visual Studio into your workflow. Connect to Visual Studio to take advantage of powerful features such as debugging and profiling. And when you’re ready for a high-volume relational database server, move your database and data from SQL Server Compact to SQL Server with just a click of the mouse.

Start > Open Source

WebMatrix connects you to a world of popular and free open-source Web applications, including DotNetNuke, Umbraco, WordPress, Joomla!, and more. Simply select an application from the built-in gallery, and WebMatrix handles the downloading and installation of your new Web site. The days of hand-editing configuration files and making sure you have all the right components are long gone. Customize your site using the built in code editor and make it yours.

Database made simple

Using a database has never been easier! WebMatrix includes a small, embedded database called SQL Server Compact that can live with your Web site code and content. Use it to start building your next Web site, and when you’re ready to publish, just copy the database file from your computer to any Web server and it will run— no extra installation required. Or you can easily migrate the database and data to SQL Server when you’re ready for high-volume traffic.

Elegant interface, simple experience

WebMatrix integrates a rich code editor, a database editor, Web server management, Search Engine Optimization, FTP publishing, and more, WebMatrix provides a fresh, new, Web site development experience that bridges all the key components you need to create, run, and deploy a Web site.

Simple to code

WebMatrix is the easiest way to learn standards-based Web development and makes it simple to build and publish Web sites on the internet. Start with HTML, CSS and JavaScript and then seamlessly connect to a database or add in dynamic server code using the new ‘Razor’ syntax for ASP.NET Web pages. Your code is easy to read, simple to learn, short to write and works with any text editor. Use built-in helper functions to connect to a database, display a Twitter feed, or embed a video. And with a seamless path to ASP.NET MVC it is now easier than ever to create powerful ASP.NET Web applications.

More than “Hello, World”

Want to display a Twitter feed? Need to show a video? Code helpers make common tasks easy to do with just a simple tag in your HTML.

Desktop or server, it’s all the same

WebMatrix uses the same powerful Web server, database engine, and frameworks environment that will run your Web site on the Internet, which makes the transition from development to product seamless.

Tightly knit, fully integrated

WebMatrix integrates with IIS Developer Express and is tightly linked with the Web server components that run your site. Directly monitor real-time Web requests and responses to track down problems right at the source. Missing an image? You’ll instantly see why and where, and WebMatrix will take you directly to the file to fix the problem.

Optimize for search

Run an SEO report and find how to make your site more visible to search engines. WebMatrix takes the secrets out of search engine optimization, provides clear guidance on how to make your site better, and even offers to take you right to the file in your site you need to fix.

Site publishing

With WebMatrix you can find the perfect home for your Web site. Use WebMatrix to find a Web host that fits your requirements and use the built-in publishing support for FTP, FTPS, and WebDeploy to ensure that your files, databases, and settings arrive intact on the web.