I want to write c# code to make a snapshot-backup if available. This is supported since SQL Server version 2005 but only in Enterprise edition but not in Express or Standard edition.
My question: how to find out in C# if the connected server supports snapshot backup (is Enterprise Edition 2005 or newer or some kind of "hasFeature(...))?
My current solution puts a try catch around the following code.
sqlCommand.CommandText = String.Format("CREATE DATABASE {0} ON " +
(NAME = {1}, FILENAME = \"{2}\" ) AS SNAPSHOT OF {1}",
databaseBackupName,
databaseName,
filenameOfDatabseBackup);
sqlCommand.ExecuteNonQuery();
If I catch a SqlException I assume there is no support on the connected server.
But maybe there could be other reasons to fail although the database supports snapshots (i.e. something is locked, connection is broken, ...)
The ideal solution would be some sqlCommand.ExecuteNonQuery() to find out if the feature is supported.
The second best is if I had to include some extra dll that can find it (?sqldmo?) but this would create an additional dependency to the project.
The third best would be some kind of exception handling.
You could certainly do something like this:
SELECT
SERVERPROPERTY('productversion') as 'Product Version',
SERVERPROPERTY('engineedition') as 'Engine Edition'
The Product Version will give you a string like this: 10.50.1600.1. SQL Server 2005 is version 9, so anything that starts with 9., 09. or 10., 11. will be fine.
The Engine Edition gives you an INT (1 = personal/MSDE/Express, 2 = standard, 3 = enterprise/developer).
Related
For my research I need to be able to query a Microsoft analysis server(2012) Data cube with the Unity game engine. For the connection there is a Microsoft Authentication needed and Unity is using the Mono Develop libraries for SQL connections which gives me a problem. Since so far i haven't found a solution for Mono to be able to use a Microsoft Authentication.
I want to find a nice way to use windows authentication inside a domain at the customer. Since the end application must be able to connect to Data cubes preferably using a connection string.
Data cubes using an IIS server that allows for HTTP connection using SOAP will not always be available depending on the costumer set-up.
Also the desire to build the application on multiple platforms makes it hard to add custom library's if there even is a custom library for this request since I haven't been able to find one yet.
My current less fortunate side options are:
Build an extra windows application with visual studio that query's the data and parses it to Unity (But requires and extra application to
run).
Use the http SOAP connection with an IIS service (But requires the analysis server to be set-up with IIS which isn't always possible depending on the customer).
Find a library that allows me to use Microsoft Authentication (but probably only works on the windows platform, or doesn't work with Unity).
I'm hoping someone has already found or maybe knows a good solution that works for Unity without giving the limitations I've mentioned above.
I am using the Microsoft.AnalysisServices.AdomdClient; with visual studio that works fine for visual studio build but doesn't work in monodevelop in unity.
try
{
using (AdomdConnection adcon = new AdomdConnection(connectionString))
{
adcon.Open();
using (AdomdCommand adcmd = adcon.CreateCommand())
{
adcmd.CommandText = textBox3.Text.ToString();
AdomdDataReader dr = adcmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount; i++)
textBox2.AppendText(dr[i] + (i == dr.FieldCount - 1 ? "" : ", ") + Environment.NewLine);
}
dr.Close();
textBox2.AppendText(adcmd.CommandText.ToString() + Environment.NewLine + Environment.NewLine);
adcmd.Connection.Close();
}
adcon.Close();
}
}
catch(Exception e)
{
textBox2.AppendText(e.ToString() + Environment.NewLine);
}
Thank you for any suggestions, feedback or answers!
Something you could try would be using the relational SQL Server engine as a kind of proxy. The relational SQL Server engine should be available whereever Analysis Services is available.
You could set up a linked server in the relational SQL Server which links to the Analysis Services server using the Analysis Services OLEDB client. How to set up linked servers is described here.
Then you can send MDX to this linked server, and get back the results in the relational engine like this:
select * from openquery(AdventureWorksOLAP,
'select [Measures].[Sales Amount] on columns from [Adventure Works]')
where AdventureWorksOLAP is the name of your linked server.
However, you should be aware that the column names are strange (containing closing square brackets, which need to be escaped within the square brackets enclosing column names by doubling). E. g. the above query would have a column that you have to access as [[Measures]].[Sales Amount]]]. Furthermore, all cell values come back as nvarchar and might need to be casted to a numeric type in order to work with them.
Maybe you could encapsulate the column name changing and column typecasting into a stored procedure.
And you could use SQL server authentication to access the relational database.
I am creating a application and I want to use a local database stored on the clients local machines. I am debating over if I should use SQLITE or is there something in Visual Studio to help me. The other thing is that I want to create the database programmatically in the users directory when the application is launched.
I am see a few things online but the articles were all about SQL Server stuff and that is not want I want to do with this application. All data will need to be stored on the local machine.
You can use SQL Server Compact, which has tooling in Visual Studio. It's syntax-compatible with SQL Server, but stores its data in a local file, which you can create on the fly (at app startup, for example).
You can create the SQLite database on the fly with the libraries provided from their website. I have used it in many projects for my personal code, as well as it being used in some of the internal architecture of Data Explorer (IBM Product). Some sample C# to create a database file:
if (!Directory.Exists(Application.StartupPath + "\\data"))
{
Directory.CreateDirectory(Application.StartupPath + "\\data");
}
SQLiteConnection conGlobal;
if (!File.Exists(dbGlobal))
{
conGlobal = new SQLiteConnection("Data Source=" + dbGlobal + ";New=True;Compress=True;PRAGMA synchronous = 1;PRAGMA journal_mode=WAL");
conGlobal.SetExtendedResultCodes(true);
firstRun = true;
}
else
{
conGlobal = new SQLiteConnection("Data Source=" + dbGlobal + ";Compress=True;PRAGMA synchronous = 1;PRAGMA journal_mode=WAL");
conGlobal.SetExtendedResultCodes(true);
}
try
{
conGlobal.Open();
}
catch (Exception)
{
//do stuff
}
Simply initiating a connection to the file will create it if the new=true is passed as the connection string. Then you can query it and get results just like you would any database.
You also have the ability to password protect the database files to prevent access to them from just opening them with an SQLite-Shell or a different SQLite DB viewer.
For more info on the pragma statements that are being passed in the connection string, see the following: http://www.sqlite.org/pragma.html
I'm not sure about programmatically (that's probably what you meant, right?) creating the database, but SQL Server Compact Edition has served me well in the past for simple apps. It's embedded and even runs in medium trust.
I want to achieve the following programatically using C#.
Query components installed in SQL Server 2008
e.g
Upgrade Tools
Debug Symbols
Replication Support
Books Online
Development Tools
I have tried using SMO API for SQL Server tried to query Information Collection as well Configuration collection but could not find the any of the above three points.
I need to be able to programmatically determine which SQL Server 2008 components are installed and which are not installed, just like SQL Server Installation setup which first checks to see which components are installed.
One way is to query SQL Server Installation Log File, but it is not helpful if SQL Server is completely no there or if someone has deleted that log file.
I need to reliably determine the installed SQL Server components
Please help.
Thanks
Steve
Your best bet is probably to query Win32_Product via WMI. You can use WMI Code Creator v1.0 to help you create an appropriate query. You can also see WQL (SQL for WMI) for information on the supported query syntax and ManagementObjectSearcher Class.
Something like this should do the trick:
using System;
using System.Management;
using System.Windows.Forms;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
ManagementObjectSearcher searcher =
new ManagementObjectSearcher("root\\CIMV2",
"SELECT * FROM Win32_Product WHERE Name LIKE '%SQL%'");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_Product instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("InstallDate: {0}", queryObj["InstallDate"]);
Console.WriteLine("InstallLocation: {0}", queryObj["InstallLocation"]);
Console.WriteLine("Name: {0}", queryObj["Name"]);
Console.WriteLine("SKUNumber: {0}", queryObj["SKUNumber"]);
Console.WriteLine("Vendor: {0}", queryObj["Vendor"]);
Console.WriteLine("Version: {0}", queryObj["Version"]);
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}
}
}
Upgrade Tools ends with Upgrade Advisor
Debug Symbols are pulled from a symbol server on demand by certain applications and don't show up in Win32_Products.
Replication Support does not appear to be detectable via a plain WMI query to Win32_Products
Books Online ends with Books Online (English)
Development Tools ends with BI Development Studio
You can find out about installed features by running the SQL Server Setup Discovery Report (requires admin privileges):
Go to the Start menu
Click All Programs
Click Microsoft SQL Server
Click Configuration Tools
Click SQL Server Installation Center
Click the Tools section link
Click Installed SQL Server features discovery report
You can also create the report from a command line by running setup.exe /ACTION=RUNDISCOVERY /Q (from C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\SQLServer2008R2 in the case of SQL Server 2008 R2). The report files will typically be in C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log\YYYYMMDD_HHmmSS, where YYYYMMDD_HHmmSS is the date and time the report was run. SqlDiscoveryReport.xml is probably the one most useful for consuming programmatically. Be aware that these locations can vary somewhat based on the install location the user chooses during the initial setup and the version of SQL Server.
Avoid Win_32 Product, see here.
Use CreateObject("WindowsInstaller.Installer") instead.
I created a small accounting application a while back. It uses SQL Server 2008 as backend data store. Now I realize that SQL Server is too much for such a
small program PLUS it is not very much portable. I mean I want to have this application on my USB stick for easy access anywhere, and SQL Server will not be
available everywhere. So now I want to replace the data store from SQL Server to something portable i.e. MS Access MDB file.
1- Is it a good option or should I use SQL Server express edition?
2- I don't have experience using SQL Express edition. If I use it, would it be needed on any machine where I intend to run my application?
2- What changes should I make in the code to make it compatioble with MDF files (or SQL Express)?
As I said it is quite simple program, it uses connected model to fetch and insert data currently. For example
void bindGrid()
{
try
{
using (SqlConnection con = new SqlConnection(ConnectionString))
{
DataSet set = new DataSet();
SqlDataAdapter da = new SqlDataAdapter();
SqlCommand selectCommand = new SqlCommand("SELECT * FROM Categories ORDER BY name", con);
da.SelectCommand = selectCommand;
da.Fill(set);
this.grdCategories.DataSource = set.Tables[0];
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Rather than using Access, I would use LocalDB. It should require very few if any changes to your code other than the connection string.
http://blogs.msdn.com/b/sqlexpress/archive/2011/07/12/introducing-localdb-a-better-sql-express.aspx
LocalDB is created specifically for developers. It is very easy to install and requires no management, yet it offers the same T-SQL language, programming surface and client-side providers as the regular SQL Server Express. In effect the developers that target SQL Server no longer have to install and manage a full instance of SQL Server Express on their laptops and other development machines. Moreover, if the simplicity (and limitations) of LocalDB fit the needs of the target application environment, developers can continue using it in production, as LocalDB makes a pretty good embedded database too.
I would recommend SQL CE for small projects.
LocalDB vs SQL Server Compact
There are significant differences between LocalDB and SQL Server Compact:
Execution mode: SQL Server Compact is an in-proc DLL, while LocalDB runs as a separate process.
Disk usage: all SQL Server Compact binaries amount to some 4MBs, while LocalDB installation takes 140MBs.
Features: SQL Server Compact offers core RDBMS functionality like querying, while LocalDB provides a much richer set of features, including Stored Procedures, Geometry and Geography data types, etc.
I am using 64-bit Windows Server 2008 with SQL Server 2008. And Using VS2008 + C# + .Net 2.0 + IIS 7.0 + ASP.Net. When executing the following statement, I met with the following error (the error occurs when accessing an aspx page), I am not sure whether it is 64-bit system specific issue?
Sys.WebForms.PageRequestManagerServerErrorException: unregistered OLE DB access interface "Microsoft.Jet.OLEDB.4.0"
StringBuilder sb = new StringBuilder();
sb.AppendLine("select * from OPENROWSET('MICROSOFT.JET.OLEDB.4.0','Excel 8.0;HDR=YES;DATABASE=" + s_path.Trim() + "',sheet1$) where name is not null"); //e:\\test1.xls
DataSet ds = SqlUtil.ExecuteDataset(Database.StrConn, CommandType.Text, sb.ToString());
if (ds.Tables[0].Rows.Count > 0)
{
GridView_Tlinkmans.DataSource = ds;
GridView_Tlinkmans.DataBind();
}
You have one or 2 issues:
You are querying OPENROWSET in SQL Server and you have x64 SQL Server, you may need the MDAC to bridge SQL Server to ODBC/OLEDB. However, this says it is part of the OS for Win 2008+. I've had to install on Win 2003
Then you probably need this which is the closest to JET I know of: Microsoft Access Database Engine 2010 Redistributable
YMMV