Failure to create a SQL Azure login with SMO - sql

The following piece of code works with regular SQL and SMO. I'm trying to get it to work with SQL Azure. According to this MSDN article, a limited subset of functionality that I need (database and login creation) should be supported. All the business checking whether an object exists will also fail: server.Logins[loginName] != null or server.Databases.Contains(dbName). I can create a database if I dont check whether it exists or not, but i cant create a login. Anyone else ran into the same problem?
string connectionString =
"Server=tcp:XXXXXX.database.windows.net;Database=MyDatabase;User ID=XXXXXXX;Password=XXXXXX;Trusted_Connection=False;Encrypt=True;TrustServerCertificate=true;"
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
ServerConnection serverConnection = new ServerConnection(connection);
Server server = new Server(serverConnection);
Login login = new Login(server, "NewLogin");
login.LoginType = LoginType.SqlLogin;
login.Create("NewStrongPwd123***");
}
Create failed for Login 'NewLogin'.
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.CreateImpl()
at Microsoft.SqlServer.Management.Smo.Login.Create(SecureString password)
at Microsoft.SqlServer.Management.Smo.Login.Create(String password)

Proposed answers to this question were identified on the MSDN Forum including a working approach. Please take a look at: http://social.msdn.microsoft.com/Forums/en-US/ssdsgetstarted/thread/26e42082-e649-4cde-916d-c1da2275e377

Related

Create a Sql Azure Database with serverless tier using SDK

Currently, I create databases and attach them to an SQL elastic pool:
database = await sqlServer.Databases.Define(mainDb.DbName).WithExistingElasticPool(pool.Name).CreateAsync();
Instead, I want to create databases with tier "General Purpose: Serverless, Gen5, 1 vCore", but I couldn't find any method that offers that possibility.
This feature is still in preview, I can't find anything on the forums on this. How can I achieve this?
As an addendum to #Jim Xu accepted answer, the API has changed.
var database = sqlserver.Databases.Define("test").WithEdition("GeneralPurpose").WithServiceObjective("GP_S_Gen5_1").Create();
The WithEdition is now a DatabaseEdition edition type, and WithServiceObjective is now a ServiceObjectiveName. Both of these are muddled string enums with lists of version types. They do both also accept a .Parse() method. So the line should now be:
var database = sqlserver.Databases.Define("test")
.WithEdition(**Database.Edition.Parse("GeneralPurpose")**)
.WithServiceObjective(**ServiceObjectiveName.Parse("GP_S_Gen5_1")**)
.Create();
According to my test, we can use the following c# code to create "General Purpose: Serverless, Gen5, 1 vCore" database
var credentials = SdkContext.AzureCredentialsFactory.FromServicePrincipal(client,key,tenant,AzureEnvironment.AzureGlobalCloud);
var azure = Azure.Configure().Authenticate(credentials).WithSubscription(SubscriptionId);
var sqlserver=azure.SqlServers.GetById("/subscriptions/<your subscrption id>/resourceGroups/<your resource group name>/providers/Microsoft.Sql/servers/<your server name>");
var database = sqlserver.Databases.Define("test").WithEdition("GeneralPurpose").WithServiceObjective("GP_S_Gen5_1").Create();
Console.WriteLine(database.ServiceLevelObjective);
Console.WriteLine(database.Edition);
Console.WriteLine(database.Name);
Console.ReadLine();
Please reference this tutorial: Create a new elastic database pool with C#.
It provides the code example about Create a new database in a pool:
Create a DataBaseCreateorUpdateProperties instance, and set the properties of the new database. Then call the CreateOrUpdate method with the resource group, server name, and new database name.
// Create a database: configure create or update parameters and properties explicitly
DatabaseCreateOrUpdateParameters newPooledDatabaseParameters = new DatabaseCreateOrUpdateParameters()
{
Location = currentServer.Location,
Properties = new DatabaseCreateOrUpdateProperties()
{
Edition = "Standard",
RequestedServiceObjectiveName = "ElasticPool",
ElasticPoolName = "ElasticPool1",
MaxSizeBytes = 268435456000, // 250 GB,
Collation = "SQL_Latin1_General_CP1_CI_AS"
}
};
var poolDbResponse = sqlClient.Databases.CreateOrUpdate("resourcegroup-name", "server-name", "Database2", newPooledDatabaseParameters);
Please try to replace "standard" with the price tier "General Purpose: Serverless, Gen5, 1 vCore".
Hope this helps.

How to stored Emails in SQL database and queried in an ASP.NET Application

I'm creating a backup monitoring application that I am going to write in Visual Studio using ASP.NET.
The way I would like this to work is backup emails being sent from the server that has a backup monitoring solution and are stored in a SQL database (SQL Server Express, MySQL) whatever would be best for something like this. I then plan to use this data to query and show statistics such as what servers have backed up successfully for each customer, and those that have failed. Also what servers have backed up successfully most and error trends such as not enough disk space etc.
Would this be possible and if so could someone point me in the right direction wither I should start trying to get information into a database first and foremost and how to achieve that or should I start by creating the application such as login, dashboard etc. I haven't got a strong programming background we covered some Visual Basic and ASP.NET in university and I was hoping to learn a lot from this project.
I was thinking of setting up a test environment with a server running a backup product and purposely making backups fail for testing and have access to the hardware/software resources working for an IT Consultancy / Support company.
Thanks in advance!
After some searching I came across this website which has a great piece of code that reads emails from an inbox such as Gmail and stores them in an SQL database.
protected void SaveEmails(object sender, EventArgs e)
{
for (int i = 0; i < this.Emails.Count; i++)
{
string constr = ConfigurationManager.ConnectionStrings["ConString2"].ConnectionString;
string sqlStatment = "INSERT INTO [Emails] ([From],[Subject],[Body],[Date]) VALUES (#From ,#Subject,#Body,#Date)";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sqlStatment, con))
{
con.Open();
cmd.Parameters.AddWithValue("#From", this.Emails[i].From);
cmd.Parameters.AddWithValue("#Subject", this.Emails[i].Subject);
cmd.Parameters.AddWithValue("#Body", this.Emails[i].Body);
cmd.Parameters.AddWithValue("#Date", this.Emails[i].DateSent);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
For the architecture of this you can try creating something like this:
External systems: Will write to the sql database
Database: Only needs one table. With possibly these columns (to give you an idea)
Receiver
Sender
IsSent
BodyMessage
SentTime
Sender: A sender application/service that will query the database at regular intervals for unsent emails and send them.
If you wonder how you technically query and insert into a SQL database then that's something there are plenty of resources on.

Trouble establishing connection to Local SQL database

Simply trying to find out the correct syntax for my connection string. Before anyone asks, yes I did look at other SO answers, and no they did not work for me. Here a couple of attempts I made from looking at other SO questions like the one I am asking
Server=(local);Database=SalesOrdersExample;Integrated Security= true
Data Source=(local);Database=SalesOrdersExample;Integrated Security=SSPI
Server=.\\SQLEXPRESS;Database=SalesOrdersExampleDataSet;Integrated Security=true
None of them worked (I have a Console.WriteLine("test"); thrown in there and it works up until I try conn.Open() (opening the connection to database) so I'm assuming that it must be my connection string since nothing gets written after conn.Open())
Console.WriteLine("test"); // works
SqlConnection conn = new SqlConnection("Server=.\\SQLEXPRESS;Database=SalesOrdersExampleDataSet;Integrated Security=true");
Console.WriteLine("test"); // works
conn.Open();
Console.WriteLine("test"); // does not work
So some information about the database is that it's local under my 'Data Connections' in my Server Explorer. I also have the .xsd file in my project so I have linked the Data Set to the current project I am on. Here is a picture representation to confirm that I have both the Data Connection and the Data Set.
EDIT: SO does not allow me to post pictures until I have 10 rep so here is direct link to picture:
DB Screenshot
Any help is appreciated thank you.
Visual Studio comes with LocalDB database, which is not exactly SQL Server Express database.
Try something like this:
Server=(localdb)\v11.0;Integrated Security=true;
or
Data Source=(LocalDB)\v11.0; AttachDbFileName=|DataDirectory|\DatabaseFileName.mdf; InitialCatalog=DatabaseName;Integrated Security=True;MultipleActiveResultSets=True
If using in c# code, you can use # to avoid problems with backslash characters:
SqlConnection conn =
new SqlConnection(#"Server=(localdb)\v11.0;Integrated Security=true;");

Upload and Download error synchronizing Sql Server and Sql Azure - Sync Framework

I'm trying to synchronize an Sql Server database with SQL Azure Database (please be patient 'cause I don't fully understand Sync Framework). These are the requirements:
First: synchronize 1 table from Sql Azure to Sql Server
Second: synchronize 13 other tables (including the table I mentioned in the first step) from Sql Server to Azure.
I've created a console application, and this is the code:
1.I create one scope with the 13 tables:
DbSyncScopeDescription myScope = new DbSyncScopeDescription("alltablesyncgroup");
DbSyncTableDescription table = qlSyncDescriptionBuilder.GetDescriptionForTable("tablename", sqlServerConn);
myScope.Tables.Add(table); //repeated 13 times.
2.I Provision both data bases:
SqlSyncScopeProvisioning sqlAzureProv = new SqlSyncScopeProvisioning(sqlAzureConn,myScope);
if (!sqlAzureProv.ScopeExists("alltablesyncgroup"))
{
sqlAzureProv.Apply();
}
SqlSyncScopeProvisioning sqlServerProv = new SqlSyncScopeProvisioning(sqlServerConn, myScope);
if (!sqlServerProv.ScopeExists("alltablesyncgroup"))
{
sqlServerProv.Apply();
}
3.I create the SyncOrchestrator with the SyncDirectionOrder.Download to sync the firts table:
SqlConnection sqlServerConn = new SqlConnection(sqllocalConnectionString);
SqlConnection sqlAzureConn = new SqlConnection(sqlazureConnectionString);
SyncOrchestrator orch = new SyncOrchestrator
{
RemoteProvider = new SqlSyncProvider(scopeName, sqlAzureConn),
LocalProvider = new SqlSyncProvider(scopeName, sqlServerConn),
Direction = SyncDirectionOrder.Download
};
orch.Synchronize();
4.Later, I use the same function only changing the direction SyncDirectionOrder.Upload to sync the 13 remaining tables
SqlConnection sqlServerConn = new SqlConnection(sqllocalConnectionString);
SqlConnection sqlAzureConn = new SqlConnection(sqlazureConnectionString);
SyncOrchestrator orch = new SyncOrchestrator
{
RemoteProvider = new SqlSyncProvider(scopeName, sqlAzureConn),
LocalProvider = new SqlSyncProvider(scopeName, sqlServerConn),
Direction = SyncDirectionOrder.Upload
};
orch.Synchronize();
Now, here is the thing, obviously I'm doing it wrong 'cause when I download, the syncStats shows that a lot of change have been applied BUT I can't see it reflected on any data base and when I try to execute the Upload sync it seems to be going into a loop 'cause the Upload process doesn't stop.
Thanks!!!
first, you mentioned you only want to sync one table from Azure to your SQL Server but you're provisioning 13 tables in the scope. if you want one table, just provision a scope with one table. (e.g. one scope for the download with table, one scope for the upload with the rest of the tables)
to find out why rows are not synching, you can subscribe to the ApplyChangeFailed event for both sides, and check if there are conflicts or errors being encountered.
or you can enable Sync Framework tracing in verbose mode so you can see what's happening underneath.

Creating new database in code, RavenDB

I'm running RavenDB.Client 2.0.2173-Unstable. I'm creating a multi-tenant system, and as part of my registration process, i would like to create a new Raven database.
I have three simple lines of code..
string newDBName = "1234";
IDocumentStore documentStore = new DocumentStore { Url = "http://myserver:8080", DefaultDatabase = newDbName};
documentStore.Initialize();
documentStore.DatabaseCommands.EnsureDatabaseExists(newDBName);
Per suggestion, I also tried this:
string newDBName = "1234";
IDocumentStore documentStore = new DocumentStore { Url = "http://myserver:8080"};
documentStore.Initialize();
documentStore.DatabaseCommands.EnsureDatabaseExists(newDBName);
I get an InvalidOperationException on the last line, Raven is telling me it could not figure out what to do.
<h1>Could not figure out what to do</h1>
<p>Your request didn't match anything that Raven knows to do, sorry...</p>
I know my connection/server works, because I'm able to read/write from the default database.
Is it a permissions issue?
You can't create a database from the database you're already in. Leave the DefaultDatabase field blank so you connect to the RavenDB system database. You should then be able to create the new tenant database.
You should also make sure to pass the tenant database name when opening sessions, creating indexes, and using DatabaseCommands.
In Ravendb v4, you can use the CreateDatabaseOperation to create a new database on the server.
store.Maintenance.Server.Send(
new CreateDatabaseOperation(new DatabaseRecord("MyNewDatabase")));